How to get the HTTP method in AWS Lambda?

Xavier M picture Xavier M · Feb 7, 2016 · Viewed 19.5k times · Source

In an AWS Lambda code, how can I get the HTTP method (e.g. GET, POST...) of an HTTP request coming from the AWS Gateway API?

I understand from the documentation that context.httpMethod is the solution for that.

However, I cannot manage to make it work.

For instance, when I try to add the following 3 lines:

    if (context.httpMethod) {
            console.log('HTTP method:', context.httpMethod)
    }

into the AWS sample code of the "microservice-http-endpoint" blueprint as follows:

exports.handler = function(event, context) {

    if (context.httpMethod) {
        console.log('HTTP method:', context.httpMethod)
    }

    console.log('Received event:', JSON.stringify(event, null, 2));

    // For clarity, I have removed the remaining part of the sample
    // provided by AWS, which works well, for instance when triggered 
    // with Postman through the API Gateway as an intermediary.
};

I never have anything in the log because httpMethod is always empty.

Answer

garnaat picture garnaat · Feb 7, 2016

The context.httpMethod approach works only in templates. So, if you want to have access to the HTTP method in your Lambda function, you need to find the method in the API Gateway (e.g. GET), go to the Integration Request section, click on Mapping Templates, and add a new mapping template for application/json. Then, select the application/json and select Mapping Template and in the edit box enter something like:

{
    "http_method": "$context.httpMethod"
}

Then, when your Lambda function is called, you should see a new attribute in the event passed in called http_method which contains the HTTP method used to invoke the function.