Python lambda function returns KeyError
Solution 1
You are using event["userId"]
, this means that sending the request payload for example
GET API : api/users/
Request Body payload:
{
"userId":"1234"
}
then above code works, Suppose you want to send userId as path parameter
GET API :api/user/{userId}
then you can access in lambda function
userId = (event['pathparameters']['userId'])
better add the print statement print(event) and check the logs in cloudwatch logs
Solution 2
This solved it for me on post requests
import json
def lambda_handler(event, context):
data = json.loads(event["body"])
email = data['email']
in case you are using the serverless framework you can also add the following code under your http event. but i dont think it is that necessary.
request:
parameters:
application/json: '{"email":"$input.params(''email'')"}'
JamZ
Updated on July 08, 2022Comments
-
JamZ almost 2 years
I'm trying to create simple Lambda function using Python 3.6.
The function should get a userId (my primary key in DynamoDB) in the request query string params and returns 200 if item exist in DB, here is my lambda function
import boto3 import os from boto3.dynamodb.conditions import Key, Attr def lambda_handler(event, context): userId = event["userId"] dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.environ['Customers']) items = table.query( KeyConditionExpression=Key('userId').eq(userId) ) return items["Items"]
When i am doing tests in Lambda interface it works and return the correct user however, when trying from Postman or using API Gateway it returns the following error
{ "errorMessage": "'userId'", "errorType": "KeyError", "stackTrace": [ [ "/var/task/index.py", 7, "lambda_handler", "userId = event["userId"]" ] ] }
- What am i missing here ?
- Struggling to understand "event" , documentation states its a python dictionary but how can i print the result of it and actually debug the lambda when called from Postman or API Gateway?