How to Fix Malformed Lambda Proxy Response

If you have a Lambda proxy integration with API Gateway, and are receiving a malformed Lambda proxy response error, you can fix it by ensuring your Lambda function’s response has the correct format.

To help you do that is the checklist below. A malformed Lambda proxy response error message implies a formatting error within the output of your Lambda function. Completing the following checklist ensures that output is formatted properly, resolving the 502 error.

(Note: If you know your payloadFormatVersion, and you use version 1.0, you can skip to the 5th item on the checklist. Otherwise, it’s likely that you have version 2.0 and can start at the beginning.)


The Checklist

1. The response of the Lambda function must use the JSON object literal formatting:

{
    ...
}

2. That response can only have the following attributes:

{
    "statusCode": "...",
    "cookies": [...],
    "isBase64Encoded": ...,
    "headers": {...},
    "body": "..."
}

Including any other attribute within the function’s response will produce a configuration error.

3. You don’t have to use all the attribute keys. The API Gateway can make assumptions if you don’t use a certain key.

4. The values of the keys must take a certain format. For example, the status code must be a valid http status code. Here is the complete list of each value’s format requirements:

{
    "statusCode": httpStatusCode,
    "cookies": ["Cookie", "AnotherCookie"],
    "isBase64Encoded": true | false,
    "headers": {
        "x-custom-header": "header value"
    },
    "body": "a string"
}

*If you return a JSON object in the body, the JSON has to be stringified. (some helpful methods: JSON.stringify in Node, JSON.dumps in Python)
** The headers attribute is for your custom (non-standard) response headers.

5. The above 4 requisites should fix your 502 error. In case you’re still getting the same configuration error message, you could have payloadFormatVersion 1.0. In that case, your Lambda function’s response must use the format specified in the documentation:

{
    "statusCode": httpStatusCode,
    "headers": {
        "x-header-name": "header value"
    },
    "multiValueHeaders": { "header1": ["value1"] },
    "body": "a string"
}

The malformed Lambda proxy response error should be gone by now! If it hasn’t, please let me know. If you’re interested in the details of Lambda proxy integration, you can visit its documentation here.



Leave a Comment