Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lambda function returns KeyError

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?
like image 565
JamZ Avatar asked Nov 28 '17 16:11

JamZ


People also ask

What is lambda function error?

Function errors occur when your function's code or runtime returns an error. Depending on the type of error, the type of invocation, and the client or service that invokes the function, the retry behavior and the strategy for managing errors varies.

What happens when AWS Lambda throws exception?

If Lambda encounters an error, it returns an exception type, message, and HTTP status code that indicates the cause of the error. The client or service that invoked the Lambda function can handle the error programmatically, or pass it along to an end user.

How do you make lambda fail?

Lambda functions can fail in three cases: An unhandled exception is raised — whether if we received an invalid input, an external API failed, or just a programming bug occurred. Timeout — Lambda running longer than the configured timeout duration is violently closed with a 'Task timed out after … seconds' message.


2 Answers

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

like image 194
Pandit Biradar Avatar answered Sep 28 '22 05:09

Pandit Biradar


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'')"}'
like image 37
user3821178 Avatar answered Sep 28 '22 03:09

user3821178