如何在AWS Gateway Lambda集成中获取查询字符串

时间:2019-07-09 05:07:52

标签: amazon-web-services aws-lambda amazon-cloudformation

我正在尝试运行经过修改的example

AWSTemplateFormatVersion: "2010-09-09"
Description: "My API Gateway and Lambda function"

Parameters:
    apiGatewayStageName:
        Type: "String"
        AllowedPattern: "^[a-z0-9]+$"
        Default: "call"

    lambdaFunctionName:
        Type: "String"
        AllowedPattern: "^[a-zA-Z0-9]+[a-zA-Z0-9-]+[a-zA-Z0-9]+$"
        Default: "my-function"

Resources:
    apiGateway:
        Type: "AWS::ApiGateway::RestApi"
        Properties:
            Name: "my-api"
            Description: "My API"

    apiGatewayRootMethod:
        Type: "AWS::ApiGateway::Method"
        Properties:
            AuthorizationType: "NONE"
            HttpMethod: "GET"
            Integration:
                IntegrationHttpMethod: "POST"
                Type: "AWS_PROXY"
                Uri: !Sub
                    - "arn:aws:apigateway:${AWS::Region}:lambda:path/functions/${lambdaArn}/invocations"
                    - lambdaArn: !GetAtt "lambdaFunction.Arn"
            ResourceId: !GetAtt "apiGateway.RootResourceId"
            RestApiId: !Ref "apiGateway"

    apiGatewayDeployment:
        Type: "AWS::ApiGateway::Deployment"
        DependsOn:
            - "apiGatewayRootMethod"
        Properties:
            RestApiId: !Ref "apiGateway"
            StageName: !Ref "apiGatewayStageName"

    lambdaFunction:
        Type: "AWS::Lambda::Function"
        Properties:
            Code:
                ZipFile: |
                    def handler(event,context):
                      return {
                        'body': 'Hello there {0}'.format(event['requestContext']['identity']['sourceIp']),
                        'headers': {
                          'Content-Type': 'text/plain'
                        },
                        'statusCode': 200
                      }
            Description: "My function"
            FunctionName: !Ref "lambdaFunctionName"
            Handler: "index.handler"
            MemorySize: 128
            Role: !GetAtt "lambdaIAMRole.Arn"
            Runtime: "python2.7"
            Timeout: 10

    lambdaApiGatewayInvoke:
        Type: "AWS::Lambda::Permission"
        Properties:
            Action: "lambda:InvokeFunction"
            FunctionName: !GetAtt "lambdaFunction.Arn"
            Principal: "apigateway.amazonaws.com"
            SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${apiGateway}/*/GET/"

    lambdaIAMRole:
        Type: "AWS::IAM::Role"
        Properties:
            AssumeRolePolicyDocument:
                Version: "2012-10-17"
                Statement:
                    - Action:
                          - "sts:AssumeRole"
                      Effect: "Allow"
                      Principal:
                          Service:
                              - "lambda.amazonaws.com"
            Policies:
                - PolicyDocument:
                      Version: "2012-10-17"
                      Statement:
                          - Action:
                                - "logs:CreateLogGroup"
                                - "logs:CreateLogStream"
                                - "logs:PutLogEvents"
                            Effect: "Allow"
                            Resource:
                                - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${lambdaFunctionName}:*"
                  PolicyName: "lambda"

    lambdaLogGroup:
        Type: "AWS::Logs::LogGroup"
        Properties:
            LogGroupName: !Sub "/aws/lambda/${lambdaFunctionName}"
            RetentionInDays: 90

Outputs:
    apiGatewayInvokeURL:
        Value: !Sub "https://${apiGateway}.execute-api.${AWS::Region}.amazonaws.com/${apiGatewayStageName}"

    lambdaArn:
        Value: !GetAtt "lambdaFunction.Arn"

一切正常,但是当我尝试获取查询字符串时,我得到了null。需要什么必要的配置才能将查询字符串参数传递给lambda?

2 个答案:

答案 0 :(得分:1)

您到底如何尝试获取查询字符串参数?

由于您使用的是代理集成,因此HTTP请求将直接发送到您的lambda函数,而无需在API Gateway上进行任何修改,这意味着查询字符串参数可通过事件对象-event['queryStringParameters']

获得。

我已经尝试过您的示例并将print语句添加到函数中

def lambda_handler(event,context):
    print('query string params', event['queryStringParameters'])
    return {
        'body': 'Hello there {0}'.format(event['requestContext']['identity']['sourceIp']),
        'headers': {
            'Content-Type': 'text/plain'
        },
        'statusCode': 200
    }

如果我到达该API端点,同时指定了一些查询字符串参数(例如?a=1&b=2),我会发现该函数正确记录了这些参数。

CloudWatch日志:

START RequestId: 18f343c8-55ff-4b26-8d74-ae81ce90e8de Version: $LATEST
query string params {'a': '1', 'b': '2'}
END RequestId: 18f343c8-55ff-4b26-8d74-ae81ce90e8de
REPORT RequestId: 18f343c8-55ff-4b26-8d74-ae81ce90e8de  Duration: 20.58 ms  Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 53 MB  

答案 1 :(得分:1)

您将在收到的queryStringParameters的{​​{1}}和multiValueQueryStringParameters子文档中找到查询字符串参数,例如

event

查询字符串参数和其他可用数据的文档可在Amazon API Gateway开发人员指南的Input Format of a Lambda Function for Proxy Integration章中找到。

请注意,Lambda事件中可用的数据因触发Lambda的事件源而异。有时,仅记录传入事件就足够了,例如const queryStringParams = event.queryStringParameters; console.log(JSON.stringify(queryStringParams));