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

AWS API Gateway调用Lambda时未传递数据问题求助

解决API Gateway调用Lambda更新DynamoDB的Key Error问题

你遇到的问题核心在于Lambda测试事件和API Gateway触发时的event结构完全不同:

  • 直接测试Lambda时,你传入的JSON会直接作为event字典的顶层内容
  • 但通过API Gateway触发时,请求体不会直接挂在event根节点,而是被封装在event['body']字段里,而且是JSON字符串格式,不是现成的字典

直接取event["Highscore"]自然会找不到键,报Key Error。

修改后的Lambda代码

import boto3
import json


def updateScore(event, context):
    dynamodb_resource = boto3.resource('dynamodb', region_name='us-east-1')
    table = dynamodb_resource.Table('Highscore')
    
    # 解析API Gateway传入的请求体(JSON字符串转字典)
    try:
        body = json.loads(event['body'])
    except (KeyError, json.JSONDecodeError):
        return {
            "statusCode": 400,
            "headers": {
                'Access-Control-Allow-Headers': 'application/json',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'PUT'
            },
            'body': json.dumps({"error": "Invalid request body"})
        }
    
    # 从解析后的body里取Highscore
    score = body["Highscore"]
    response = table.update_item(
        Key={'ID': 0},
        ExpressionAttributeNames={"#hs": "Highscore"},
        UpdateExpression="SET #hs = :val1",
        ExpressionAttributeValues={":val1": score}
    )

    return {
        "statusCode": 200,
        "headers": {
            'Access-Control-Allow-Headers': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'PUT'
        },
        'body': json.dumps(score)  # 返回值要转成JSON字符串,符合API Gateway要求
    }

额外注意点

  • 原代码同时初始化了dynamodb_client和dynamodb_resource,但只用了resource,可删掉client的初始化减少冗余
  • API Gateway要求返回的body字段必须是字符串,之前直接返回数字不符合规范,需转成JSON字符串
  • 确保API Gateway的集成方式是Lambda代理集成,如果是非代理集成,event结构会不同,需要额外配置映射模板

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:05:26