[英]Error when trying access parameters in AWS Python Lambda function using API Gateway
I have this python lambda function 我有这个python lambda函数
import json
def lambda_handler(event, context):
post_user = ""
post_user = event["user"]
print(post_user)
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": True
}
This works as expected when I run a test within the lambda IDE. 当我在Lambda IDE中运行测试时,这可以按预期工作。 The test is configured to pass:
测试配置为通过:
{ "user": "JOHN", "pwd": "pwd1" }
{“ user”:“ JOHN”,“ pwd”:“ pwd1”}
but when I run a test using the API Gateway, I get this error: 但是当我使用API网关运行测试时,出现此错误:
Mon Mar 25 20:47:29 UTC 2019 : Endpoint response body before transformations: {"errorMessage": "'user'", "errorType": "KeyError", "stackTrace": [" File \\"/var/task/lambda_function.py\\", line 6, in lambda_handler\\n post_user = event[\\"user\\"]\\n"]} Mon Mar 25 20:47:29 UTC 2019 : Lambda execution failed with status 200 due to customer function error: 'user'.
Mon Mar 25 20:47:29 UTC 2019:转换前的端点响应主体:{“ errorMessage”:“'用户'”,“ errorType”:“ KeyError”,“ stackTrace”:[“文件\\” / var / task / lambda_function.py \\“,第6行,位于lambda_handler \\ n中post_user = event [\\” user \\“] \\ n”]}星期一3月25日20:47:29 UTC 2019:由于客户功能错误,Lambda执行失败,状态为200 :“用户”。 Lambda request id: f7955f74-e608-4b10-b216-4e4acf682307 Mon Mar 25 20:47:29 UTC 2019 : Method completed with status: 502
Lambda请求ID:f7955f74-e608-4b10-b216-4e4acf682307 Mon Mar 25 20:47:29 UTC 2019:方法已完成,状态为:502
I have defined the API gateway test as follows: 我定义了API网关测试,如下所示:
This is because when the event
object comes from API Gateway, it has some extra information on it. 这是因为
event
对象来自API网关时,它具有一些额外的信息。 It's not as simple as the JSON you use to test from the console. 它不像您用来从控制台进行测试的JSON那样简单。
You need to first access the body
object and then finally your JSON object. 您需要先访问
body
对象,然后再访问JSON对象。
Here's how an event from API Gateway looks like: 来自API网关的事件如下所示:
{
"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": "'{\"user\":\"john\",\"pwd\":\"pwd1\"}'"
}
Keep in mind that the body
from API Gateway always comes stringified, so if you want to access it, you first need to parse this JSON string using json.loads(event["body"])
. 请记住,API Gateway的
body
始终是字符串化的,因此,如果要访问它,则首先需要使用json.loads(event["body"])
解析此JSON字符串。
Remember that the body of your response must be Stringified when returning to API Gateway, as we discussed on this answer . 请记住,如我们在此答案上所讨论的,返回到API网关时, 响应的主体必须为String。
You can see the event sent from API Gateway in the docs 您可以在文档中查看从API网关发送的事件
@Thales Minussi led me to this answer but the key I'm getting from the response is different than he suggested but his suggestion is what helped me so I'm accepting it as the answer @Thales Minussi使我得到了这个答案,但是我从响应中得到的关键与他的建议不同,但是他的建议对我有所帮助,因此我接受它作为答案
I was getting this response. 我得到了这个回应。 The
body
key is coming as null
. body
密钥即将为null
。 but there were queryStringParameters
但是有
queryStringParameters
{
"resource": "/match_creds",
"path": "/match_creds",
"httpMethod": "GET",
"headers": null,
"multiValueHeaders": null,
"queryStringParameters": {
"pwd": "pwd1",
"user": "JOHN"
},
"multiValueQueryStringParameters": {
"pwd": [
"pwd1"
],
"user": [
"JOHN"
]
},
"pathParameters": null,
"stageVariables": null,
"requestContext": {
"path": "/match_creds",
"accountId": "",
"resourceId": "",
"stage": "test-invoke-stage",
"domainPrefix": "testPrefix",
"requestId": "",
"identity": {
"cognitoIdentityPoolId": null,
"cognitoIdentityId": null,
"apiKey": "test-invoke-api-key",
"cognitoAuthenticationType": null,
"userArn": "",
"apiKeyId": "test-invoke-api-key-id",
"userAgent": "",
"accountId": "",
"caller": "",
"sourceIp": "test-invoke-source-ip",
"accessKey": "",
"cognitoAuthenticationProvider": null,
"user": ""
},
"domainName": "testPrefix.testDomainName",
"resourcePath": "/match_creds",
"httpMethod": "GET",
"extendedRequestId": "",
"apiId": ""
},
"body": null,
"isBase64Encoded": false
}
I changed my function to 我将功能更改为
import json
def lambda_handler(event, context):
json_data = event["queryStringParameters"]
user = json_data["user"]
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps(user)
}
您需要激活“集成请求”下的“使用Lambda代理集成”设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.