例如,如果我们想用

得到-用户?name =鲍勃

or

获取/用户/鲍勃

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

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

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

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


当前回答

为了获取查询参数,您可以像这样在queryStringParameters对象中获取它们

const name = event.queryStringParameters.name;

第二个是一个干净的URL。如果你的路径是/user/{name},你可以像这样从pathParameters对象中获取值

const name = event.pathParameters.name;

其他回答

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}]

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!

得到-用户?name =鲍勃

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

获取/用户/鲍勃

{
    "name": "$input.params('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;

对我来说有效的方法是

转到集成请求 单击URL查询字符串参数 单击“添加查询字符串” 在name字段中放入查询名称,这里是“name” 在Mapped From字段中,放入method.request.querystring.name