Sub topic 6
The version 2.0 event and response format
This chapter assumes you can write a basic Lambda handler in Python, know what an HTTP API route is, and have seen a proxy integration connect a route to a function. Here you will learn exactly what API Gateway sends to your function and what it expects back.
What payload format 2.0 is
When an HTTP API invokes a Lambda function through a proxy integration, it builds a JSON document called the event. The shape of that document is set by the integration's payload format version. HTTP APIs support two versions, 1.0 and 2.0. Version 1.0 matches the REST API event. Version 2.0 is a flatter, smaller format that exists only for HTTP APIs, and it is the default when you create a Lambda integration through SAM or the console.
Version 2.0 also relaxes the response contract. You can return a plain JSON-serializable value and API Gateway will wrap it for you, which you will see below.
Anatomy of the event
A typical event for GET /items/42?color=red looks like this:
{
"version": "2.0",
"routeKey": "GET /items/{id}",
"rawPath": "/items/42",
"rawQueryString": "color=red",
"cookies": ["session=abc"],
"headers": {
"accept": "*/*",
"content-type": "application/json",
"host": "abc123.execute-api.us-east-1.amazonaws.com"
},
"queryStringParameters": { "color": "red" },
"pathParameters": { "id": "42" },
"requestContext": {
"accountId": "123456789012",
"apiId": "abc123",
"domainName": "abc123.execute-api.us-east-1.amazonaws.com",
"http": {
"method": "GET",
"path": "/items/42",
"protocol": "HTTP/1.1",
"sourceIp": "203.0.113.10",
"userAgent": "curl/8.4.0"
},
"requestId": "abc-123",
"routeKey": "GET /items/{id}",
"stage": "$default",
"time": "26/Nov/2026:17:59:58 +0000",
"timeEpoch": 1795715998000
},
"body": null,
"isBase64Encoded": false
}The fields you will use most are in this table.
| Field | Meaning |
|---|---|
| `version` | Always `"2.0"` for this format. |
| `routeKey` | The route that matched, such as `GET /items/{id}` or `$default`. Also available in `requestContext`. |
| `rawPath` | The request path as received, including the stage name when the stage is not `$default`. |
| `rawQueryString` | The unparsed query string. |
| `cookies` | A list of `Cookie` header values, split on semicolons. Present only if the request has cookies. |
| `headers` | Header names in lowercase. Multiple values of the same header are joined with commas. |
| `queryStringParameters` | Parsed query values. Repeated keys are joined with commas. Absent when there is no query string. |
| `pathParameters` | Values for `{name}` segments in the route. Absent when the route has none. |
| `requestContext.http` | Method, path, protocol, source IP and user agent. |
| `requestContext.authorizer` | Output of a JWT or Lambda authorizer, when one is attached. |
| `body` | The request body as a string, or absent when there is none. |
| `isBase64Encoded` | `true` when `body` is base64 text because the content is binary. |
Differences from version 1.0
- There is no
httpMethodorpathat the top level. UserequestContext.http.methodandrequestContext.http.path. - There is no
multiValueHeadersormultiValueQueryStringParameters. Repeated values are comma-joined. - Header names are always lowercase, so
event["headers"]["content-type"]works butContent-Typedoes not. - Cookies are lifted into their own
cookieslist.
Things that are missing, not empty
Several keys are omitted entirely when they have no value. A handler that indexes them directly raises KeyError and the caller gets a 500.
pathParametersis missing on routes without path parameters, including$default.queryStringParametersis missing when the URL has no query string.bodymay be missing ornull.cookiesis missing when no cookie was sent.
Read these with .get() and a safe default:
def handler(event, context):
query = event.get("queryStringParameters") or {}
path_params = event.get("pathParameters") or {}
cookies = event.get("cookies") or []
body = event.get("body") or ""
color = query.get("color", "any")
return {"color": color, "cookie_count": len(cookies), "body_length": len(body)}Note the or {} form. It handles both a missing key and an explicit null, which .get(key, {}) alone does not.
The response format
Your function returns a JSON object with these fields:
| Field | Type | Notes |
|---|---|---|
| `statusCode` | integer | The HTTP status. Defaults to 200 in the inferred case below. |
| `headers` | object | Single-value response headers. |
| `cookies` | list of strings | Each entry becomes one `Set-Cookie` header. |
| `body` | string | Must be a string. Serialize JSON yourself. |
| `isBase64Encoded` | boolean | Set `true` when `body` holds base64 text for binary output. |
Because cookies is its own list, you can send several Set-Cookie headers. Version 2.0 has no multiValueHeaders, so a response that needs multiple values for any other header cannot express them as separate headers. Join them into one comma-separated value only where the header's syntax allows it.
import json
def handler(event, context):
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"cookies": ["session=abc123; HttpOnly; Secure; Path=/", "theme=dark; Path=/"],
"body": json.dumps({"ok": True}),
}The inferred response
With version 2.0, if your function returns valid JSON that is not a response object with a statusCode, API Gateway treats the returned value as the body. It sets the status to 200 and the content-type to application/json.
def handler(event, context):
return {"message": "hello", "route": event["requestContext"]["routeKey"]}This is convenient for prototypes. In production, return the full object so that you control the status code and headers. An inferred response also hides mistakes: if you meant to return a 404 but misspelled statusCode, the caller sees a 200 with your whole dictionary as the body.
What happens with a malformed response
If the function raises an exception, times out, or returns something that API Gateway cannot interpret, the client receives a generic error. The two you meet most often are:
500 Internal Server Errorwhen the function raises an unhandled exception. The details are in the function's CloudWatch log group, not in the response.502 Bad Gatewaywhen the response is malformed, for example abodythat is a dictionary instead of a string, or astatusCodethat is not an integer.
Unlike the inferred case, a returned object that does include statusCode is validated strictly. The most common cause of a 502 is returning "body": {"a": 1} instead of "body": json.dumps({"a": 1}).
Binary bodies
Binary request bodies, such as images, arrive base64-encoded with isBase64Encoded set to true. Decode them before use. To return binary data, base64-encode it and set isBase64Encoded to true. API Gateway decodes it before sending it to the client.
import base64
def handler(event, context):
body = event.get("body") or ""
raw = base64.b64decode(body) if event.get("isBase64Encoded") else body.encode("utf-8")
encoded = base64.b64encode(raw[::-1]).decode("ascii")
return {
"statusCode": 200,
"headers": {"content-type": "application/octet-stream"},
"body": encoded,
"isBase64Encoded": True,
}This handler reverses the bytes it receives and returns them as binary. An HTTP API treats some content types as binary automatically, so check the content type your client sends when you debug a body that looks garbled.
How a request flows
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| 500 with `KeyError: 'pathParameters'` in logs | Handler indexes an omitted key | Use `event.get("pathParameters") or {}` |
| 502 Bad Gateway | `body` is not a string, or `statusCode` is not an integer | Call `json.dumps` on the body and return an `int` status |
| Header lookup returns `None` | Code used `Content-Type` with capital letters | Use lowercase names such as `content-type` |
| `AttributeError` on `event["httpMethod"]` | Code written for version 1.0 | Use `event["requestContext"]["http"]["method"]` |
| Garbled upload | Body is base64 and `isBase64Encoded` was ignored | Decode when the flag is `true` |
| 200 with an unexpected body | Inferred response was used by accident | Return an explicit `statusCode` |
Testing against a real event
You can invoke the handler locally without deploying by passing it a hand-built version 2.0 event. This catches missing-key bugs early.
from app import handler
event = {
"version": "2.0",
"routeKey": "GET /items/{id}",
"requestContext": {"routeKey": "GET /items/{id}", "http": {"method": "GET"}},
"pathParameters": {"id": "42"},
}
result = handler(event, None)
assert result["statusCode"] == 200
print(result)Then try the same handler with pathParameters removed to confirm that your code returns a 4xx rather than crashing.
Exercise
A route POST /upload returns 502 Bad Gateway. The handler ends with return {"statusCode": 201, "body": {"saved": True}}. What is wrong, and how do you fix it?
Show answer
The body is a dictionary, but a version 2.0 response requires a string, so API Gateway rejects the response as malformed. Serialize it: "body": json.dumps({"saved": True}), adding import json at the top of the file.
Exercise
Your handler runs event["queryStringParameters"]["page"] and works in testing but returns 500 for requests without a query string. Rewrite the line so it defaults to "1".
Show answer
Use (event.get("queryStringParameters") or {}).get("page", "1"). The or {} covers the key being absent or null, and the second .get supplies the default.