简体   繁体   English

python将querystring参数传递给API网关

[英]python pass querystring parameters to API gateway

I am trying to integrate API gateway with Lambda proxy, 我正在尝试将API网关与Lambda代理集成,

The API server receives the request with these parameters ie postcode and house API服务器使用这些参数(即邮政编码和房屋)接收请求

https://api.domain.com/getAddressproxy?postcode=XX2YZ&house=123

However tests from the API gateway to the Lambda proxy does not return values 但是,从API网关到Lambda代理的测试不会返回值

https://xxxxxxxxxx.execute-api.eu-west-1.amazonaws.com/Test/getaddressproxy?postcode=XX2YZ&house=123

I think the issue is that the lambda function is not passing the query string parameters to the API server. 我认为问题在于lambda函数没有将查询字符串参数传递给API服务器。

Any idea how i can pass the query string parameters to the request object? 知道我如何将查询字符串参数传递给请求对象吗?

Code: 码:

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

Either you can take query string inside Lambda like below, 您可以像下面这样在Lambda中获取查询字符串,

var result =  event["queryStringParameters"]['queryStringParam1']

According to your API URL, 根据您的API URL,

var postcode =  event["queryStringParameters"]['postcode']
var house =  event["queryStringParameters"]['house']

or you can use body mapping template in the integration request section and get request body and query strings. 或者,您可以在集成请求部分中使用正文映射模板,并获取请求正文和查询字符串。 Construct a new JSON at body mapping template, which will have data from request body and query string. 在正文映射模板上构造一个新的JSON,该模板将包含请求正文和查询字符串中的数据。 As we are adding body mapping template your business logic will get the JSON we have constructed at body mapping template. 当我们添加主体映射模板时,您的业务逻辑将获得我们在主体映射模板处构造的JSON。

Inside body mapping template to get query string please do , 体内映射模板以获取查询字符串请做,

$input.params('querystringkey') $ input.params('querystringkey')

For example inside body mapping template, 例如在人体贴图模板中,

 #set($inputRoot = $input.path('$')) { "firstName" : "$input.path('$.firstName')", "lastName" : "$input.path('$.lastName')" "language" : "$input.params('$.language')" } 

Please read https://aws.amazon.com/blogs/compute/tag/mapping-templates/ for more details on body mapping template 请阅读https://aws.amazon.com/blogs/compute/tag/mapping-templates/了解有关人体贴图模板的更多详细信息

event["queryStringParameters"] is a dictionary if the API Gateway passes one or None if not passed. 如果API网关通过了一个,则event["queryStringParameters"]是一个字典,如果未通过,则为None Convert this to a query string and append to the Request URL. 将此转换为查询字符串并附加到请求URL。

...
import urllib
...

qs = urllib.urlencode(event["queryStringParameters"] or {})
req = urllib2.Request(
        ''.join(
          (target_server, event['path'], '?', qs)
        )
      )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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