例如,如果我们想用

得到-用户?name =鲍勃

or

获取/用户/鲍勃

如何将这两个例子作为参数传递给Lambda函数?

我在文档中看到了一些关于设置“映射from”的内容,但我在API Gateway控制台中找不到该设置。

method.request.path。在方法请求页面中定义了一个名为parameter-name的路径参数。 method.request.querystring。parameter-name用于在方法请求页面中定义的名为parameter-name的查询字符串参数。

尽管我定义了一个查询字符串,但我没有看到这两个选项。


当前回答

为了回答我自己的一个问题,我遇到了这个技巧。

在API Gateway映射模板中,使用下面的代码来给出HTTP客户端发送的完整查询字符串:

{
    "querystring": "$input.params().querystring"
}

这样做的好处是,您不必在查询字符串中限制自己使用一组预定义的映射键。现在您可以接受查询字符串中的任何键值对,如果这是您想要的处理方式的话。

注意:上面只列出了VTL模板可用的变量$input.params(x)。内部可能会发生变化,querystring可能不再可用。

其他回答

如今,AWS上的API Gateway控制台中包含了一个下拉模板。

对于您的API,单击资源名称…然后

展开“Body Mapping Templates”

输入

application / json

为Content-Type(必须显式地输入),并单击勾

一个新窗口将打开,显示“生成模板”和一个下拉菜单(见图)。

选择

请求传递

然后点击保存

要访问任何变量,只需使用以下语法(这是Python) 例如URL:

https://yourURL.execute-api.us-west-2.amazonaws.com/prod/confirmReg?token=12345&uid=5

可以得到如下变量:

from __future__ import print_function

import boto3
import json

print('Loading function')


def lambda_handler(event, context):
    print(event['params']['querystring']['token'])
    print(event['params']['querystring']['uid'])

因此,不需要显式地命名或映射您想要的每个变量。

Python 3.8 with boto3 v1.16v - 2020年12月

配置路由时,必须配置“API网关”接受路由。否则,除了基本路由之外,其他所有内容都将以{missing auth令牌}或其他内容结束…

一旦你配置API网关接受路由,确保你启用了lambda代理,这样事情就会更好地工作,

要访问路由,

new_route = event['path'] # /{some_url}

访问查询参数

query_param = event['queryStringParameters'][{query_key}]

这里的很多答案都很棒。但我想要简单一点的东西。 我想要一些东西,将与“Hello World”样本免费工作。这意味着我想要一个简单的生成一个匹配查询字符串的请求体:

{
#foreach($param in $input.params().querystring.keySet())
  "$param": "$util.escapeJavaScript($input.params().querystring.get($param))" #if($foreach.hasNext),#end
#end
}

我认为上面的答案在构建一些真实的东西时产生了一些更有用的东西,但是对于使用AWS的模板快速运行一个hello世界来说,这非常有用。

得到-用户?name =鲍勃

{
    "name": "$input.params().querystring.get('name')"
}

获取/用户/鲍勃

{
    "name": "$input.params('name')"
}

Lambda函数需要JSON输入,因此需要解析查询字符串。解决方案是使用Mapping Template将查询字符串更改为JSON。我用它为c# . net核心,所以预期的输入应该是一个JSON与“queryStringParameters”参数。遵循以下4个步骤来实现这一目标:

打开API Gateway资源的映射模板,添加新的application/json content-tyap:

Copy the template below, which parses the query string into JSON, and paste it into the mapping template: { "queryStringParameters": {#foreach($key in $input.params().querystring.keySet())#if($foreach.index > 0),#end"$key":"$input.params().querystring.get($key)"#end} } In the API Gateway, call your Lambda function and add the following query string (for the example): param1=111&param2=222&param3=333 The mapping template should create the JSON output below, which is the input for your Lambda function. { "queryStringParameters": {"param3":"333","param1":"111","param2":"222"} } You're done. From this point, your Lambda function's logic can use the query string parameters. Good luck!