3

I am having difficulty getting http method used in a call to aws lambda via api gateway. I created a REST api in api gateway, which makes a call to a lambda function. In the lambda function I want to have two functions, one for POST requests and one for GET requests. I am unable to get the method from event. In other threads answers are usually for javascript or java only.

I run the following curl command from my terminal: curl "https://myurl/endpoint" I also try to send a GET request via advanced rest client.

Here's what I'm trying to do:

def lambda_handler(event, context):

method = event['httpMethod']
if method == "GET":
    return get_function()
if method == "POST":
    return post_function()

Running the above code results in a keyError. I have tried this as well:

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

I tried printing out the event itself like this method = event. All I get from this is {}, both in the response and in cloudwatch.

How can I read the http method in a request

davidb
  • 1,503
  • 4
  • 30
  • 49

2 Answers2

1

Below code should work in Python 3.7 runtime. Of course, you can improve the code but, it will give you what you are looking for.

    reqcontxt = event.get("requestContext")
    httpprtcl = reqcontxt.get("http")
    methodname = httpprtcl.get("method")
    print('### http method name ###' + str(methodname))

Thanks.

Hiren

dossani
  • 1,892
  • 3
  • 14
  • 23
1

With help from @Marcin I understood that I had to tick 'Use Lambda Proxy Integration' option in integration request. Without it my request did not pass any method or headers data to lambda. It was either this or I would need to add some more code in my application to define the method but as I was using curl for testing I didn't add -X GET nor anything like that to the request.

davidb
  • 1,503
  • 4
  • 30
  • 49