148

I am trying to set up a hello world example with AWS lambda and serving it through api gateway. I clicked the "Create a Lambda Function", which set up the api gatway and selected the Blank Function option. I added the lambda function found on AWS gateway getting started guide:

exports.handler = function(event, context, callback) {
  callback(null, {"Hello":"World"});  // SUCCESS with message
};

The issue is that when I make a GET request to it, it's returning back a 502 response { "message": "Internal server error" }. And the logs say "Execution failed due to configuration error: Malformed Lambda proxy response".

1
  • 1
    tldr; the body of the json response must be stringified. Commented Dec 25, 2022 at 16:30

19 Answers 19

191

Usually, when you see Malformed Lambda proxy response, it means your response from your Lambda function doesn't match the format API Gateway is expecting, like this

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "body": "..."
}

If you are not using Lambda proxy integration, you can login to API Gateway console and uncheck the Lambda proxy integration checkbox.

Also, if you are seeing intermittent Malformed Lambda proxy response, it might mean the request to your Lambda function has been throttled by Lambda, and you need to request a concurrent execution limit increase on the Lambda function.

7
80

If lambda is used as a proxy then the response format should be

{
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"body": "..."
}

Note : The body should be stringified

7
  • If "response" is the name of your object, using JSON.stringify(response) does not work. Leaving it like this worked for me. callback(null,response);
    – Neo
    Commented Aug 31, 2017 at 22:43
  • 5
    @Neo You don't need to stringify the response object. You need to stringify the data inside the body key of response object Commented Sep 1, 2017 at 7:30
  • 5
    Of these, only statusCode is required for a call from API Gateway to succeed.
    – Trenton
    Commented Feb 16, 2018 at 1:47
  • 2
    Ensuring the body is stringified worked for me. Thanks a lot +1
    – Kimutai
    Commented May 3, 2019 at 8:08
  • 2
    The body should be stringified OMG thanks for that Commented Jul 1, 2020 at 23:23
31

Yeah so I think this is because you're not actually returning a proper http response there which is why you're getting the error.

personally I use a set of functions like so:

    module.exports = {
        success: (result) => {
            return {
                statusCode: 200,
                headers: {
                    "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
                    "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
                },
                body: JSON.stringify(result),
            }
        },
        internalServerError: (msg) => {
            return {
                statusCode: 500,
                headers: {
                    "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
                    "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
                },
                body: JSON.stringify({
                    statusCode: 500,
                    error: 'Internal Server Error',
                    internalError: JSON.stringify(msg),
                }),
            }
        }
} // add more responses here.

Then you simply do:

var responder = require('responder')

// some code

callback(null, responder.success({ message: 'hello world'}))
2
  • 1
    Now, if we use Access-Control-Allow-Credentials value as true,we cant keep 'Access-Control-Allow-Origin' value as '*' Commented Jun 9, 2019 at 1:31
  • 1
    I observed it supports only one Origin: headers: { "Access-Control-Allow-Origin" : "<<Single Domain>>", "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS }, Commented Jun 12, 2019 at 11:05
26

For Python3:

import json

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        'body': json.dumps({
            'success': True
        }),
        "isBase64Encoded": False
    }

Note the body isn't required to be set, it can just be empty:

        'body': ''
0
26

Your Node.js handlers need to either return a Promise or use the callback function.

I had this issue, which originated from an invalid handler code which looks completely fine:

exports.handler = (event, context) => {
    return {
       isBase64Encoded: false,
       body: JSON.stringify({ foo: "bar" }),
       headers: {
          'Access-Control-Allow-Origin': '*',
       },
       statusCode: 200,
    };
}

This handler was previously declared async without ever using await, so I removed the async keyword without realizing that Lambda expects your handler function to either return a Promise (async/await) or call the callback.

I got the hint from examining the somewhat confusing API Gateway response logs:

> Endpoint response body before transformations: null

The way to fix it would be to either

  • Return a Promise:
