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
相关产品推荐
相关产品推荐

