Sub topic 7
Reading requests in your handler
This chapter assumes you know the basics of HTTP and Python, and that you have seen a Lambda handler receive an event and a context. It also assumes you know that an HTTP API sends the version 2.0 payload to a Lambda proxy integration. Here you will learn where each part of a request lives in that event and how to read it safely.
Where each part of the request lives
With payload format 2.0, API Gateway sends your handler one JSON object. You read the request from these fields.
| Request part | Event field | Type |
|---|---|---|
| Route that matched | `requestContext.routeKey` | string |
| HTTP method | `requestContext.http.method` | string |
| Raw path | `rawPath` | string |
| Path parameters | `pathParameters` | dict, or missing |
| Query string | `queryStringParameters` | dict, or missing |
| Headers | `headers` | dict with lowercase keys |
| Body | `body` | string, or missing |
| Body encoding | `isBase64Encoded` | boolean |
Fields that have no value are often absent instead of empty. A request with no query string has no queryStringParameters key. Use event.get(...) with a default, or your handler will raise a KeyError and the client will see a 500 response.
Reading each part
Path parameters come from the placeholders in the route. For the route GET /items/{id}, the value is in pathParameters["id"]. The route guarantees it exists, so direct access is fine there.
Query parameters are strings. If the client calls /items?limit=5, then limit is the string "5", so convert it and handle bad input.
Header names arrive in lowercase, whatever the client sent. Read content-type, not Content-Type.
The body is always a string. Parse it yourself. If isBase64Encoded is true, decode it first. This happens for binary content types.
import base64
import json
def read_body(event):
raw = event.get("body")
if not raw:
return None
if event.get("isBase64Encoded"):
raw = base64.b64decode(raw).decode("utf-8")
return json.loads(raw)
def read_limit(event, default=10, maximum=100):
params = event.get("queryStringParameters") or {}
try:
value = int(params.get("limit", default))
except ValueError:
return default
return max(1, min(value, maximum))
def handler(event, context):
headers = event.get("headers") or {}
content_type = headers.get("content-type", "")
method = event["requestContext"]["http"]["method"]
if method == "POST" and "application/json" not in content_type:
return {"statusCode": 415, "body": "Send application/json"}
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps({"limit": read_limit(event)}),
}Common mistakes
- Indexing a missing key.
event["queryStringParameters"]["limit"]fails when there is no query string. Useor {}first. - Forgetting that values are strings.
"5" > 3raises aTypeErrorin Python 3. - Parsing an empty body.
json.loads("")raisesJSONDecodeError. Check for a missing body first. - Trusting input. Check types and ranges before using any value. Clients can send anything.
Exercise
A client calls GET /items with no query string. Your handler runs event["queryStringParameters"].get("limit") and returns a 500 error. Why does it fail, and how do you fix it?
Show answer
With no query string, API Gateway leaves out the queryStringParameters key, or the value is None. Indexing it raises a KeyError (or an AttributeError on None). Use params = event.get("queryStringParameters") or {} and then params.get("limit").