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

使用APIGatewayRestResolver触发KeyError: 'httpMethod'问题求助

问题描述

使用AWS Lambda Powertools的APIGatewayRestResolver组件,目标是让API网关返回对应业务场景的错误码(而非固定返回200),但测试Lambda函数时触发KeyError: 'httpMethod'错误,相关代码及错误信息如下:

代码片段

from aws_lambda_powertools import Logger, Tracer, Metrics
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.utilities.typing import LambdaContext

tracer = Tracer()
logger = Logger()
metrics = Metrics()
app = APIGatewayRestResolver()


@app.post("/dept_predictor")
@tracer.capture_method
def dept_predictor():
    post_data: dict = app.current_event.json_body
    print(post_data)
    try:
        print("Received event: " + json.dumps( app.current_event, indent=2))
        print(type(event), '-->', event)
        payload = event['data']
        print(payload)
    
        response  = runtime_client.invoke_endpoint(EndpointName=ENDPOINT_NAME, 
                                                  ContentType='application/json', 
                                                  Body=json.dumps(payload),
                                                  Accept='Accept')
        print(response)
        print(response.keys())
      
        if "errorMessage" in response.keys() and "502 Bad Gateway" in str(response):
            return {"statusCode":"502",'body': response}
            
        elif "errorMessage" in response.keys() and "504 Gateway Time-out" in str(response):
            return {"statusCode":"504",'body': response}
        
            
        result = json.loads(response['Body'].read().decode())
        return {"statusCode":"200",'body': result}
    except Exception as e:
        print("Exception----", traceback.print_exc())
        exception_handler(e)

错误信息

{
  "errorMessage": "'httpMethod'",
  "errorType": "KeyError",
  "stackTrace": [
    "  File \"/opt/python/aws_lambda_powertools/logging/logger.py\", line 442, in decorate\n    return lambda_handler(event, context, *args, **kwargs)\n",
    "  File \"/opt/python/aws_lambda_powertools/tracing/tracer.py\", line 305, in decorate\n    response = lambda_handler(event, context, **kwargs)\n",
    "  File \"/var/task/lambda_function.py\", line 85, in lambda_handler\n    return app.resolve(event, context)\n",
    "  File \"/opt/python/aws_lambda_powertools/event_handler/api_gateway.py\", line 540, in resolve\n    response = self._resolve().build(self.current_event, self._cors)\n",
    "  File \"/opt/python/aws_lambda_powertools/event_handler/api_gateway.py\", line 604, in _resolve\n    method = self.current_event.http_method.upper()\n",
    "  File \"/opt/python/aws_lambda_powertools/utilities/data_classes/common.py\", line 100, in http_method\n    return self[\"httpMethod\"]\n",
    "  File \"/opt/python/aws_lambda_powertools/utilities/data_classes/common.py\", line 17, in __getitem__\n    return self._data[key]\n"
  ]
}
问题分析与解决办法

核心原因

APIGatewayRestResolver是专门适配API Gateway REST API格式事件的组件,它要求输入事件必须包含httpMethod等API Gateway标准字段。出现KeyError的直接原因是测试时传入的事件不符合该格式,比如用了Lambda控制台默认的测试模板(非API Gateway触发结构),或者手动构造的事件缺失关键字段。

此外代码还存在几个潜在问题:

  • 未导入json、traceback模块,未定义runtime_client、ENDPOINT_NAME、exception_handler,会导致后续执行报错
  • 函数中直接使用未定义的event变量,应该通过app.current_event获取事件数据

解决步骤

  1. 使用符合规范的测试事件
    测试时必须传入API Gateway REST API格式的事件,示例如下:

    {
      "resource": "/dept_predictor",
      "httpMethod": "POST",
      "path": "/dept_predictor",
      "body": "{\"data\": {\"key\": \"test-value\"}}",
      "headers": {
        "Content-Type": "application/json"
      },
      "requestContext": {
        "requestId": "test-request-id-123"
      }
    }
    

    在Lambda控制台测试时,可直接选择"API Gateway AWS Proxy"模板作为基础修改。

  2. 修复代码中的依赖与变量问题

    • 补充缺失的导入:import json、import traceback,以及SageMaker Runtime客户端初始化:import boto3; runtime_client = boto3.client('sagemaker-runtime')
    • 定义ENDPOINT_NAME常量:ENDPOINT_NAME = "your-sagemaker-endpoint-name"
    • 替换未定义的event变量为app.current_event,比如payload = app.current_event.json_body['data']
    • 实现exception_handler或直接在异常块返回错误响应,示例:
      except Exception as e:
          logger.exception("请求处理失败")
          return {"statusCode": 500, "body": json.dumps({"error": str(e)})}
      
  3. 调整响应格式
    APIGatewayRestResolver会自动处理响应封装,statusCode建议用数字类型,body需为JSON字符串(不能直接传字典),比如:

    return {"statusCode": 502, "body": json.dumps(str(response))}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:36:27