例如,如果我们想用

得到-用户?name =鲍勃

or

获取/用户/鲍勃

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

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

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

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


当前回答

正如@Jonathan的回答,在集成请求中标记使用Lambda代理集成后,在您的源代码中,您应该按以下格式实现通过502坏网关错误。

NodeJS 8.10:

exports.handler = async (event, context, callback) => {
  // TODO: You could get path, parameter, headers, body value from this
  const { path, queryStringParameters, headers, body } = event;

  const response = {
    "statusCode": 200,
    "headers": {
      "Content-Type": "application/json"
    },
    "body": JSON.stringify({
      path, 
      query: queryStringParameters,
      headers,
      body: JSON.parse(body)
    }),
    "isBase64Encoded": false
  };

  return response;
};

在重新运行API之前,不要忘记在API网关部署您的资源。 Response JSON只返回正文中正确的集合。 你可以从事件中获取路径,参数,头,体值

const {path, queryStringParameters, headers, body} = event;

其他回答

你可以使用Lambda作为“Lambda代理集成”,参考这个[https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html#api-gateway-proxy-integration-lambda-function-python],这个Lambda可用的选项是

对于Nodejs Lambda ”事件。头”、“事件。pathParameters”、“事件。身体”、“event.stageVariables”, 和“event.requestContext”

对于Python Lambda 事件['headers']['parametername']等

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

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

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

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

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

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

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

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

参考医生: 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

需要修改映射模板

正如@Jonathan的回答,在集成请求中标记使用Lambda代理集成后,在您的源代码中,您应该按以下格式实现通过502坏网关错误。

NodeJS 8.10:

exports.handler = async (event, context, callback) => {
  // TODO: You could get path, parameter, headers, body value from this
  const { path, queryStringParameters, headers, body } = event;

  const response = {
    "statusCode": 200,
    "headers": {
      "Content-Type": "application/json"
    },
    "body": JSON.stringify({
      path, 
      query: queryStringParameters,
      headers,
      body: JSON.parse(body)
    }),
    "isBase64Encoded": false
  };

  return response;
};

在重新运行API之前,不要忘记在API网关部署您的资源。 Response JSON只返回正文中正确的集合。 你可以从事件中获取路径,参数,头,体值

const {path, queryStringParameters, headers, body} = event;