Sub topic 6
The version 2.0 event and response format
This chapter assumes you know basic HTTP, can read Python, and have seen a Lambda handler with an event and context argument. Earlier chapters covered routes and the proxy integration. Here you look at what API Gateway actually hands your function and what it expects back.
What payload format 2.0 is
When an HTTP API invokes Lambda through a proxy integration, it sends the request as a JSON document called the event. The shape of that document is set by the payload format version. HTTP APIs support 1.0 and 2.0. Version 2.0 is the default for new integrations created in the console and by SAM, and it is smaller and simpler than 1.0.
The shape of the event
Your handler receives a dictionary with these main fields:
| Field | Meaning |
|---|---|
| `version` | Always `"2.0"` for this format |
| `routeKey` | The matched route, such as `GET /items/{id}`, or `$default` |
| `rawPath` | The request path, including the stage name if one is in the URL |
| `rawQueryString` | The query string as one unparsed string |
| `queryStringParameters` | Query parameters as a dictionary, when present |
| `headers` | Request headers with lowercase names |
| `cookies` | A list of `Cookie` header values, when present |
| `pathParameters` | Values for `{name}` segments in the route |
| `requestContext` | Metadata: `routeKey`, `stage`, `http.method`, `requestId`, authorizer data |
| `body` | The body as a string, or missing when there is none |
| `isBase64Encoded` | `true` if `body` is base64 text |
Three details cause most mistakes:
- Header names are lowercase, so read
content-type, notContent-Type. bodyis always a string. You must calljson.loadsyourself.queryStringParameters,pathParametersandbodycan be absent. Useevent.get(...)for them.
The response format
Your function returns a dictionary with three fields:
statusCode: an integer such as200or404.headers: a dictionary of response headers.body: a string.
The following handler uses all of these. It branches on routeKey, reads a path parameter, and parses a JSON body:
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"})In 2.0 you can also return only a value that is not a response object. API Gateway then treats it as the body, assumes a 200 status, and sets content-type to application/json. This shortcut is handy for demos. An explicit response object is clearer, so prefer it.
Common errors
TypeErrororKeyErroronpathParameters. The route has no path parameter, so the field is missing. Branch on the route first.- 502-style failures. If the function returns a malformed response, such as a non-string
bodyinside a response object, the client seesInternal Server Error. Always calljson.dumpson dictionaries. - Missing header lookups. Reading
Content-Typereturns nothing because 2.0 lowercases names. - Binary bodies. When
isBase64Encodedistrue, decode withbase64.b64decodebefore parsing.
Exercise
A client sends GET /items?color=red to a route GET /items. Which event fields hold the value red, and what type is each?
Show answer
queryStringParameters holds {"color": "red"} as a dictionary, and rawQueryString holds "color=red" as a string. queryStringParameters may be absent if the request has no query string, so read it with event.get("queryStringParameters") or {}.