Accessing query parameter in Lambda with Python

+1 vote
Hi All,

I am trying to build Lambda function with python. I am trying to access header, request ,query parameter passed as a part of request . I am able to access body part using <Event> like <event['Number1']> but not able to access other request or header parameter . Have tried like <event['pathParameters']['token']> but of no use.

Can anyone please help on this.

Thanks

Baharul Islam
Dec 5, 2018 in AWS by Baharul
• 140 points
49,430 views
@Baharul can you help me with some more detail as what are you actually trying to do? What kind of request are you processing and what are the different fields?

Hi ,

I am trying to develop some AWS rest API using python.In API I want to retrieve all transport info like content_type, http method , client Ip address. 
Also in get and put method want to get header information like userID, userGroup and request header as maybe Policy-No as per below image.

Thanks

Baharul Islam

@Baharul, great I came to know as what you are trying to achieve. 

You can  use this to get your query string

{
    "querystring": "$input.params().querystring"
}

Thanks @Shuvodip.

I was looking for code in Python. Also for aws Lambda I think we need to get it using <event or context>

@Baharul, yes you can use 

event["queryStringParameters"]['queryparam1']

to access the query, did you use this? In your question you said it didn't work. What error did you get?

@Baharul have you checked the Lambda Proxy Integration?

Hi Shuvodip,

I am getting error as without Lambda proxy integration

{
   "errorMessage": "'queryStringParameters'",
   "errorType": "KeyError",
   "stackTrace": ["  File \"/var/task/lambda_function.py\", line 23, in lambda_handler\n    \"querystring\": event[\"queryStringParameters\"]['userID']\n"]
}

As soon as I am enabling proxy integration I am getting bad request gateway  request. Only difference between this two is proxy integration.

HTTP/1.1 502 Bad Gateway
Date: Wed, 05 Dec 2018 13:38:36 GMT
Content-Type: application/json
Content-Length: 36
Connection: keep-alive
x-amzn-RequestId: 10d81e71-f893-11e8-92fb-b9ef3d2c5a0f
x-amz-apigw-id: Rb4yZG5CCYcFnvQ=

{"message": "Internal server error"}

@Baharul check the format of the response of your lambda function. Generally this error occurs when there is a permission issue or the response of lambda function is not as per the required format.
Hi @Shuvodip ,

I have made simple lambda code as below with Integration Proxy as enabled.

import json

def lambda_handler(event, context):
    # TODO implement
    number1 = event['Number1']
    number2 = event['Number2']
    sum = number1 + number2
    #querystring= event["queryStringParameters"]['test']
    querystring=context["test"]
    Body = {
        "response":{
           "resultStatus": "SUCCESS",
           "results":{
               "Number1": number1,
               "Number2": number2,
               "Sum": sum,
               "querystring": querystring
           }
        }
    }
    return {
        'statusCode': 200,
        'body': Body
    }
    

But when running the API I am getting error as

{
   "errorMessage": "'LambdaContext' object is not subscriptable",
   "errorType": "TypeError",
   "stackTrace": ["  File \"/var/task/lambda_function.py\", line 9, in lambda_handler\n    querystring=context[\"test\"]\n"]
}

Can anyone please help on this point.

Thanks

Baharul Islam
Hey @Baharul, Sorry for the long delay but I am unable to understand the problem you are facing here.
@Baharul I got a documentation of a similar thing that you are trying to do here:

https://docs.aws.amazon.com/apigateway/latest/developerguide/integrating-api-with-aws-services-lambda.html

import json

def lambda_handler(event, context):
    # TODO implement
    number1 = event['Number1']
    number2 = event['Number2']
    sum = number1 + number2
    #querystring= event["queryStringParameters"]['test']
    querystring=context["test"]  #what are you trying to achieve here?
    Body = {
        "response":{
           "resultStatus": "SUCCESS",
           "results":{
               "Number1": number1,
               "Number2": number2,
               "Sum": sum,
               "querystring": querystring
           }
        }
    }
    return {
        'statusCode': 200,
        'body': Body
    }

Thanks Shuvodip.

Here I am just trying to retrieve parameter that are pass as a part of query parameter in url like ?EmployeeID=456

Hey @baharul 

See this lambda function

def lambda_handler(event, context):
   num1 = event["queryStringParameters"]["num1"]
    num2 = event["queryStringParameters"]["num2"]
    sum =int(num1) + int(num2)
    response = {}
    response["headers"] = event["headers"]
    response["sum"] = sum
    response["num1"] = num1
    response["num2"] = num2
    return {
        'statusCode': 200,
        'body': json.dumps(event)
    }

You get everything under event itself. Try using it and let me know.

Thanks Shuvodip. When I am trying to run the same from SoapUI via API gateway getting error as 

{
   "errorMessage": "'headers'",
   "errorType": "KeyError",
   "stackTrace": ["  File \"/var/task/lambda_function.py\", line 10, in lambda_handler\n    response[\"headers\"] = event[\"headers\"]\n"]
}

Please refer below screen for more details...

Lambda Function

Gateway

Soup UI test

1 answer to this question.

0 votes

Have you gone through the mapping template reference provided by Amazon
https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html

You can see how they are accessing the query string.

For more info on AWS Lambda, refer to https://www.youtube.com/watch?v=XjPUyGKRjZs

Hope this helps!!

If you need to know more about Python, join Python certification course today.

Thanks!

answered Dec 5, 2018 by bugseeker

Related Questions In AWS

0 votes
1 answer

Python Pusher in AWS Lambda

Using virtualenv to keep track of dependencies will be ...READ MORE

answered May 30, 2018 in AWS by Cloud gunner
• 4,670 points
998 views
+1 vote
1 answer
0 votes
1 answer

Using Shapely on AWS Lambda with Python 3

For some reason, the pip install of ...READ MORE

answered Oct 8, 2018 in AWS by Priyaj
• 58,090 points
2,564 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Pass account id of an AWS sub account using a variable as an argument in CloudWatch Alarm Actions with python (boto3)?

Python String and Integer concatenation >>> print("arn:aws:swf:us-east-2:{0}:action/actions/AWS_EC2.InstanceId.Stop/1.0".format(acccnum)) arn:aws:swf:us-east-2:12312312312312:action/actions/AWS_EC2.InstanceId.Stop/1.0 >>> print("arn:aws:swf:us-east-2:" ...READ MORE

answered Oct 5, 2018 in AWS by Priyaj
• 58,090 points
1,357 views
+1 vote
10 answers
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP