通过API网关在AWS Lambda中获取JSON正文


84

我目前正在使用NodeJS通过AWS Api Gateway在AWS lambda上构建机器人,并且遇到POST请求和JSON数据问题。我的api使用“使用Lambda代理集成”,甚至当我测试代理在主体中发送内容类型为Application / json和某些json的代理时,例如{"foo":"bar"},如果不先解析对象就无法访问该对象

例如

  var json = JSON.parse(event.body);
  console.log(json.foo);

现在我知道仅通过JSON.parse运行它似乎没什么大不了的,但是我已经看到了很多其他例子,而事实并非如此。看到这里https://github.com/pinzler/fb-messenger-bot-aws-lambda/blob/master/index.js

是否需要向API网关添加任何内容以正确处理此问题?“发布方法请求”部分中的“请求正文”步骤具有请求正文的application / json设置的内容类型。

就我所知,上述示例的自述文件似乎未使用代理集成,因此我不确定在这里应该做什么

Answers:


71

您可以在API Gateway中配置两种不同的Lambda集成,例如Lambda集成和Lambda代理集成。对于Lambda集成,您可以自定义不需要解析正文的有效负载中传递给Lambda的内容,但是当您在API Gateway中使用Lambda Proxy集成时,API Gateway会将所有内容都代理到Lambda中像这样,

{
    "message": "Hello me!",
    "input": {
        "path": "/test/hello",
        "headers": {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate, lzma, sdch, br",
            "Accept-Language": "en-US,en;q=0.8",
            "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": "US",
            "Host": "wt6mne2s9k.execute-api.us-west-2.amazonaws.com",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
            "Via": "1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net (CloudFront)",
            "X-Amz-Cf-Id": "nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==",
            "X-Forwarded-For": "192.168.100.1, 192.168.1.1",
            "X-Forwarded-Port": "443",
            "X-Forwarded-Proto": "https"
        },
        "pathParameters": {"proxy": "hello"},
        "requestContext": {
            "accountId": "123456789012",
            "resourceId": "us4z18",
            "stage": "test",
            "requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
            "identity": {
                "cognitoIdentityPoolId": "",
                "accountId": "",
                "cognitoIdentityId": "",
                "caller": "",
                "apiKey": "",
                "sourceIp": "192.168.100.1",
                "cognitoAuthenticationType": "",
                "cognitoAuthenticationProvider": "",
                "userArn": "",
                "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
                "user": ""
            },
            "resourcePath": "/{proxy+}",
            "httpMethod": "GET",
            "apiId": "wt6mne2s9k"
        },
        "resource": "/{proxy+}",
        "httpMethod": "GET",
        "queryStringParameters": {"name": "me"},
        "stageVariables": {"stageVarName": "stageVarValue"},
        "body": "{\"foo\":\"bar\"}",
        "isBase64Encoded": false
    }
}

对于您所引用的示例,它不是从原始请求中获取正文。它正在将响应主体构造回API网关。应该是这种格式,

{
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "body": "...",
    "isBase64Encoded": false
}

23
然后JSON.parse(event.body)(Lambda代理集成)
timhc22 '18

3
@ timhc22这是要点,单行应为接受的答案
5413668060

49

我认为将API网关与Lambda集成时需要了解一些事情。

Lambda集成与Lambda代理集成

过去只有Lambda集成需要映射模板。我想这就是为什么仍然看到许多使用它的示例。

  • 如何从Amazon API Gateway将查询字符串或路由参数传递到AWS Lambda

    自2017年9月起,您不再需要配置映射来访问请求正文。

  • AWS上的无服务器架构

    Lambda代理集成,如果启用它,API Gateway会将每个请求映射到JSON并将其作为事件对象传递给Lambda。在Lambda函数中,您将能够从中检索查询字符串参数,标头,阶段变量,路径参数,请求上下文以及主体。

    在不启用Lambda代理集成的情况下,您必须在API Gateway的“集成请求”部分中创建一个映射模板,并决定如何自己将HTTP请求映射到JSON。如果要将信息传递回客户端,则可能必须创建一个集成响应映射。

    在添加Lambda代理集成之前,用户被迫手动映射请求和响应,这是令人担忧的原因,尤其是对于更复杂的映射。

正文是转义字符串,而不是JSON

使用Lambda代理集成,发生lambda时,主体是使用反斜杠转义的字符串,而不是JSON。

"body": "{\"foo\":\"bar\"}" 

如果在JSON格式化程序中进行了测试。

