例如,如果我们想用

得到-用户?name =鲍勃

or

获取/用户/鲍勃

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

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

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

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


当前回答

我的2美分:很多答案建议激活“使用Lambda代理集成”选项,并从$.event中获取参数。queryStringParameter或$.event. pathparameters。但如果你碰巧激活了访问控制允许起源(又名CORS),请继续阅读。

在撰写本文时,Lambda代理集成和CORS还不能很好地协同工作。我的方法是禁用Lambda代理集成的复选框,并手动为请求和响应提供一个映射模板,如下所示:

为application/json请求模板:

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

请注意,我故意将属性命名为queryStringParameters和pathParameters,以模拟Lambda代理集成将生成的名称。这样,如果有一天我激活Lambda代理集成,我的lambdas将不会中断。

application/json的响应模板:

#set($payload = $util.parseJson($input.json('$')))
#set($context.responseOverride.status = $payload.statusCode)
$payload.body

你如何在你的lambda (python)中读取这些?(假设参数是可选的)

def handler(event, context):
    body = event["queryStringParameters"] or {}
    result = myfunction(**body)
    return {
        "statusCode": code,
        "headers": {
            "content-type": "application/json",
        },
        "body": result
    }

其他回答

得到-用户?name =鲍勃

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

获取/用户/鲍勃

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

参考医生: https://docs.aws.amazon.com/apigateway/latest/developerguide/integrating-api-with-aws-services-lambda.html#api-as-lambda-proxy-expose-get-method-with-path-parameters-to-call-lambda-function

需要修改映射模板

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

在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)

现在您应该能够为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