How do I resolve API Gateway "malformed Lambda proxy response" errors or 502 status codes?

Last updated: 2020-10-30

I configured Amazon API Gateway proxy integration to work with an AWS Lambda function. When I call my API, I receive a configuration error or a 502 status code. How can I resolve this?

Short description

The format of the Lambda function's response is often the source of these errors. If the format is the problem, then you see a message that looks like this in the logs:

Thu Dec 08 01:13:00 UTC 2016 : Execution failed due to configuration error: Malformed Lambda proxy response
Thu Dec 08 01:13:00 UTC 2016 : Method completed with status: 502

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": "..."
}

Resolution

  1. Review the logging output from the API Gateway console, or view the API Gateway log events in the Amazon CloudWatch console.
  2. In the logs, check the format of your Lambda function's response to your API. If the response isn't JSON in the correct format, then reformat it.

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);
};

Note: If your function is written in another programming language, refer to that language's programming reference. Confirm that the function returns a response in the correct format.

In this response, there are four fields: statusCode, headers, body, and isBase64Encoded.

  • The statusCode is an integer interpreted by API Gateway that's returned to the caller of the API method.
  • The headers are collected and then sent back with the API Gateway response.
  • The body field, if you're returning JSON, must be converted to a string to prevent further problems with the response. Use JSON.stringify to handle this in Node.js functions. Other runtimes require different solutions, but the concept is the same.
  • The isBase64Encoded field is important if you're working with binary data. If you don't use this field, it's a best practice to set this to a Boolean value of FALSE.