在API网关中格式化正文映射模板

问题描述

需要您的帮助!我有下面的Lambda函数,它将从API网关获取输入(使用RestAPI Post方法),并将与Payload相同的值传递给第二个Lambda函数

    def lambda_handler(event,context):
    
        customerName = event['Name']
        customerEmail = event['EmailAddress']
        
        input = {"Name": customerName,"EmailAddress": customerEmail}
        
        response = lambda_client.invoke(
        FunctionName='arn_of_the_lambda_to_be_invoked',InvocationType='Event',Payload=json.dumps(input))

以下是我对JSON格式的API网关的输入-

    {
        "Name": "TestUser","EmailAddress": "[email protected]"
    }

尝试了Lambda代理集成和通用主体映射模板(来自here)。在这两种情况下,API Gateway均返回以下错误-

响应正文:

{
  "errorMessage": "'Name'","errorType": "KeyError","stackTrace": [
    "  File \"/var/task/lambda_function.py\",line 7,in lambda_handler\n    customerName = event['Name']\n"
  ]
}

当我从Lambda控制台直接调用Lambda时,使用相同的JSON输入,它可以工作。我知道API网关以及JSON正文会推动许多其他事情。但是,我无法弄清楚。

如何使它正常工作?

解决方法

在lambda代理集成中,事件将采用以下格式。

{
    "resource": "Resource path","path": "Path parameter","httpMethod": "Incoming request's method name"
    "headers": {String containing incoming request headers}
    "multiValueHeaders": {List of strings containing incoming request headers}
    "queryStringParameters": {query string parameters }
    "multiValueQueryStringParameters": {List of query string parameters}
    "pathParameters":  {path parameters}
    "stageVariables": {Applicable stage variables}
    "requestContext": {Request context,including authorizer-returned key-value pairs}
    "body": "A JSON string of the request payload."
    "isBase64Encoded": "A boolean flag to indicate if the applicable request payload is Base64-encode"
}

您发布的值将作为json字符串放在body中。您需要解析json。

import json

def lambda_handler(event,context):

    fullBody = json.loads(event['body'])
    print('fullBody: ',fullBody)
    body = fullBody['body']
    customerName = body['Name']
    customerEmail = body['EmailAddress']
    
    input = {"Name": customerName,"EmailAddress": customerEmail}
    
    response = lambda_client.invoke(
    FunctionName='arn_of_the_lambda_to_be_invoked',InvocationType='Event',Payload=json.dumps(input))

Input format of a Lambda function for proxy integration

请记住,lambda应该以以下格式返回输出以进行Lambda代理集成。

{
    "isBase64Encoded": true|false,"statusCode": httpStatusCode,"headers": { "headerName": "headerValue",... },"multiValueHeaders": { "headerName": ["headerValue","headerValue2",...],"body": "..."
}