例如,如果我们想用

得到-用户?name =鲍勃

or

获取/用户/鲍勃

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

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

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

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


当前回答

现在您应该能够为Lambda使用新的代理集成类型来自动获得标准形状的完整请求,而不是配置映射。

见:http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html api-gateway-set-up-lambda-proxy-integration-on-proxy-resource

其他回答

接受的答案对我来说很好,但是扩展gimenete的答案,我想要一个通用的模板,我可以用它来传递所有的查询/路径/头参数(目前只是字符串),我得到了下面的模板。我把它贴在这里,以防有人觉得有用:

#set($keys = [])
#foreach($key in $input.params().querystring.keySet())
  #set($success = $keys.add($key))
#end

#foreach($key in $input.params().headers.keySet())
  #if(!$keys.contains($key))
    #set($success = $keys.add($key))
  #end
#end

#foreach($key in $input.params().path.keySet())
  #if(!$keys.contains($key))
    #set($success = $keys.add($key))
  #end
#end

{
#foreach($key in $keys)
  "$key": "$util.escapeJavaScript($input.params($key))"#if($foreach.hasNext),#end
#end
}

查询字符串可以直接在lambda中用javascript解析

GET /user?name =鲍勃

 var name = event.queryStringParameters.name;

但是,这并不能解决GET用户/bob的问题。

为了将参数传递给lambda函数,您需要在API Gateway请求和lambda函数之间创建映射。映射在所选API Gateway资源的集成请求->映射模板部分中完成。

创建一个application/json类型的映射,然后在右侧编辑(单击铅笔)模板。

映射模板实际上是一个Velocity模板,你可以使用if,循环,当然还可以打印变量。模板中注入了这些变量,你可以分别访问查询字符串参数、请求头等等。使用下面的代码,您可以重新创建整个查询字符串:

{
    "querystring" : "#foreach($key in $input.params().querystring.keySet())#if($foreach.index > 0)&#end$util.urlEncode($key)=$util.urlEncode($input.params().querystring.get($key))#end",
    "body" : $input.json('$')
}

注意:点击复选符号保存模板。您可以使用资源中的“test”按钮测试更改。但是为了在AWS控制台中测试查询字符串参数,您需要在资源的Method Request部分中定义参数名称。

注意:查看Velocity用户指南以获得关于Velocity模板语言的更多信息。

然后在你的lambda模板中,你可以执行以下操作来解析查询字符串:

var query = require('querystring').parse(event.querystring)
// access parameters with query['foo'] or query.foo

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

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

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

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

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

让它工作的步骤是:

在API网关控制台中…

Go to Resources -> Integration Request Click on the plus or edit icon next to the templates dropdown (odd I know since the template field is already open and the button here looks greyed out) Explicitly type application/json in the content-type field even though it shows a default (if you don't do this it will not save and will not give you an error message) put this in the input mapping { "name": "$input.params('name')" } click on the check box next to the templates dropdown (I'm assuming this is what finally saves it)