Parse error on line 1:
{\"foo\":\"bar\"}
-^
Expecting 'STRING', '}', got 'undefined'

以下文档是关于回复的,但应适用于请求。

为了使JavaScript作为JSON对象访问它,需要使用JapaScript中的json.parse和Python中的json.dumps将其转换回JSON对象。

AWS文档显示该怎么办。

if (event.body !== null && event.body !== undefined) {
    let body = JSON.parse(event.body)
    if (body.time) 
        time = body.time;
}
...
var response = {
    statusCode: responseCode,
    headers: {
        "x-custom-header" : "my custom header value"
    },
    body: JSON.stringify(responseBody)
};
console.log("response: " + JSON.stringify(response))
callback(null, response);

感谢您指出主体只是转义字符串NOT JSON。
nngeek

1

我在Zappa上使用lambda;我正在以json格式通过POST发送数据:

我的basic_lambda_pure.py代码是:

import time
import requests
import json
def my_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    print("Log stream name:", context.log_stream_name)
    print("Log group name:",  context.log_group_name)
    print("Request ID:", context.aws_request_id)
    print("Mem. limits(MB):", context.memory_limit_in_mb)
    # Code will execute quickly, so we add a 1 second intentional delay so you can see that in time remaining value.
    print("Time remaining (MS):", context.get_remaining_time_in_millis())

    if event["httpMethod"] == "GET":
        hub_mode = event["queryStringParameters"]["hub.mode"]
        hub_challenge = event["queryStringParameters"]["hub.challenge"]
        hub_verify_token = event["queryStringParameters"]["hub.verify_token"]
        return {'statusCode': '200', 'body': hub_challenge, 'headers': 'Content-Type': 'application/json'}}

    if event["httpMethod"] == "post":
        token = "xxxx"
    params = {
        "access_token": token
    }
    headers = {
        "Content-Type": "application/json"
    }
        _data = {"recipient": {"id": 1459299024159359}}
        _data.update({"message": {"text": "text"}})
        data = json.dumps(_data)
        r = requests.post("https://graph.facebook.com/v2.9/me/messages",params=params, headers=headers, data=data, timeout=2)
        return {'statusCode': '200', 'body': "ok", 'headers': {'Content-Type': 'application/json'}}

我得到了下一个json响应:

{
"resource": "/",
"path": "/",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"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": "US",
"Content-Type": "application/json",
"Host": "ox53v9d8ug.execute-api.us-east-1.amazonaws.com",
"Via": "1.1 f1836a6a7245cc3f6e190d259a0d9273.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "LVcBZU-YqklHty7Ii3NRFOqVXJJEr7xXQdxAtFP46tMewFpJsQlD2Q==",
"X-Amzn-Trace-Id": "Root=1-59ec25c6-1018575e4483a16666d6f5c5",
"X-Forwarded-For": "69.171.225.87, 52.46.17.84",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https",
"X-Hub-Signature": "sha1=10504e2878e56ea6776dfbeae807de263772e9f2"
},
"queryStringParameters": null,
"pathParameters": null,
"stageVariables": null,
"requestContext": {
"path": "/dev",
"accountId": "001513791584",
"resourceId": "i6d2tyihx7",
"stage": "dev",
"requestId": "d58c5804-b6e5-11e7-8761-a9efcf8a8121",
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"apiKey": "",
"sourceIp": "69.171.225.87",
"accessKey": null,
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": null,
"user": null
},
"resourcePath": "/",
"httpMethod": "POST",
"apiId": "ox53v9d8ug"
},
"body": "eyJvYmplY3QiOiJwYWdlIiwiZW50cnkiOlt7ImlkIjoiMTA3OTk2NDk2NTUxMDM1IiwidGltZSI6MTUwODY0ODM5MDE5NCwibWVzc2FnaW5nIjpbeyJzZW5kZXIiOnsiaWQiOiIxNDAzMDY4MDI5ODExODY1In0sInJlY2lwaWVudCI6eyJpZCI6IjEwNzk5NjQ5NjU1MTAzNSJ9LCJ0aW1lc3RhbXAiOjE1MDg2NDgzODk1NTUsIm1lc3NhZ2UiOnsibWlkIjoibWlkLiRjQUFBNHo5RmFDckJsYzdqVHMxZlFuT1daNXFaQyIsInNlcSI6MTY0MDAsInRleHQiOiJob2xhIn19XX1dfQ==",
"isBase64Encoded": true
}

我的数据在主体钥匙上,但是是用code64编码的,我怎么知道呢?我看到密钥是Base64Encoded

我复制主体键的值,并使用此工具和“ eureka”进行解码,得到值。

希望对您有所帮助。:)

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.