exports.handler = (event, context) => {
    return new Promise((resolve) => resolve({
        isBase64Encoded: false,
        body: JSON.stringify({ foo: "bar" }),
        headers: {
            'Access-Control-Allow-Origin': '*',
        },
        statusCode: 200,
    }));
}
  • Use the callback:
exports.handler = (event, context, callback) => {
    callback({
        isBase64Encoded: false,
        body: JSON.stringify({ foo: "bar" }),
        headers: {
            'Access-Control-Allow-Origin': '*',
        },
        statusCode: 200,
    });
}
  • Add the async keyword (async function implicitly returns a Promise), I would NOT recommend this approach, since some other developer or IDE refactor tool will come along and remove the supposedly unnecessary async:
exports.handler = async (event, context) => {
    return {
        isBase64Encoded: false,
        body: JSON.stringify({ foo: "bar" }),
        headers: {
            'Access-Control-Allow-Origin': '*',
        },
        statusCode: 200,
    };
}
2
  • 3
    I did the exact same thing - removed async as I removed the await and started hitting the exact same issue! Your post really helped. Thanks!
    – Vimanyu
    Commented May 12, 2021 at 17:37
  • 💯💯💯💯💯💯💯💯💯 Commented Sep 1, 2023 at 1:34
7

From the AWS docs

In a Lambda function in Node.js, To return a successful response, call callback(null, {"statusCode": 200, "body": "results"}). To throw an exception, call callback(new Error('internal server error')). For a client-side error, e.g., a required parameter is missing, you can call callback(null, {"statusCode": 400, "body": "Missing parameters of ..."}) to return the error without throwing an exception.

7

Just a piece of code for .net core and C# :

using Amazon.Lambda.APIGatewayEvents;
...
var response = new APIGatewayProxyResponse
{
   StatusCode = (int)HttpStatusCode.OK,
   Body = JsonConvert.SerializeObject(new { msg = "Welcome to Belarus! :)" }),
   Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
};
return response;

Response from lambda will be :

{"statusCode":200,"headers":{"Content-Type":"application/json"},"multiValueHeaders":null,"body":"{\"msg\":\"Welcome to Belarus! :)\"}","isBase64Encoded":false}

Response from api gateway will be :

{"msg":"Welcome to Belarus! :)"}
1
  • 2
    OMG, thank you so much, you just saved me after hours of trying to figure out how to freakin get a header in the response. I tried plain JSON, didn't work. I tried key value pairs, didn't work. Dictionary was the way to go! THANK YOU!
    – Misha
    Commented Mar 27, 2020 at 22:10
6

I've tried all of above suggestion but it doesn't work while body value is not String

return {
    statusCode: 200,
    headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*"
    },
    body: JSON.stringify({
        success: true
    }),
    isBase64Encoded: false
};
5

For anyone else who struggles when the response appears valid. This does not work:

