在Lambda函数中,根据API网关事件解析路径参数和查询参数时,必须正确地设置API网关触发器的集成请求模板。 Lambda函数应该只返回有效的HTTP响应状况代码和有效负载。以下是Python代码示例:
import json
def lambda_handler(event, context):
http_method = event['httpMethod']
path_params = event['pathParameters']
query_params = event['queryStringParameters']
if http_method == 'GET' and 'id' in path_params:
# 根据ID获取信息
response_payload = {'name': 'John Doe'}
status_code = 200
else:
# 未找到资源的情况
response_payload = {'message': 'Not Found'}
status_code = 404
# 返回HTTP响应
response = {
'statusCode': status_code,
'body': json.dumps(response_payload),
'headers': {'Content-Type': 'application/json'}
}
return response