简体   繁体   中英

AWS API Gateway Integration Response

I am using AWS Lambda and API Gateway and facing an issue with my API's response code,
In case of an exception I am setting responseCode as 400 in my response,
But the API status is 200.

I found that my solution is related to AWS API Gateway's Integration Response,
I created all the possible Http Status codes that my application needs,
And I set the Lambda Error Regex in Integration Response,
But I still get API status as 200 despite me sending "responseCode" : "400", in my APIs response(response type is JsonObject in Java).

I have the following code AWS Lambda code,
I am passing ErrorCode as query parameter to my Get method,
And returning the same Error code in response eg. "responseCode" : "400".

My expected output is "responseCode" : "400" but, the API's status should also become 400 instead of 200.

public class MainHandler implements RequestHandler<JSONObject, JSONObject> {

    public JSONObject handleRequest(JSONObject request, Context context) {

        try {
            JSONObject requestJson = (JSONObject) new JSONParser().parse(request.toString());
            System.out.println("RequestJson : " + requestJson);

            JSONObject params = (JSONObject) requestJson.get("params");
            System.out.println("Params : " + params);

            JSONObject queryString = (JSONObject) params.get("querystring");
            System.out.println("QueryString : " + queryString);

            String error = (String) queryString.get("errorCode");
            System.out.println("ErrorCode : " + error);

            JSONObject resp = new JSONObject();
            resp.put("responseCode", error);

            return resp;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

AWS API Gateway Method Response - 在此输入图像描述

AWS API Gateway Integration Response - 在此输入图像描述

Postman response -
The API status shows 200 Ok, whereas I want it as 400. 在此输入图像描述

I am referring the following links -
1. https://forums.aws.amazon.com/thread.jspa?threadID=192918
2. Is there a way to change the http status codes returned by Amazon API Gateway?

Your Lambda Error Regex is not a regular expression. Changing it to .*"responseCode":\\s"400".* should do it.

But for that use case it would be better to activate Lambda proxy integration . This provides a more flexible way to set the response code directly from the lambda function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM