Question

Difficulty: EasyTroubleshooting API Gateway Errors and CORS

A mobile application client receives a 502 Bad Gateway error when calling a REST API endpoint. The endpoint is configured with Amazon API Gateway using a Lambda Proxy integration. Upon reviewing the Amazon CloudWatch logs, the developer confirms that the backend Lambda function executed successfully and completed without timing out. Which of the following is the most likely cause of this error?

  1. A
    The REST API resource does not have CORS enabled, which blocked API Gateway from processing the backend response.
  2. The Lambda function is returning a raw string response instead of a JSON object containing the required statusCode field.Answer
  3. C
    The developer did not configure an integration response mapping template in API Gateway to convert the Lambda output.
  4. D
    The Lambda function's IAM execution role lacks the permissions to invoke the API Gateway endpoint.

Answer

The Lambda function is returning a raw string response instead of a JSON object containing the required statusCode field.
The correct answer is correct because under a Lambda Proxy integration, API Gateway expects the backend Lambda function to return a JSON object containing specific keys, including 'statusCode' and 'body'. If the function returns a raw text string, API Gateway fails to parse the output and returns a 502 Bad Gateway error to the client.

Step-by-Step Solution

1
Analyze the error symptoms and configuration.
The client gets a 502 Bad Gateway error, but the backend Lambda function (integrated via Lambda Proxy integration) executes successfully according to CloudWatch logs.
This indicates the connection from API Gateway to Lambda was successful, but API Gateway failed to process the response returned by Lambda.
2
Identify the response requirements for Lambda Proxy integration.
For Lambda Proxy integrations, API Gateway expects the backend Lambda function to return a JSON object with specific fields, such as 'statusCode', 'body', and 'headers'.
API Gateway relies on these fields to construct the HTTP response to the client.
3
Determine the cause of the failure.
If the Lambda function returns a raw string or JSON that does not match this format (e.g., missing the 'statusCode' field), API Gateway cannot parse it and returns a 502 Bad Gateway error.
The function executed successfully, so the issue must lie in the format of the returned payload.

Key Concept

API Gateway Lambda Proxy Integration response format requirements
Rate this question