如何在AWS Lambda中获取HTTP方法?

Xav*_*r M 10 http-method amazon-web-services aws-lambda aws-api-gateway

在AWS Lambda代码中,如何获取来自AWS Gateway API的HTTP请求的HTTP方法(例如GET,POST ...)?

我从文档中了解到context.httpMethod是解决方案.

但是,我无法让它发挥作用.

例如,当我尝试添加以下3行时:

    if (context.httpMethod) {
            console.log('HTTP method:', context.httpMethod)
    }
Run Code Online (Sandbox Code Playgroud)

进入"microservice-http-endpoint"蓝图的AWS示例代码如下:

exports.handler = function(event, context) {

    if (context.httpMethod) {
        console.log('HTTP method:', context.httpMethod)
    }

    console.log('Received event:', JSON.stringify(event, null, 2));

    // For clarity, I have removed the remaining part of the sample
    // provided by AWS, which works well, for instance when triggered 
    // with Postman through the API Gateway as an intermediary.
};
Run Code Online (Sandbox Code Playgroud)

我从来没有在日志中有任何东西因为httpMethod总是空的.

gar*_*aat 16

context.httpMethod方法仅适用于模板.因此,如果您想要访问Lambda函数中的HTTP方法,则需要在API网关中找到该方法(例如GET),转到" 集成请求"部分,单击" 映射模板",然后添加新的映射模板对application/json.然后,选择application/json并选择映射模板,然后在编辑框中输入以下内容:

{
    "http_method": "$context.httpMethod"
}
Run Code Online (Sandbox Code Playgroud)

然后,当调用Lambda函数时,您应该在event传入的调用中看到一个新属性,http_method其中包含用于调用该函数的HTTP方法.


Mat*_*ttS 6

API Gateway现在有一个内置的映射模板,可以传递诸如http方法,路由之类的内容。我无法嵌入,因为我没有足够的分数,但是您明白了。

以下是如何在API Gateway控制台中添加它的屏幕截图:

要到达那里,请导航到AWS Console> API网关>(选择资源,IE-GET / home)> Integration Request>映射模板>然后单击application / json并从上面的屏幕快照中显示的下拉列表中选择Method Request Passthrough。

  • 这里的重点不是显示代码,而是向用户显示AWS API Gateway控制台中的面板外观。 (5认同)
  • 文字是可搜索的,图像则不是。Windows错误屏幕也不是可复制粘贴的,但是将消息作为文本可以帮助您找到要搜索的内容。 (2认同)

Jor*_*tas 5

当我从函数创建模板 microservice-http-endpoint-python 项目时,我遇到了这个问题。由于它创建了一个 HTTP API 网关,并且只有 REST API 具有映射模板,因此我无法完成这项工作。仅更改Lambda的代码。

基本上,代码的作用是相同的,但我没有使用事件['httpMethod']

请检查一下:

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)))
Run Code Online (Sandbox Code Playgroud)

我将代码更改为:

操作 = 事件['httpMethod']

操作 = 事件['requestContext']['http']['方法']

我如何获得这个解决方案?

我只是返回整个事件,检查 JSON 并使其以正确的格式工作。