5

I have created aws apigateway lambda integration for my proxy server. When i am making get request to the gateway, the request is successfully going through. The lambda function also executes successfully and writes response in outputstream with statusCode as 200. But apigateway always returns 502.

Snippet of handleRequest():

 BufferedReader reader = new BufferedReader(new 
        InputStreamReader(inputStream));
        JSONObject event = (JSONObject) parser.parse(reader);
        request = Input.builder().setEvent(event).build();

    Response response = requestManager.handleRequest(request);
    logger.log(String.format("Response [%s]", response.toString()));

    JSONObject responseJson = new JSONObject();
    responseJson.put("statusCode", response.getStatusCode());
    responseJson.put("headers", response.getHeaders());
    JSONObject jsonBody = (JSONObject) parser.parse(response.getBody());
    responseJson.put("body", jsonBody);
    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
    logger.log("response recieved");
    logger.log(String.format("responseJson [%s]", responseJson));
    writer.write(responseJson.toJSONString());
    writer.close();
    logger.log(String.format("output stream [%s]", outputStream));

Am i missing anything ?

6 Answers 6

6

502 errors with Lambda usuaully indicate that you are using the Lambda proxy method and not generating the proper JSON response. Make sure your response adheres to the appropriate format.

If you are still having problems, please share a sample JSON generated by your Lambda function.

Sign up to request clarification or add additional context in comments.

2 Comments

output stream [ { "headers": { "Keep-Alive": "", "Transfer-Encoding": "chunked", "Server": "Apache", "Vary": "Accept-Encoding", "Date": "", "Content-Type": "application/json;charset=UTF-8" }, "body": { "metadata": {}, "http_code": 200, "data": { "size": 1, "list_item_type": "message", "type": "messages", "items": [ ] }, "message": "", "status": "success" }, "statusCode": 200 } ]
@kunalshrivastava body is expected to be a String. If you want to pass back JSON, you'll need to escape it.
0

I had the same issue where all of my logs were saying the lambda executed successfully but API Gateway was still returning 502s on every request. Turns out I forgot to configure the response status codes in the API Gateway Console so it was throwing errors because the response was "incorrect" even with proper formatting. Just add in a status code 200, 400, 403, etc. to the route on your gateway and that might solve your problem.

Comments

0

Make sure you're hitting your callback with the response before calling context.succeed(event) or some other call to context.

This was my problem and putting my callback first fixed the persistent 502 res.

Comments

0

There are two versions of the response format. It might be that are posting a version 1 format response to an endpoint expecting version 2:

Lambda function response for format 1.0

With the 1.0 format version, Lambda integrations must return a response in the following format.

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headername": "headervalue", ... },
    "multiValueHeaders": { "headername": ["headervalue", "headervalue2", ...], ... },
    "body": "..."
}

Lambda function response for format 2.0

With the 2.0 format version, API Gateway can infer the response format for you. API Gateway makes the following assumptions if your Lambda function returns valid JSON and doesn't return a statusCode:

  • isBase64Encoded is false.
  • statusCode is 200.
  • content-type is application/json.
  • body is the function's response.

The following examples show the output of a Lambda function and API Gateway's interpretation.

Lambda function output API Gateway interpretation
"Hello from Lambda!" {
"isBase64Encoded": false,
"statusCode": 200,
"body": "Hello from Lambda!",
"headers": {
"content-type": "application/json"
}
}
{ "message": "Hello from Lambda!" } {
"isBase64Encoded": false,
"statusCode": 200,
"body": "{ \"message\": \"Hello from Lambda!\" }",
"headers": {
"content-type": "application/json"
}
}

To customize the response, your Lambda function should return a response with the following format:

{
    "cookies" : ["cookie1", "cookie2"],
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headername": "headervalue", ... },
    "body": "Hello from Lambda!"
} 

Comments

0

Try something like this:

// Custom response for API gateway
return {
  statusCode: 200,
    headers: {
      my_header: "my_value"
    },
    body: JSON.stringify({result: 'success'}),
    isBase64Encoded: false
};

Adapted from: https://repost.aws/knowledge-center/malformed-502-api-gateway

Comments

0

I had a similar issue where I had created a REST API with Lambda Integration. According to docs here, your response from lambda handler needs to be in this format:

    let response = {
      statusCode: 200,
      headers: {
        'x-custom-header': 'custom-header-value',
      },
      body: JSON.stringify(resp),
    };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.