0

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...

2
  • Print the event object and check what's coming in. You can check the logs from CloudWatch Commented Feb 3, 2022 at 11:04
  • @HussainMansoor I updated the question. As far, as I understand, everything seems fine. I've never used CloudWatch before Commented Feb 3, 2022 at 11:23

2 Answers 2

1

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

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

Comments

0

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']
            .
            .
        }
    )

1 Comment

Thu Feb 03 11:36:32 UTC 2022 : Endpoint response body before transformations: {"errorMessage": "string indices must be integers", "errorType": "TypeError", "requestId": "888f419c-18da-42a0-8277-a13f5e9719b9", "stackTrace": [" File \"/var/task/post_dragons.py\", line 15, in lambda_handler\n 'name': event['body']['name'],\n"]} Thu Feb 03 11:36:32 UTC 2022 : Lambda execution failed with status 200 due to customer function error: string indices must be integers. Lambda request id: 888f419c-18da-42a0-8277-a13f5e9719b9 Thu Feb 03 11:36:32 UTC 2022 : Method completed with status: 502

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.