简体   繁体   中英

How do you format Python using json.dumps, to make your Lambda function respond correctly to API Gateway?

This is my first post on Stack Overflow, so hope I'm being specific enough. I am trying to integrate a Lambda function (coded in Python) with DynamoDB and API Gateway. I want the API to return a single item from DynamoDB, but I'm getting an Internal server error message when I navigate to the API endpoint. I have looked at the CloudWatch Logs and they say it's caused by a malformed Lambda proxy response .

Having further investigated, I am fairly sure this has to do with formatting the Lambda responseBody using json.dumps . But I don't know the correct syntax to do this having tried dozens of different combinations (I don't have any Python experience).

Here is my Lambda function:

def lambda_handler(event, context):

    ddbResponse = table.update_item(
        Key={
            "id": "user1"
        },
        UpdateExpression='ADD clicks :inc',
        ExpressionAttributeValues={
            ':inc': 1
        },
        ReturnValues="UPDATED_NEW"
    )

    responseBody = json.dumps(XXXXXXXXXX)

    apiResponse = {
        "isBase64Encoded": False,
        "statusCode": 200,
        "body": responseBody
    }

    return apiResponse

If I just want the API response to be the number of clicks returned from the DynamoDB table, what would I have to put in the XXXX's between the json.dumps bracket? Thanks in advance

ddbResponse['Attributes']['clicks']) will give you clicks. we can return

return {
    'statusCode': 200,
    'body': json.dumps({'clicks': int(ddbResponse['Attributes']['clicks'])})
}

To return only clicks

{
    'statusCode': 200,
    'body': int(response['Attributes']['clicks'])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM