我正在尝试将 API 网关与 Lambda 代理集成,
API 服务器接收带有这些参数的请求,即邮政编码和房屋
https://api.domain.com/getAddressproxy?postcode=XX2YZ&house=123
但是从 API 网关到 Lambda 代理的测试没有返回值
https://xxxxxxxxxx.execute-api.eu-west-1.amazonaws.com/Test/getaddressproxy?postcode=XX2YZ&house=123
我认为问题是 lambda 函数没有将查询字符串参数传递给 API 服务器。
知道如何将查询字符串参数传递给请求对象吗?
代码:
from __future__ import print_function
import json
import urllib2
import ssl
print('Loading function')
target_server = "https://api.domain.com"
def lambda_handler(event, context):
print("Got event\n" + json.dumps(event, indent=2))
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
print("Event here: ")
print(event['path'])
print(event["queryStringParameters"])
req = urllib2.Request(target_server + event['path'])
if event['body']:
req.add_data(event['body'])
# Copy only some headers
copy_headers = ('Accept', 'Content-Type')
for h in copy_headers:
if h in event['headers']:
req.add_header(h, event['headers'][h])
out = {}
try:
resp = urllib2.urlopen(req, context=ctx)
out['statusCode'] = resp.getcode()
out['body'] = resp.read()
except urllib2.HTTPError as e:
out['statusCode'] = e.getcode()
out['body'] = e.read()
return out
请您参考如下方法:
要么你可以像下面这样在 Lambda 中获取查询字符串,
var result = event["queryStringParameters"]['queryStringParam1']
根据您的 API URL,
var postcode = event["queryStringParameters"]['postcode']
var house = event["queryStringParameters"]['house']
或者您可以在集成请求部分使用正文映射模板并获取请求正文和查询字符串。构造一个新的 JSON at body 映射模板,它将包含来自请求正文和查询字符串的数据。当我们添加 body 映射模板时,您的业务逻辑将获得我们在 body 映射模板中构建的 JSON。
获取查询字符串的内部正文映射模板,
$input.params('querystringkey')
例如体内映射模板,
#set($inputRoot = $input.path('$'))
{
"firstName" : "$input.path('$.firstName')",
"lastName" : "$input.path('$.lastName')"
"language" : "$input.params('$.language')"
}
请阅读https://aws.amazon.com/blogs/compute/tag/mapping-templates/有关 body 映射模板的更多详细信息
