Pragmatism 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:

$ curl -i -X PUT
HTTP/2 403
content-type: application/json
content-length: 42

{"message":"Missing Authentication Token"}

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;

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: 'Test API'

        Type: 'AWS::Serverless::Api'
            StageName: prod
                    StatusCode: 405
                        "application/json": '{ "message": "Method Not Allowed" }'

        Type: AWS::Serverless::Function
            FunctionName: 'myapiname-test'
            Description: ''
            CodeUri: .
            Handler: index.php
            Timeout: 10
            MemorySize: 256
            Runtime: provided
                - 'arn:aws:lambda:eu-west-2:209497400698:layer:php-73:4'
                    Type: Api
                        RestApiId: !Ref "MyApiName"
                        Path: /test
                        Method: GET

# This lets us retrieve the app's URL in the "Outputs" tab in CloudFormation
        Description: 'API URL in the Prod environment'
        Value: !Sub 'https://${MyApiName}.execute-api.${AWS::Region}'

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

$ curl -i -X PUT
HTTP/2 405
content-type: application/json
content-length: 35

{ "message": "Method Not Allowed" }


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.