Sub topic 7
Reading requests in your handler
This chapter assumes you can write a basic Lambda handler in Python and know how a route is connected to a function through proxy integration. It also assumes you know the shape of a version 2.0 event at a high level. Here you will learn where each part of an HTTP request ends up in that event, which fields can be missing, and how to read them without raising an exception on a bad request.
Where each part of the request lives
With payload format 2.0, API Gateway turns the HTTP request into one JSON object and passes it to your handler as event. The fields you read most often are listed below.
| Request part | Event field | Type and notes |
|---|---|---|
| Route that matched | `routeKey` and `requestContext.routeKey` | String such as `GET /items/{id}`, or `$default` |
| Method | `requestContext.http.method` | Upper-case string |
| Path | `rawPath` | The path as sent, including the stage prefix on non-`$default` stages |
| Path parameters | `pathParameters` | Dict. The key is **absent** when the route has no parameters |
| Query string | `queryStringParameters` | Dict of strings. The key is **absent** when there is no query string |
| Raw query string | `rawQueryString` | Unparsed string, empty when there is none |
| Headers | `headers` | Dict with **lower-case** names |
| Cookies | `cookies` | List of `name=value` strings. Cookies are not in `headers` |
| Body | `body` | String, absent or null when there is no body |
| Body encoding | `isBase64Encoded` | `true` when `body` is base64 text |
| Caller identity | `requestContext.authorizer` | Present only when the route has an authorizer |
Fields that may be missing
Most handler bugs on this topic come from one rule: API Gateway omits empty collections instead of sending empty ones. A GET /items request with no query string has no queryStringParameters key at all. Code like event["queryStringParameters"]["limit"] raises KeyError on that request, and the client sees a 500 error.
Use .get() with a safe default, and also guard against an explicit None:
params = event.get("queryStringParameters") or {}
limit = params.get("limit", "10")The same applies to pathParameters, headers, cookies and body. For routes with a path parameter such as GET /items/{id}, API Gateway only matches the route when the parameter is present, so event["pathParameters"]["id"] is safe there. Use .get() anywhere a route such as $default could send you other requests.
Query strings and repeated parameters
Every value in queryStringParameters is a string, so convert numbers yourself. If a client repeats a parameter, as in ?tag=a&tag=b, version 2.0 joins the values with a comma into "a,b". You cannot tell a repeated parameter from a single value that contains a comma. If the difference matters, parse rawQueryString with urllib.parse.parse_qs, which returns a list for every key.
from urllib.parse import parse_qs
tags = parse_qs(event.get("rawQueryString", "")).get("tag", [])Headers and cookies
Header names arrive in lower case, whatever the client sent. Read headers.get("content-type"), never headers.get("Content-Type"). Repeated headers are also joined with commas.
Cookies are separate from headers in version 2.0. API Gateway removes the cookie header and puts each cookie into the cookies list as a name=value string.
def get_cookies(event):
result = {}
for item in event.get("cookies") or []:
name, _, value = item.partition("=")
result[name.strip()] = value
return resultReading the body
body is always a string or missing. API Gateway does not parse JSON for you. If the request has a binary content type, or the body is not valid text, isBase64Encoded is true and body holds base64 text. Check the flag before you parse.
Three failures need handling: no body, a body that is not valid text after decoding, and a body that is not valid JSON. Each is a client error, so return a 400 response and do not let the exception escape. An uncaught exception in the handler becomes a generic 500 response and tells the client nothing.
A complete, runnable example
This module parses a GET /items request with a bounded limit and a POST /items request with a JSON body. It raises a small exception for client mistakes and turns it into a 400 response in one place. You can run it directly with python app.py, because it ends with two sample events.
import base64
import json
from urllib.parse import parse_qs
class BadRequest(Exception):
pass
def respond(status, body):
return {
"statusCode": status,
"headers": {"content-type": "application/json"},
"body": json.dumps(body),
}
def get_json_body(event):
body = event.get("body")
if not body:
raise BadRequest("Request body is required")
headers = event.get("headers") or {}
content_type = headers.get("content-type", "")
if not content_type.startswith("application/json"):
raise BadRequest("content-type must be application/json")
try:
if event.get("isBase64Encoded"):
body = base64.b64decode(body).decode("utf-8")
return json.loads(body)
except ValueError:
# Covers bad base64, bad UTF-8 and bad JSON.
raise BadRequest("Body must be valid JSON")
def get_limit(event):
params = event.get("queryStringParameters") or {}
raw = params.get("limit", "10")
try:
limit = int(raw)
except ValueError:
raise BadRequest("limit must be an integer")
if not 1 <= limit <= 100:
raise BadRequest("limit must be between 1 and 100")
return limit
def handler(event, context):
route = event["requestContext"]["routeKey"]
try:
if route == "GET /items":
tags = parse_qs(event.get("rawQueryString", "")).get("tag", [])
return respond(200, {"limit": get_limit(event), "tags": tags})
if route == "POST /items":
return respond(201, {"created": get_json_body(event)})
except BadRequest as error:
return respond(400, {"message": str(error)})
return respond(404, {"message": "Not found"})
if __name__ == "__main__":
get_event = {
"requestContext": {"routeKey": "GET /items"},
"rawQueryString": "limit=5&tag=a&tag=b",
"queryStringParameters": {"limit": "5", "tag": "a,b"},
}
post_event = {
"requestContext": {"routeKey": "POST /items"},
"headers": {"content-type": "application/json"},
"body": '{"name": "widget"}',
"isBase64Encoded": False,
}
print(handler(get_event, None))
print(handler(post_event, None))
print(handler({"requestContext": {"routeKey": "POST /items"}}, None))The third call has no body, so it prints a 400 response. That is the behavior you want for a client mistake.
Identity from an authorizer
When a route has an authorizer, the result appears under requestContext.authorizer. For a JWT authorizer, the verified claims are at requestContext.authorizer.jwt.claims. For a Lambda authorizer that uses the simple response format, the context dictionary it returned is at requestContext.authorizer.lambda. Trust these fields, because API Gateway filled them in after checking the token. Do not trust a user ID that the client sent in the body or in a header you did not verify.
def get_user(event):
authorizer = event["requestContext"].get("authorizer") or {}
claims = authorizer.get("jwt", {}).get("claims", {})
return claims.get("sub")Common mistakes
- Indexing instead of
.get(). A missingqueryStringParameters,headersorbodyraisesKeyErrorand returns a 500 response. - Mixed-case header lookups.
headers["Content-Type"]fails because names are lower-cased. - Parsing before decoding. A base64 body passed to
json.loadsraises an error. CheckisBase64Encodedfirst. - Expecting numbers. Query and path values are strings. Convert and range-check them.
- Reading the cookie header. Version 2.0 moves cookies into the
cookieslist. - Assuming one value per query key. Repeated keys are comma-joined. Use
rawQueryStringwhen you need exact values.
Exercise
A client calls GET /items with no query string. Your handler contains limit = event["queryStringParameters"].get("limit", "10"). What does the client receive, and how do you fix the line?
Show answer
The event has no queryStringParameters key, so the line raises KeyError. The unhandled exception becomes a 500 response. Fix it with limit = (event.get("queryStringParameters") or {}).get("limit", "10"), which also covers a key that is present but null.
Exercise
A client sends ?tag=red&tag=blue. queryStringParameters["tag"] is "red,blue". How can you get the list ["red", "blue"], and why can't you just split the string on commas?
Show answer
Parse rawQueryString with urllib.parse.parse_qs(event.get("rawQueryString", "")), which returns {"tag": ["red", "blue"]}. Splitting on commas is unreliable because a single value such as ?tag=red,blue produces the same joined string as two repeated parameters.