How to get the HTTP method in AWS Lambda?

后端 未结 3 803
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 06:26

In an AWS Lambda code, how can I get the HTTP method (e.g. GET, POST...) of an HTTP request coming from the AWS Gateway API?

I understand from the documentation tha

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-04 06:30

    I had this problem when I created a template microservice-http-endpoint-python project from functions. Since it creates an HTTP API Gateway, and only REST APIs have Mapping template I was not able to put this work. Only changing the code of Lambda.

    Basically, the code does the same, but I am not using the event['httpMethod']

    Please check this:

    import boto3
    import json
    
    print('Loading function')
    dynamo = boto3.client('dynamodb')
    
    
    def respond(err, res=None):
        return {
            'statusCode': '400' if err else '200',
            'body': err.message if err else json.dumps(res),
            'headers': {
                'Content-Type': 'application/json',
            },
        }
    
    
    def lambda_handler(event, context):
        '''Demonstrates a simple HTTP endpoint using API Gateway. You have full
        access to the request and response payload, including headers and
        status code.
    
        To scan a DynamoDB table, make a GET request with the TableName as a
        query string parameter. To put, update, or delete an item, make a POST,
        PUT, or DELETE request respectively, passing in the payload to the
        DynamoDB API as a JSON body.
        '''
        print("Received event: " + json.dumps(event, indent=2))
    
        operations = {
            'DELETE': lambda dynamo, x: dynamo.delete_item(**x),
            'GET': lambda dynamo, x: dynamo.scan(**x),
            'POST': lambda dynamo, x: dynamo.put_item(**x),
            'PUT': lambda dynamo, x: dynamo.update_item(**x),
        }
        
        operation =  event['requestContext']['http']['method']
    
        if operation in operations:
            payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body'])
            return respond(None, operations[operation](dynamo, payload))
        else:
            return respond(ValueError('Unsupported method "{}"'.format(operation)))
    

    I changed the code from:

    operation = event['httpMethod']

    to

    operation = event['requestContext']['http']['method']

    How do I get this solution?

    I simply returned the entire event, checked the JSON and put it to work with the correct format.

提交回复
热议问题