AWS API Gateway — non-200 responses don’t include response body

David Treves
3 min readJun 25, 2016

--

This is a follow up on my previous post about mapping error messages from AWS Lambda to an API-GW HTTP client.

The Symptom

So you’ve mapped your Lambda errors to proper HTTP status codes. You also cleaned the error message and added it to the response body. All seems in place. BUT — it doesn’t work — the response body doesn’t make it to the client.

Checking the developer tools in your favourite browser confirms the response body isn’t there. Trying to access it using the API Gateway JS SDK returns empty string as well..

To make it even more confusing — test your API using cUrl and you see that the response body does exist.

One hint to get you in the right direction is the browser’s warning that the response doesn’t include Access-Control-Allow-Origin header. On Chrome this is the message you get:

XMLHttpRequest cannot load <your-API-URL>. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400.

OK, so we have an error message — that’s a good lead to follow. But you know you enabled CORS on all your resources. So what can that be?

The Problem

As it turns out, the API-GW console doesn’t enable CORS on non-200 responses!

Maybe It’s me, but it doesn’t seem right.. When I enable CORS then.. Well.. I enable CORS. It shouldn’t be a selective setting.

Now that I flushed this rant out of the system — lets solve this.

The Solution

We need to do two things here to make that work. It’s a manual process for each resource so brace yourself for some tedious work:

  • Under Method Response for each HTTP Response you should add Access-Control-Allow-Origin header:
  • Under Integration Response for each Lambda Error Regex (the mapping from your lambda error to HTTP status code) you should set Access-Control-Allow-Origin header with your desired value. In the below case I allow anybody by entering ‘*’.
  • Deploy the update.

Conclusion

AWS API Gateway is an exciting platform with great potential. Augment it with AWS Lambda and you can do truly amazing stuff! But being a young platform it still requires polishing and improved UX.

Non-200 responses require manual settings in order to set them in line with the 200 response templating and mapping.

And of course in hindsight it turned out to be one of those “duh” moments, especially that I did get a very clear error. But I guess the assumption that Enable CORS sorted it for me I didn’t even check that section of the configuration. Besides — the investigation, the fixing and the reward of seeing it working is all part of the fun, right? :)

--

--