For instance if I want to return a specific 400 error for invalid parameters or perhaps a 201 when the lambda function call resulted in a create.
I'd like to have different http status codes but it looks like api gateway always returns a 200 status code even if the lambda function is returning an error.
To be able to return a custom error object as JSON you have to jump through a couple of hoops.
First, you must fail the Lambda and pass it a stringified JSON object:
Next, you setup the regex mapping for each of the status codes you would like to return. Using the object I defined above you would setup this regex for 400:
.*"status":400.*
Finally, you setup a Mapping Template to extract the JSON response from the errorMessage property returned by Lambda. The Mapping Template looks like this:
$input.path('$.errorMessage')
I wrote an article on this that goes into more detail and explains the response flow from Lambda to API Gateway here: http://kennbrodhagen.net/2016/03/09/how-to-return-a-custom-error-object-and-status-code-from-api-gateway-with-lambda/
Update per 20-9-2016
Amazon finally made this easy using the Lambda Proxy integration. This allows your Lambda function to return proper HTTP codes and headers:
Say goodbye request/response mapping in the API Gateway!
Option 2
Integrate an existing Express app with Lambda/API Gateway using aws-serverless-express.
The easiest way to do this is to use LAMBDA_PROXY integration. Using this method, you don't need any special transformations to be set into API Gateway pipeline.
Your return object would have to be similar to the snippet below:
It does have a few drawbacks: as having to be specially careful about error handling, and coupling your lambda function to the API Gateway endpoint; that said, if you were not really going to use it anywhere else, it is not that much of a problem.
I'm using serverless 0.5. This is how it works, for my case
s-function.json:
handler.js:
This is how it's recommended on an AWS Compute Blog if using API Gateway. Checking to see if integration works with direct Lambda invocation.
For direct Lambda invocations, this appears to be the best solution parsing on the client-side.
Here's the fastest way to return custom HTTP Status Codes and a custom
errorMessage
:In the API Gateway dashboard, do the following:
Add an integration response for each of the HTTP Status Codes you created earlier. Make sure input passthrough is checked. Use lambda error regex to identify which status code should be used when you return an error message from your lambda function. For example:
Your API Gateway route should return this:
I see no way to copy these settings and re-use it for different methods, so we have much annoying redundant manual inputting to do!
My Integration Responses look like this: