2

I am very new to AWS Serverless and have chosen to use Python for my Lambda handler

When I use API Gateway to query DynamoDB to get an item in a table, if it doesn't exist, it throws this error. I am just trying to get it to return NOTHING if the item doesn't exist. Here is the error:

{
    "errorMessage": "'Item'",
    "errorType": "KeyError",
    "stackTrace": ["  File \"/var/task/lambda_function.py\", line 11, in lambda_handler\n    json_body = response['Item']\n"]
}

I have searched high and low to try and find properties in the DynamoDB response that would tell me there are no items, then I could write an If statement based on that.

Here is my Lambda code:

import json
import boto3

def lambda_handler(event, context):
    client = boto3.resource("dynamodb")
    table = client.Table("pnr-snapshot")
    pnrID = event['pnrID']
    
    response = table.get_item(Key={'pnrID': pnrID})
    json_body = response['Item']
    return json_body

I thought maybe adding a try into the code would help but instead I get this syntax error:

{"errorMessage":"Syntax error in module 'lambda_function': unexpected EOF while parsing (lambda_function.py, line 12)","errorType":"Runtime.UserCodeSyntaxError","stackTrace":[" File "/var/task/lambda_function.py" Line 12\n \t\treturn json_body\n"]}

import json
import boto3

def lambda_handler(event, context):
    client = boto3.resource("dynamodb")
    table = client.Table("pnr-snapshot")
    pnrID = event['pnrID']

    try:
        response = table.get_item(Key={'pnrID': pnrID})
        json_body = response['Item']
        return json_body

I'd really appreciate any help...

1 Answer 1

3

Could not do the following check for if the key exists?

import json
import boto3

def lambda_handler(event, context):
    client = boto3.resource("dynamodb")
    table = client.Table("pnr-snapshot")
    pnrID = event['pnrID']
    
    response = table.get_item(Key={'pnrID': pnrID})
    if 'Item' in response:
        json_body = response['Item']
        return json_body
    else:
        return ''

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Chris! That did the trick... still pretty new at Python so your help is appreciated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.