Cerin
Cerin

Reputation: 64709

How to retrieve a URL query string parameter from inside an AWS Lambda Python function?

How do you access URL querystring parameters from inside an AWS Lambda function served though an API Gateway?

I have both the API gateway + Lambda function setup so I can call it from a public URL. My Python function is simply:

def lambda_handler(event, context):
    print('event:', event)
    print('context:', context)

I've configured the API's GET "Method Request" handler to pass through the "abc" querystring parameter.

I've also configured the API's GET "Integration Request" handler to map "abc" from "method.request.querystring.abc".

However, when I access my URL, e.g. https://myapp.execute-api.us-east-1.amazonaws.com/prod/myfunc?abc=123, the only thing logged is:

event: {}
context: <bootstrap.LambdaContext object at 0x7fc7a6cb0850>

What am I doing wrong? Why isn't "abc" being passed through in the event dictionary?

Upvotes: 3

Views: 2083

Answers (2)

George Ogden
George Ogden

Reputation: 815

I have a similar problem and I know how frustrating it is. Use this mapping template:

{
  "method": "$context.httpMethod",
  "body" : $input.json('$'),
  "headers": {
    #foreach($param in $input.params().header.keySet())
    "$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext),#end

    #end
  },
  "queryStringParameters": {
    #foreach($param in $input.params().querystring.keySet())
    "$param": "$util.escapeJavaScript($input.params().querystring.get($param))" #if($foreach.hasNext),#end

    #end
  },
  "pathParameters": {
    #foreach($param in $input.params().path.keySet())
    "$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end

    #end
  }  
}

Then you should find your event looks like this:

{
    "method":"GET",
    "body":{

    },
    "headers":{

    },
    "queryParams":{
        "id":"459463732",
        "command":"join_session"
    },
    "pathParams":{

    }
}

The context is used for other information, such as IP addresses and timeout settings.

Upvotes: 0

Jules Oll&#233;on
Jules Oll&#233;on

Reputation: 6888

Check Use Lambda Proxy integration in the Integration Request to have it pass all request details in the event.

Upvotes: 1

Related Questions