如何在AWS Lambda函数中获取GET和POST参数

时间:2017-09-07 13:46:28

标签: python aws-lambda aws-api-gateway serverless-framework

我正在使用AWS Lambda + API Gateway + Serverless(Python)。太神奇了!

所以我认为函数中的 event 参数包含很多信息,包括HTTP请求信息

此外,我发现了

queryStringParameters
body

是否包含GET和POST参数的键。

"queryStringParameters": {
  "name": "me"
},

"body": "------WebKitFormBoundaryXAin8CB3c0fwFfAe\r\nContent-Disposition: form-data; name=\"sex\"\r\n\r\nmale\r\n------WebKitFormBoundaryXAin8CB3c0fwFfAe--\r\n",

如何从正文键获取哈希/字典?

由于

2 个答案:

答案 0 :(得分:2)

如果你想在Lambda中完全自由/完全透明,那么你可能想看看Lambda代理集成

import json

def endpoint(event, context):
# With the Lambda proxy integration, API Gateway maps the entire client request to the
# input event parameter of the backend Lambda function as follows:
# {
#     "resource": "Resource path",
#     "path": "Path parameter",
#     "httpMethod": "Incoming request's method name"
#     "headers": {Incoming request headers}
#     "queryStringParameters": {query string parameters }
#     "pathParameters":  {path parameters}
#     "stageVariables": {Applicable stage variables}
#     "requestContext": {Request context, including authorizer-returned key-value pairs}
#     "body": "A JSON string of the request payload."
#     "isBase64Encoded": "A boolean flag to indicate if the applicable request payload is Base64-encode"
# }
    body = {}
    body["event"] = event

    # With the Lambda proxy integration, API Gateway requires the backend Lambda function
    # to return output according to the following JSON format:
    # {
    #     "isBase64Encoded": true|false,
    #     "statusCode": httpStatusCode,
    #     "headers": { "headerName": "headerValue", ... },
    #     "body": "..."
    # }
    response = {
        "statusCode": 200,
        "isBase64Encoded": False,
        "headers": {"x-test-header" : "foobar"},
        "body": json.dumps(body),
    }
    return response

并在模板中

"paths": {
    "/{proxy+}": {
      "x-amazon-apigateway-any-method": {
        "parameters": [{
          "name": "proxy",
          "in": "path",
          "required": true,
          "type": "string"
        }],
        "produces": ["application/json"],
        "responses": {},
        "x-amazon-apigateway-integration": {
          "responses": {
            "default": {
              "statusCode": "200"
            }
          },
          "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:xxxx:function:yyy/invocations",
          "passthroughBehavior": "when_no_match",
          "httpMethod": "POST",
          "cacheNamespace": "57w2aw",
          "cacheKeyParameters": [
            "method.request.path.proxy"
          ],
          "contentHandling": "CONVERT_TO_TEXT",
          "type": "aws_proxy"
        }
      }
    }
}

答案 1 :(得分:-1)

请使用“$ input.params('key')”。

请在API网关集成响应中创建一个正文映射模板,然后尝试“$ input.params('YourQueryStringKey')”

实施例,

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

然后在Lambda函数中,你可以得到如下的值,

var name= event.name;