Python lambda 函数返回 KeyError

Jam*_*amZ 9 python amazon-web-services python-3.x aws-lambda

我正在尝试使用 Python 3.6 创建简单的 Lambda 函数。

该函数应该在请求查询字符串参数中获取一个 userId(我在 DynamoDB 中的主键),如果项目存在于 DB 中,则返回 200,这是我的 lambda 函数

import boto3
import os
from boto3.dynamodb.conditions import Key, Attr

def lambda_handler(event, context):

  userId = event["userId"]

  dynamodb = boto3.resource('dynamodb')
  table = dynamodb.Table(os.environ['Customers'])
  items = table.query(
  KeyConditionExpression=Key('userId').eq(userId)
  )

  return items["Items"]
Run Code Online (Sandbox Code Playgroud)

当我在 Lambda 接口中进行测试时,它可以工作并返回正确的用户,但是,当从 Postman 尝试或使用 API Gateway 时,它返回以下错误

{
"errorMessage": "'userId'",
"errorType": "KeyError",
"stackTrace": [
    [
        "/var/task/index.py",
        7,
        "lambda_handler",
        "userId = event["userId"]"
    ]
]
}
Run Code Online (Sandbox Code Playgroud)
  • 我在这里错过了什么?
  • 努力理解“事件”,文档说明它是一个 python 字典,但是当从 Postman 或 API Gateway 调用时,我如何打印它的结果并实际调试 lambda?

Pan*_*dar 4

您正在使用event["userId"],这意味着发送请求有效负载

GET API : api/users/
Request Body payload:

{
"userId":"1234"
}
Run Code Online (Sandbox Code Playgroud)

那么上面的代码可以工作,假设您想将 userId 作为路径参数发送

GET API :api/user/{userId}
Run Code Online (Sandbox Code Playgroud)

然后你可以在 lambda 函数中访问

userId = (event['pathparameters']['userId'])
Run Code Online (Sandbox Code Playgroud)

最好添加打印语句 print(event) 并检查cloudwatch日志中的日志