How to get the HTTP method in AWS Lambda?
Asked Answered
D

7

23

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.

Donate answered 7/2, 2016 at 10:52 Comment(0)
H
29

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.

Heman answered 7/2, 2016 at 13:33 Comment(4)
Thanks. By the way, just a minor typo error in your answer : ""$context.httpMethod" is "$context.httpMethod"Donate
Does it work for you guys with the Chrome extension Advanced REST client? I get null for the context variables when I use it, but it works with the extensions Postman and DHC, or direct call in the browser if it's a GET endpoint.Tann
Make sure you redeploy your endpoint after you make these changes. Took me the longest time to figure out.Henbane
Just pointing it out in case anybody confuses themselves like I just did. If you use the Method Request passthrough template in the AWS console (as of June 2023 anyway) it stores the HTTP method in a dict object named context which is passed into the event Lambda handler parameter, not to be confused with the context Lambda handler parameter, which is exactly what I confused. So to access it you would do event['context']['http-method'], NOT context['http-method'].Bollworm
H
15

API Gateway now has a built-in mapping template that passes along stuff like http method, route, and a lot more. I can't embed because I don't have enough points, but you get the idea.

Here is a screenshot of how you add it in the API Gateway console:

To get there navigate to AWS Console > API Gateway > (select a resource, IE - GET /home) > Integration Request > Mapping Templates > Then click on application/json and select Method Request Passthrough from dropdown shown in the screenshot above

Headmaster answered 8/9, 2018 at 1:49 Comment(5)
text is searchable, images not. The Windows error screens are also not copy-pastable, but having the messages as text helps to find what one is searching for.Ashby
idownvotedbecau.se/imageofcode lists the reasons why people consider it worth a downvote when people paste images of text rather than the text itself.Cuthburt
The point here was not to show the code but to show the user what the panel looks like in the AWS API Gateway Console.Headmaster
This is the better answer. Even though the accepted answer is correct, it replaces the information rather than adds/annotates which is more likely what the intent of the question wasSteeve
Posting this comment across both answers since it's pertinent to both... Just pointing it out in case anybody confuses themselves like I just did. If you use the Method Request passthrough template in the AWS console (as of June 2023 anyway) it stores the HTTP method in a dict object named context which is passed into the event Lambda handler parameter, not to be confused with the context Lambda handler parameter, which is exactly what I confused. So to access it you would do event['context']['http-method'], NOT context['http-method'].Bollworm
R
5

I had this problem when I created a template microservice-http-endpoint-python project from functions. Since it creates an HTTP API Gateway, and only REST APIs have Mapping template I was not able to put this work. Only changing the code of Lambda.

Basically, the code does the same, but I am not using the event['httpMethod']

Please check this:

import boto3
import json

print('Loading function')
dynamo = boto3.client('dynamodb')


def respond(err, res=None):
    return {
        'statusCode': '400' if err else '200',
        'body': err.message if err else json.dumps(res),
        'headers': {
            'Content-Type': 'application/json',
        },
    }


def lambda_handler(event, context):
    '''Demonstrates a simple HTTP endpoint using API Gateway. You have full
    access to the request and response payload, including headers and
    status code.

    To scan a DynamoDB table, make a GET request with the TableName as a
    query string parameter. To put, update, or delete an item, make a POST,
    PUT, or DELETE request respectively, passing in the payload to the
    DynamoDB API as a JSON body.
    '''
    print("Received event: " + json.dumps(event, indent=2))

    operations = {
        'DELETE': lambda dynamo, x: dynamo.delete_item(**x),
        'GET': lambda dynamo, x: dynamo.scan(**x),
        'POST': lambda dynamo, x: dynamo.put_item(**x),
        'PUT': lambda dynamo, x: dynamo.update_item(**x),
    }
    
    operation =  event['requestContext']['http']['method']

    if operation in operations:
        payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body'])
        return respond(None, operations[operation](dynamo, payload))
    else:
        return respond(ValueError('Unsupported method "{}"'.format(operation)))

I changed the code from:

operation = event['httpMethod']

to

operation = event['requestContext']['http']['method']

How do I get this solution?

I simply returned the entire event, checked the JSON and put it to work with the correct format.

Robotize answered 18/4, 2020 at 19:32 Comment(2)
Thank you. For those using the Node.js runtime, it can be done similarly: let operation = event.requestContext.http.method;Unpile
@jorge freitas I don't think this works anymore, I tried it and it seems that now it is event['requestContext']['httpMethod'].Swap
P
1

If event appears an empty object, make sure you enabled proxy integration for the method. Proxy integration for an HTTP method adds request information into event. See Use Lambda Proxy integration on API Gateway page.

Piperonal answered 23/11, 2021 at 15:59 Comment(0)
C
1

I'm using aws-lambda-go. It might be missmatched between request type v1 for api gateway v2. Version missmatched could be the reason for another languages

Ref: https://github.com/aws/aws-lambda-go/issues/179

Cassowary answered 18/8, 2023 at 10:9 Comment(0)
S
1

I had to console log my event, and found out that the method is at this point event.requestContext.http.method

export const handler = async (event) => {
    console.log(event);
    // Enable CORS
    const headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
        'Access-Control-Allow-Methods': 'OPTIONS, POST, GET, PUT, DELETE'
    };

    try {
        if (event.requestContext.http.method === 'OPTIONS') {
Succeed answered 2/2 at 6:55 Comment(0)
H
0

If you are using API gateway, http method will be automatically passed to the event parameter when the lambda is triggered.

export const handler: Handler<APIGatewayProxyEvent> = async (
  event: APIGatewayEvent,
  context: Context
): Promise<APIGatewayProxyResult> => {
  const httpMethod = event.httpMethod;

  ...
}
Hatti answered 1/8, 2022 at 21:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.