How to correctly call queryStringParameters for AWS Lambda + API Gateway?

12,616

Solution 1

I recommend adding a couple of diagnostics, as follows:

import json

def lambda_handler(event, context):
    print('event:', json.dumps(event))
    print('queryStringParameters:', json.dumps(event['queryStringParameters']))

    transactionId = event['queryStringParameters']['transactionid']
    transactionType = event['queryStringParameters']['type']
    transactionAmounts = event['queryStringParameters']['amount']
    // remainder of code ...

That way you can see what is in event and event['queryStringParameters'] to be sure that it matches what you expected to see. These will be logged in CloudWatch Logs (and you can see them in the AWS Lambda console if you are testing events using the console).

In your case, it turns out that your test event included transactionId when your code expected to see transactionid (different spelling). Hence the KeyError exception.

Solution 2

just remove ['queryStringParameters']. the print event line shows the event i only a array not a key value pair. I happen to be following the same tutorial. I'm still on the api gateway part so i'll update once mine is completed.

Whan you test from the lambda function there is no queryStringParameters in the event but it is there when called from the api gateway, you can also test from the api gateway where queryStringParameters is required to get the values passed.

Share:
12,616

Related videos on Youtube

JWB
Author by

JWB

Updated on June 04, 2022

Comments

  • JWB
    JWB almost 2 years

    I'm following a tutorial on setting up AWS API Gateway with a Lambda Function to create a restful API. I have the following code:

    import json
    
    def lambda_handler(event, context):
        # 1. Parse query string parameters
        transactionId = event['queryStringParameters']['transactionid']
        transactionType = event['queryStringParameters']['type']
        transactionAmounts = event['queryStringParameters']['amount']
    
        # 2. Construct the body of the response object
        transactionResponse = {}
        # returning values originally passed in then add separate field at the bottom
        transactionResponse['transactionid'] = transactionId
        transactionResponse['type'] = transactionType
        transactionResponse['amount'] = transactionAmounts
        transactionResponse['message'] = 'hello from lambda land'
    
        # 3. Construct http response object
        responseObject = {}
        responseObject['StatusCode'] = 200
        responseObject['headers'] = {}
        responseObject['headers']['Content-Type'] = 'application/json'
        responseObject['body'] = json.dumps(transactionResponse)
    
        # 4. Return the response object
        return responseObject
    
    

    When I link the API Gateway to this function and try to call it using query parameters I get the error:

    {
    "message":"Internal server error"
    }
    

    When I test the lambda function it returns the error:

    {
      "errorMessage": "'transactionid'",
      "errorType": "KeyError",
      "stackTrace": [
        "  File \"/var/task/lambda_function.py\", line 5, in lambda_handler\n    transactionId = event['queryStringParameters']['transactionid']\n"
      ]
    

    Does anybody have any idea of what's going on here/how to get it to work?

    • jarmod
      jarmod over 3 years
      What URL path/query did you submit and what does event['queryStringParameters'] contain?
    • JWB
      JWB over 3 years
      I submitted my-api-gateway-url.com/test?transactionid=5&type=purchase&am‌​ount=50 and from my understanding event['queryStringParameters'] is a dictionary if the API Gateway passes a query string parameter
    • jarmod
      jarmod over 3 years
      Are you using Lambda proxy integration? What does event['queryStringParameters'] actually contain?
    • JWB
      JWB over 3 years
      yes, and how do I check that? It should contain the query string parameters, no?
    • jarmod
      jarmod over 3 years
      The docs explain how to configure Lambda proxy integration. Check that, and then actually print out the values of event and event['queryStringParameters'] (preferably as prettified JSON) so you can see what's actually being presented to your Lambda function.
    • JWB
      JWB over 3 years
      I have the Lambda proxy integration configured. I cannot print the values of event because the lambda code is erroring.
    • jarmod
      jarmod over 3 years
      Print event before you attempt to access it as a dictionary. In the first line of your Lambda function. Ditto for event[‘queryStringParameters’].
    • JWB
      JWB over 3 years
      I did, I even put print(‘test’) before the function and it still just returns the error
    • jarmod
      jarmod over 3 years
      Not sure why that’s relevant. Your Lambda function executes. It will fail because you are requesting dictionary key that doesn’t exist. Please print out the things I have asked for before it fails so you can see what’s actually available in event and queryStringParameters.
    • JWB
      JWB over 3 years
      It’s relevant because it for some reason is skipping straight to the function lambda_handler or it's processing "keyerror" as a syntax error? I put the print statements everywhere possible within that function. It will not print the contents of event. It only returns the error from the original message.
    • jarmod
      jarmod over 3 years
      You’re aware that anything you print in a Lambda function gets logged in CloudWatch Logs, yes?
    • JWB
      JWB over 3 years
      I'm sorry, I didn't know how to properly configure the Test Events to get the lambda function to test properly. It returns the following {'queryStringParameters': {'transactionId': '5', 'type': 'purchase', 'amount': '100'}} I used those values as test values in the json i passed into the test event json
    • jarmod
      jarmod over 3 years
      Typo in transactionid (which is what your code is expecting to see).
    • JWB
      JWB over 3 years
      ahhh i see now, thank you for all your help
    • jarmod
      jarmod over 3 years
      So, it’s working ok now? I’ll add an answer.
    • Marcin
      Marcin over 3 years
      There was no need to delete the question. I could have provided an answer if my comments were helpful.
  • JWB
    JWB over 3 years
    so you're saying event['transactionid'] should work?
  • Gordon Christie
    Gordon Christie over 3 years
    or add queryStringParameters into your test json on the lambdafunction { "queryStringParameters": { "transactionid": 123, "type": "type", "amount": 123 } }