Dry breakfast
Dry breakfast

Reputation: 11

Lambda execution failed with status 200 due to customer function error: 'name'

I'm new to AWS services. Trying to implement simple CRUD with AWS SAM(yaml), Lambdas and API Gateway. Faced with problem of POST method. The Lambda itself works fine, but if I try it within API Gateway - get:

Lambda execution failed with status 200 due to customer function error: 'name'

Here's the Lambda code itself:

import json
import boto3
import os


dynamodb = boto3.resource('dynamodb')
table_name = os.environ.get('DYNAMO_TABLE', 'dragons-table')
region = os.environ.get('REGION_NAME', 'us-east-1')
table = dynamodb.Table(table_name)


def lambda_handler(event, context):
    table.put_item(
        Item={
            'name': event['name'],
            'breed': event['breed'],
            'danger_rating': event['danger_rating']
        }
    )
    response = {
        'message': "Item added"
    }
    return {
        "statusCode": 201,
        "body": json.dumps(response),
    }

And here's the logs after execution:

Thu Feb 03 10:48:15 UTC 2022 : Endpoint response body before transformations: {"errorMessage": "'name'", "errorType": "KeyError", "requestId": "83fcc181-b4b5-4a6d-b035-4ea12eaa892e", "stackTrace": ["  File \"/var/task/post_dragons.py\", line 13, in lambda_handler\n    name = event['name']\n"]}
Thu Feb 03 10:48:15 UTC 2022 : Lambda execution failed with status 200 due to customer function error: 'name'. Lambda request id: 83fcc181-b4b5-4a6d-b035-4ea12eaa892e
Thu Feb 03 10:48:15 UTC 2022 : Method completed with status: 502

The Lambda Proxy integration is definitely on, so event can't be null...

Would be really greateful for help. Thank you :)

UPDATE: added CloudWatch logs after adding print(event):

{'resource': '/dragons', 'path': '/dragons', 'httpMethod': 'POST', 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'CloudFront-Forwarded-Proto': 'https', 'CloudFront-Is-Desktop-Viewer': 'true', 'CloudFront-Is-Mobile-Viewer': 'false', 'CloudFront-Is-SmartTV-Viewer': 'false', 'CloudFront-Is-Tablet-Viewer': 'false', 'CloudFront-Viewer-Country': 'UA', 'Content-Type': 'application/json', 'Host': 'HOST.execute-api.us-east-1.amazonaws.com', 'Postman-Token': 'b63589cf-40dc-43bb-bc16-37a4044170ef', 'User-Agent': 'PostmanRuntime/7.29.0', 'Via': '1.1 HOST.cloudfront.net (CloudFront)', 'X-Amz-Cf-Id': '==', 'X-Amzn-Trace-Id': 'Root=', 'X-Forwarded-For': '91.208.153.1, 54.239.171.73', 'X-Forwarded-Port': '443', 'X-Forwarded-Proto': 'https'}, 'multiValueHeaders': {'Accept': ['*/*'], 'Accept-Encoding': ['gzip, deflate, br'], 'CloudFront-Forwarded-Proto': ['https'], 'CloudFront-Is-Desktop-Viewer': ['true'], 'CloudFront-Is-Mobile-Viewer': ['false'], 'CloudFront-Is-SmartTV-Viewer': ['false'], 'CloudFront-Is-Tablet-Viewer': ['false'], 'CloudFront-Viewer-Country': ['UA'], 'Content-Type': ['application/json'], 'Host': ['HOST.execute-api.us-east-1.amazonaws.com'], 'Postman-Token': ['b63589cf-40dc-43bb-bc16-37a4044170ef'], 'User-Agent': ['PostmanRuntime/7.29.0'], 'Via': ['1.1 13182ff42379bbc1098730eb0992dbae.cloudfront.net (CloudFront)'], 'X-Amz-Cf-Id': ['Zv9A5svGpQsMHJl9JpF7I6E6lbCmrKnhuzJJtoGjaKnpNMMk4aibvg=='], 'X-Amzn-Trace-Id': ['Root='], 'X-Forwarded-For': ['91.208.153.1, 54.239.171.73'], 'X-Forwarded-Port': ['443'], 'X-Forwarded-Proto': ['https']}, 'queryStringParameters': None, 'multiValueQueryStringParameters': None, 'pathParameters': None, 'stageVariables': None, 'requestContext': {'resourceId': 'q5leiw', 'resourcePath': '/dragons', 'httpMethod': 'POST', 'extendedRequestId': 'M9nWSGX0IAMFW3g=', 'requestTime': '03/Feb/2022:11:13:56 +0000', 'path': '/Prod/dragons', 'accountId': '939694363734', 'protocol': 'HTTP/1.1', 'stage': 'Prod', 'domainPrefix': 'HOST', 'requestTimeEpoch': , 'requestId': '', 'identity': {'cognitoIdentityPoolId': None, 'accountId': None, 'cognitoIdentityId': None, 'caller': None, 'sourceIp': '91.208.153.1', 'principalOrgId': None, 'accessKey': None, 'cognitoAuthenticationType': None, 'cognitoAuthenticationProvider': None, 'userArn': None, 'userAgent': 'PostmanRuntime/7.29.0', 'user': None},  'body': '{\r\n    "name": "dragon",\r\n    "breed": "dragon",\r\n    "danger_rating": 6,\r\n    "description": "description"\r\n}', 'isBase64Encoded': False}

UPDATE: new interesting thing, that I found - the type of the body of my request in API Gateway - string. Why so? If I test Lambda - everything is OK, but API Gateway does smth...

Upvotes: 0

Views: 3630

Answers (2)

Dry breakfast
Dry breakfast

Reputation: 11

As I noticed before API Gateway makes the body of request as a String, not JSON.

I just added json.loads(event['body']). That's all :)

Sounds like an ugly hack, whatever. Write me, if you know better solution.

Thank you all ;)

You also may find better explanation here: Getting json body in aws Lambda via API gateway

Upvotes: 1

Hussain Mansoor
Hussain Mansoor

Reputation: 3134

According to the logs you shared the name key is not directly under event object. You have to get the value with something like:

table.put_item(
        Item={
            'name': event['body']['name']
            .
            .
        }
    )

Upvotes: 0

Related Questions