AWS Protips: Returning Proper HTTP Status with AWS Lambda and API Gateway using Gordon

Gordon is a great tool for building and deploying your AWS applications.  Spend the time setting it up properly, and your AWS deployments to Lambda and API Gateway will go smoothly.  But when you're first using it, and you don't have a Swagger background, you might find yourself in the same position I was:  trying to figure out how to surface a proper HTTP status code from Lambda, up through API Gateway -- and with very little help from the usual sources (e.g. Google).

Instead of letting you suffer through the pain of stringing it all together, I'll just show you how to do it, and explain how it works along the way.  As an example, we'll do a POST request, that can return two possible HTTP statuses:  a 200 and a 400.


Set up your Lambda

I'm making the assumption that you -- if you are to this point -- you have learned some of the basic basics of Gordon and setting up API Gateway and hooking up the Lambdas.  This means you know how to set up a basic handler.  This will let me skip some things, and go to the substance.

Let's say that you are validating input for a client app, and you want to make sure that a user_id is included in the request.  If it's not included, you want to force API Gateway to raise the proper HTTP status -- in this case, a 400 for a malformed request.


def handler(event, context):


    if 'user_id' not in event:
        raise Exception("[Malformed] user_id is missing from request")

    ...do something in your code

    return useful_json


The key to getting API Gateway to notice that you want it to return something aside from the usual '200 OK' status, is that you *must* raise an exception that contains a string that can be matched by a regular expression.  In this case, I chose to use the string '[Malformed]'.  This string is sent as part of the response, where it is trapped by a piece of code we will write for API Gateway.

NOTE:  I found out the hard way, and wasted several hours in the process, discovering that you cannot fake up this response -- you MUST raise the Exception here.  If you try to fake it up, the code we're about to write for API Gateway will never see your string, and will not be able to match on it.


Setting up API Gateway

I'm assuming you are slightly familiar with the YAML setup for Gordon.  There isn't much documentation on doing anything complex (one reason I'm writing this).  Below is the setup for this method inside of an example api (called 'api'):


/add_user:
    methods: POST
    integration:
        lambda: api.add_user
        responses:
            - code: "400"
              pattern: "^\\[Malformed\\].*"
              template:
                  application/json: |
                      #set($inputRoot=$input.path('$.errorMessage'))
                      $inputRoot
            - code: "200"
            pattern: ""
    responses:
        - code: "400"
        - code: "200"


You'll noticed that our string from our Lambda exception is here.  Here, API Gateway will match on the exception message we set up.  There's four things you'll have to set up here.  The first is the regular expression pattern under the integration response for the exception (e.g. missing user_id).  The integration response is just what Lambda returns when it's finished.  It will set the HTTP status to the matching code with the response.  In this case, a 400.  The third thing to add is the response template.  This is written as Apache Velocity template code.  In this case, it matches on the string 'errorMessage' -- and returns  the entire error message we defined for the Lambda.

The fourth place is the method response.  Since this is a POST, and adding a record, technically we should be returning a 201 CREATED.  But a great many APIs in the real world will return a 200, just out of laziness of the engineer (not pointing fingers -- I'm guilty of this as well).

Now, you'll notice that we have 200, that matches to everything.  This is just the default passthrough behavior.  But we need to set it here.  Also in the method response.

Conclusion

This wasn't meant to be an introduction to Gordon and API Gateway -- it is meant to be something that shows up in the search engine results for the engineer struggling to use this amazing Gordon tool with AWS, and can't get any love.  

Good luck with your project.  Hope this helped relieve a bit of your anxiety.

Peace
Robin


references


Gordon - https://github.com/jorgebastida/gordon
Apache Velocity Engine - http://velocity.apache.org/engine/devel/vtl-reference.html
API Gateway Mapping Template Reference http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
Ryan Green's blog https://aws.amazon.com/blogs/compute/error-handling-patterns-in-amazon-api-gateway-and-aws-lambda/