Sub topic 2
The version 2.0 event and response format
Assume you know basic HTTP methods, status codes, headers, JSON, Python, and Lambda fundamentals. This chapter uses an HTTP API with a Lambda proxy integration. API Gateway sends the request to Lambda as an event and expects a structured response.
Version 2.0 event
Payload format version 2.0 groups request details into predictable fields. The route key identifies the matched route. Path parameters, query parameters, headers, and the body appear in separate fields.
import json
def respond(status, body):
return {
"statusCode": status,
"headers": {"content-type": "application/json"},
"body": json.dumps(body),
}
def handler(event, context):
route = event["requestContext"]["routeKey"]
if route == "GET /items/{id}":
item_id = event["pathParameters"]["id"]
return respond(200, {"id": item_id})
if route == "POST /items":
try:
payload = json.loads(event.get("body") or "")
except json.JSONDecodeError:
return respond(400, {"message": "Body must be valid JSON"})
return respond(201, {"created": payload})
return respond(404, {"message": "Not found"})For a request such as GET /items/42, pathParameters["id"] contains "42". Query values are in queryStringParameters. Header names might be normalized, so read them without relying on capitalization.
Responses and errors
A response needs a numeric statusCode and a string body. JSON objects must be serialized with json.dumps. Set content-type when returning JSON.
Return client errors such as 400 or 404 deliberately. Catch expected parsing or validation errors. Unexpected exceptions should be logged and allowed to produce a server error. A malformed Lambda response can produce a 502 integration error, so test the response shape as carefully as the business logic.
> callout note > The body field is a string, even when the content is JSON. Returning a Python dictionary directly is not a valid proxy response.
Defining the API with AWS SAM
AWS SAM is an infrastructure-as-code tool for declaring serverless resources. Explicitly set payload format 2.0 so the handler and template agree.
Resources:
ItemsApi:
Type: AWS::Serverless::HttpApi
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: app.handler
CodeUri: src/
Events:
GetItem:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /items/{id}
Method: GET
PayloadFormatVersion: '2.0'
CreateItem:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /items
Method: POST
PayloadFormatVersion: '2.0'Exercise
What should the handler return when the POST body is not valid JSON?
Show answer
Return a response with status code 400 and a JSON string body explaining that the body is invalid.