Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Amazon Lambda function throws key error?

I have this lambda function

    import json
    import boto3
def lambda_handler(event, context):
    print("event:::")
    print(event)
    connection_id = event['requestContext']['connectionId']
    username = event['queryStringParameters']['username']

    dynamodb = boto3.resource('dynamodb')
    table1 = dynamodb.Table('table')
    table1.put_item(
        Item={
            'connection_id': connection_id,
            'username': username
           # 'message': message

        }
        )
    return {
        'statusCode': 200
    }

when I test it throws this

Test Event Name
dd

    Response
    {
      "errorMessage": "'requestContext'",
      "errorType": "KeyError",
      "requestId": "3105164b-79ac-4881-9c61-259ac437c34c",
      "stackTrace": [
        "  File \"/var/task/lambda_function.py\", line 8, in lambda_handler\n    connection_id = event['requestContext']['connectionId']\n"
      ]
    }

Function Logs

START RequestId: 3105164b-79ac-4881-9c61-259ac437c34c Version: $LATEST
event:::
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
[ERROR] KeyError: 'requestContext'
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 8, in lambda_handler
    connection_id = event['requestContext']['connectionId']END RequestId: 3105164b-79ac-4881-9c61-259ac437c34c
REPORT RequestId: 3105164b-79ac-4881-9c61-259ac437c34c  Duration: 1.23 ms   Billed Duration: 2 ms   Memory Size: 128 MB Max Memory Used: 51 MB

Request ID
3105164b-79ac-4881-9c61-259ac437c34c

my function works when I remove keys,but with keys, it throws the above error
why does this happen if the python code is correct?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

……………………………………………………………………

>Solution :

Your test execution needs input values. You can see in your error that the test used the default input {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}. You have to change the test input to a JSON string that contains the connection_id and queryStringParameters in the correct format.

It seems that you use Lambda in combination with the API Gateway. The gateway usually creates the event input. You can also create a test in the API Gateway, where you can specify the query parameters.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading