question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

start-api ignores isBase64Encoded: true

See original GitHub issue

Description

When my function returns a base64 encoded body with isBase64Encoded: true, sam local start-api returns a response that is base64 encoded.

Steps to reproduce

Write a function

package main

import (
	"context"
	"encoding/base64"
	"net/http"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handle(ctx context.Context, r events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
	return events.APIGatewayProxyResponse{
		StatusCode:      http.StatusOK,
		Body:            base64.StdEncoding.EncodeToString([]byte("hello")),
		IsBase64Encoded: true,
	}, nil
}

func main() {
	lambda.Start(handle)
}

Define template

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  Function:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: build
      FunctionName: test
      Handler: main
      Runtime: go1.x
      Timeout: 3
      Events:
        Root:
          Type: Api
          Properties:
            Path: /
            Method: ANY
        CatchAll:
          Type: Api
          Properties:
            Path: /{proxy+}
            Method: ANY

Build function

GOOS=linux go build -o build/main .

Start sam

sam local start-api -t template.yml --skip-pull-image

Get the result

curl http://127.0.0.1:3000

Observed result

aGVsbG8=

Expected result

hello

Additional environment details (Ex: Windows, Mac, Amazon Linux etc)

  1. OS: Mac
  2. sam --version: SAM CLI, version 0.43.0

–debug output

Telemetry endpoint configured to be https://xxx
local start-api command is called
No Parameters detected in the template
2 resources found in the template
Found Serverless function with name='Function' and CodeUri='build'
No Parameters detected in the template
2 resources found in the template
Found '2' API Events in Serverless function with name 'Function'
Detected Inline Swagger definition
Lambda function integration not found in Swagger document at path='/' method='x-amazon-apigateway-any-method'
Lambda function integration not found in Swagger document at path='/{proxy+}' method='x-amazon-apigateway-any-method'
Found '0' APIs in resource 'ServerlessRestApi'
Removed duplicates from '0' Explicit APIs and '2' Implicit APIs to produce '2' APIs
2 APIs found in the template
Mounting Function at http://127.0.0.1:3000/ [DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT]
Mounting Function at http://127.0.0.1:3000/{proxy+} [DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT]
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template
Localhost server is starting up. Multi-threading = True
2020-02-27 17:25:58  * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
Constructed String representation of Event to invoke Lambda. Event: {"httpMethod": "GET", "body": null, "resource": "/", "requestContext": {"resourceId": "123456", "apiId": "1234567890", "resourcePath": "/", "httpMethod": "GET", "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", "accountId": "123456789012", "stage": "Prod", "identity": {"apiKey": null, "userArn": null, "cognitoAuthenticationType": null, "caller": null, "userAgent": "Custom User Agent String", "user": null, "cognitoIdentityPoolId": null, "cognitoAuthenticationProvider": null, "sourceIp": "127.0.0.1", "accountId": null}, "extendedRequestId": null, "path": "/"}, "queryStringParameters": null, "multiValueQueryStringParameters": null, "headers": {"Host": "127.0.0.1:3000", "User-Agent": "curl/7.54.0", "Accept": "*/*", "X-Forwarded-Proto": "http", "X-Forwarded-Port": "3000"}, "multiValueHeaders": {"Host": ["127.0.0.1:3000"], "User-Agent": ["curl/7.54.0"], "Accept": ["*/*"], "X-Forwarded-Proto": ["http"], "X-Forwarded-Port": ["3000"]}, "pathParameters": null, "stageVariables": null, "path": "/", "isBase64Encoded": false}
Found one Lambda function with name 'Function'
Invoking main (go1.x)
No environment variables found for function 'Function'
Environment variables overrides data is standard format
Loading AWS credentials from session with profile 'None'
Resolving code path. Cwd=/path, CodeUri=build
Resolved absolute path to code is /path/build
Code /path/build is not a zip/jar file
Skipping building an image since no layers were defined
Requested to skip pulling images ...

Mounting /path/build as /var/task:ro,delegated inside runtime container
Starting a timer for 3 seconds for function 'Function'
START RequestId: ba25691e-7a74-1f8f-bd6a-15527b27c20f Version: $LATEST
END RequestId: ba25691e-7a74-1f8f-bd6a-15527b27c20f
REPORT RequestId: ba25691e-7a74-1f8f-bd6a-15527b27c20f  Init Duration: 211.99 ms        Duration: 6.47 ms       Billed Duration: 100 ms   Memory Size: 128 MB     Max Memory Used: 22 MB
No Content-Type given. Defaulting to 'application/json'.
2020-02-27 17:26:05 127.0.0.1 - - [27/Feb/2020 17:26:05] "GET / HTTP/1.1" 200 -

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:5
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
shadow-lightcommented, Jul 10, 2021

Looks like this has been fixed in https://github.com/aws/aws-sam-cli/pull/2941

1reaction
stschwarkcommented, May 25, 2021

I ran into the same issue and my impression also is that SAM fails to find the returned Content-Type in the list of BinaryMediaTypes which is only available / required for AWS::Serverless::Api but not for AWS::Serverless::HttpApi. Would it be correct to conclude that sam local cannot currently be used to test endpoints that return base64 encoded binary content?

Read more comments on GitHub >

github_iconTop Results From Across the Web

start-api ignores isBase64Encoded: true · Issue #1826 - GitHub
When my function returns a base64 encoded body with isBase64Encoded: true, sam local start-api returns a response that is base64 encoded.
Read more >
Handling binary data using Amazon API Gateway HTTP APIs
"isBase64Encoded": true }. JSON. A Lambda function can inspect the isBase64Encoded flag and reverse the encoding to obtain the original data ...
Read more >
I recently migrated from Cloudflare Workers to AWS Lambda + ...
It ignores `isBase64Encoded` by some reason, and lambda just returns Base64 output, instead of binary. * And the main problem - local lambdas...
Read more >
How I moved Liftosaur from Cloudflare Workers to AWS Lambda
It has CLI to run the lambdas locally, sam local start-api . ... It ignores isBase64Encoded flag by some reason, and local lambda...
Read more >
AWS lambda :Malformed Lambda proxy response
The actual JSON response catptured in java app & lambda is {"statusCode":200,"isBase64Encoded":false}. AWS Collective.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found