Python lambda function returns KeyError

Viewed 29193

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?
3 Answers

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'')"}'

In my case my Python Lambda required a key called exclude. To resolve the issue of getting this response when calling via API Gateway, I needed to update the integration request with a mapping template:

Mapping Template

Related