Developing software in the Real World

Changing the AWS API Gateway response status code in SAM

When creating an API with AWS Lambda and Api Gateway, I discovered that a client request to a given resource with a verb that wasn’t supported resulted in an unexpected response.

You can see this from this curl command to the /test resource which is only defined for GET:

Given that I can GET the /Prod/hello resource, I would not expect to see 405 Method Not Allowed for PUT, and 403 Forbidden is a bit of a head-scratcher.

One way to handle this is to customise the Gateway Response. Gateway Responses are the set responses that API Gateway will return when it can’t processing an incoming request. There are quite a few responses, and the one we want is MISSING_AUTHENTICATION_TOKEN.

What we are going to do is create an AWS::Serverless::Api resource in our template.yaml which sets a different status code and response for the MISSING_AUTHENTICATION_TOKEN response. This is a new ability of SAM version 1.11.0, so make sure you have at least that version.

Our template looks like this;

Once we’ve deployed, a PUT request to our endpoint now returns the expected response:


I should note that this solution isn’t a panacea and introduces another problem. If you try to access an endpoint that doesn’t exist, you also get a 405 back rather than the expected 404. Of course, before this change you got a 403, so it’s wrong regardless. More work here is definitely needed.

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *