How do I resolve HTTP 502 "Malformed Lambda proxy response" errors from API Gateway REST APIs?

Last updated: 2021-11-18

I configured Amazon API Gateway proxy integration to work with an AWS Lambda function. When I call my REST API, I receive a configuration error and an HTTP 502 status code. How do I resolve the issue?

Short description

If your Lambda function's response to the API request isn't formatted correctly, API Gateway returns an HTTP 502 status code.

Example HTTP 502 "Malformed Lambda proxy response" error message as it appears in Amazon CloudWatch 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 function must return output according to the following JSON format:

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

Resolution

1.    Review your REST API's CloudWatch metrics with the API dashboard in API Gateway.
-or-
Review your REST API's log events in the Amazon CloudWatch console.

2.    In the logs, review the format of your Lambda function's response to your API. If the response isn't in the required JSON format, then reformat it.

3.    Test your REST API method in the API Gateway console.

Example Node.js Lambda function with the response correctly formatted

Note: Node.js Lambda functions support async handlers and non-async handlers. The following example function uses an async handler.

exports.handler = async (event) => {

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

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

    return response;
};

In this example response, there are four fields:

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