我正在尝试使用Python 3.6创建简单的Lambda函数。
该函数应该在请求查询字符串params中获取userId(我在DynamoDB中的主键),如果DB中存在item,则返回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"]
当我在Lambda接口中进行测试时,它可以工作并返回正确的用户,但是当从Postman尝试或使用API网关时,它会返回以下错误
{
"errorMessage": "'userId'",
"errorType": "KeyError",
"stackTrace": [
[
"/var/task/index.py",
7,
"lambda_handler",
"userId = event["userId"]"
]
]
}
您正在使用event["userId"]
,这意味着发送请求有效负载,例如
GET API : api/users/
Request Body payload:
{
"userId":"1234"
}
然后上面的代码工作,假设您要发送userId作为路径参数
GET API :api/user/{userId}
然后你可以访问lambda函数
userId = (event['pathparameters']['userId'])
更好地添加print语句print(事件)并检查cloudwatch日志中的日志