You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Lambda(Python)如何获取调用函数的API Gateway请求方法?

获取API Gateway触发Lambda时的请求方法

请求方法其实就在event参数里,不同类型的API Gateway(REST API/HTTP API)对应的字段位置略有区别:

  • REST API(传统网关):直接从event['httpMethod']获取,比如GET请求返回'GET',POST请求返回'POST'
  • HTTP API:从event['requestContext']['http']['method']字段中获取

可以用以下Python代码示例来捕获请求方法:

def lambda_handler(event, context):
    # 判断API Gateway类型并获取请求方法
    if 'httpMethod' in event:
        request_method = event['httpMethod']
    elif 'requestContext' in event and 'http' in event['requestContext']:
        request_method = event['requestContext']['http']['method']
    else:
        request_method = '未知请求方法'
    
    return {
        'statusCode': 200,
        'body': f"当前请求方法: {request_method}"
    }

调试小技巧:如果不确定event的结构,可以在函数里添加print(event)语句,然后查看Lambda的执行日志,就能直观看到所有传入的参数字段。

内容的提问来源于stack exchange,提问作者Ivan Kanchev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 09:34:55