callback(null,JSON.stringify( {
  isBase64Encoded: false,
  statusCode: 200,
  headers: { 'headerName': 'headerValue' },
  body: 'hello world'
})

but this does:

callback(null,JSON.stringify( {
  'isBase64Encoded': false,
  'statusCode': 200,
  'headers': { 'headerName': 'headerValue' },
  'body': 'hello world'
})

Also, it appears that no extra keys are allowed to be present on the response object.

4

A very very special case, if you pass the headers directly there is a chance you have this header:

"set-cookie": [ "........" ]

But Amazon needs this:

"set-cookie": "[ \\"........\\" ]"

4

If you're using AWS Lambda for Go , you have to use events.APIGatewayProxyResponse.

func hello(ctx context.Context, event ImageEditorEvent) (events.APIGatewayProxyResponse, error) {
    return events.APIGatewayProxyResponse{
        IsBase64Encoded: false,
        StatusCode:      200,
        Headers:         headers,
        Body:            body,
    }, nil
}
2

Most likely your returning body is in JSON format, but only STRING format is allowed for Lambda proxy integration with API Gateway.

So wrap your old response body with JSON.stringify().

2

I had this error because I accidentally removed the variable ServerlessExpressLambdaFunctionName from the CloudFormation AWS::Serverless::Api resource. The context here is Serverless Express by Vendia "Run serverless applications and REST APIs using your existing Node.js application framework, on top of AWS Lambda and Amazon API Gateway"

0

In case the above doesn't work for anyone, I ran into this error despite setting the response variable correctly.

I was making a call to an RDS database in my function. It turned out that what was causing the problem was the security group rules (inbound) on that database.

You'll probably want to restrict the IP addresses that can access the API, but if you want to get it working quick / dirty to test out if that change fixes it you can set it to accept all like so (you can also set the range on the ports to accept all ports too, but I didn't do that in this example):

enter image description here

0

A common cause of the "Malformed Lambda proxy response" error is headers that are not {String: String, ...} key/values pairs.

Since set-cookie headers can and do appear in multiples, they are represented in http.request.callback.response as the set-cookie key having an Array of Strings value instead of a single String. While this works for developers, AWS API Gateway doesn't understand it and throws a "Malformed Lambda proxy response" error.

My solution is to do something like this:

function createHeaders(headers) {
  const singleValueHeaders = {}
  const multiValueHeaders = {}
  Object.entries(headers).forEach(([key, value]) => {
    const targetHeaders = Array.isArray(value) ? multiValueHeaders : singleValueHeaders
    Object.assign(targetHeaders, { [key]: value })
  })

  return {
    headers: singleValueHeaders,
    multiValueHeaders,
  }
}

var output = {
  ...{
    "statusCode": response.statusCode,
    "body": responseString
  },
  ...createHeaders(response.headers)
}

Note that the ... above does not mean Yada Yada Yada. It's the ES6 spread operator.

0

Here's another approach. Configure the mapping template in your API gateway integration request and response. Go to IntegrationRequest -> MappingTemplate -> select "When there are no templates defined" -> type application/json for content-type. Then you don't have to explicitly send a json. Even the response you get at your client can be a plain string.

0

Python 3.7

Before

{
    "isBase64Encoded": False,
    "statusCode": response.status_code,
    "headers": {
                  "Content-Type": "application/json",
               },
     "body": response.json()
}

After

{
    "isBase64Encoded": False,
    "statusCode": response.status_code,
    "headers": {
                  "Content-Type": "application/json",
               },
     "body": str(response.json()) //body must be of string type
}
0

If you're just new to AWS and just want your URL working,

If you haven't created a trigger for your Lambda Function, navigate to the function in Lambda Functions app and create trigger choosing API Gateway.

Navigate to API Gateway App -> Choose your Particular Lambda's API Gateway (Method execution) -> Click on INTEGRATION Request -> Uncheck "Use Lambda Proxy integration" (check box).

Then click on "<-Method Execution" & click on Test Client section. Provide the options and click test button. You should see a success response.

If you are still unable to get a success response, create an alias for the correct version (if you have multiple versions in the Lambda Function)

Pick the URL from the logs and use your POST/GET Tool (Postman) and choose authentication as AWS Signature - provide your authentication keys(AccessKey & SecretKey) in the postman request with AWS Region & Service Name as lambda.

P.S : This may only help beginners and may be irrelevant to others.

0

The format of your function response is the source of this error. For API Gateway to handle a Lambda function's response, the response must be JSON in this format:

{ "isBase64Encoded": true|false, "statusCode": httpStatusCode, "headers": { "headerName": "headerValue", ... }, "body": "..." }

Here's an example function in Node.js with the response correctly formatted:

exports.handler = (event, context, callback) => {

var responseBody = {
    "key3": "value3",
    "key2": "value2",
    "key1": "value1"
};

var response = {
    "statusCode": 200,
    "headers": {
        "my_header": "my_value"
    },
    "body": JSON.stringify(responseBody),
    "isBase64Encoded": false
};
callback(null, response);

};

Reference: How do I resolve HTTP 502 errors from API Gateway REST APIs with Lambda proxy integration?

Not the answer you're looking for? Browse other questions tagged or ask your own question.