How to Parse an AWS API Gateway Proxy Event in Python
Extract and parse common fields from a mock API Gateway proxy event, turning the JSON body into a native Python dict.
Python code
36 linesimport json
from typing import Any, Dict, Optional
def parse_proxy_event(event: Dict[str, Any]) -> Dict[str, Any]:
"""Extract and parse common fields from an API Gateway proxy event."""
body = event.get("body", "")
if isinstance(body, str):
body = json.loads(body) if body else {}
elif body is None:
body = {}
return {
"method": event.get("httpMethod", ""),
"path": event.get("path", ""),
"query_params": event.get("queryStringParameters") or {},
"headers": event.get("headers") or {},
"path_params": event.get("pathParameters") or {},
"body": body,
"is_base64": event.get("isBase64Encoded", False),
}
if __name__ == "__main__":
sample_event = {
"httpMethod": "POST",
"path": "/users",
"queryStringParameters": {"page": "2", "limit": "10"},
"headers": {"Content-Type": "application/json", "Authorization": "Bearer token123"},
"pathParameters": {"userId": "42"},
"body": '{"name": "Alice", "age": 30}',
"isBase64Encoded": False,
}
parsed = parse_proxy_event(sample_event)
print(json.dumps(parsed, indent=2))
Output
{
"method": "POST",
"path": "/users",
"query_params": {"page": "2", "limit": "10"},
"headers": {"Content-Type": "application/json", "Authorization": "Bearer token123"},
"path_params": {"userId": "42"},
"body": {"name": "Alice", "age": 30},
"is_base64": false
}
How it works
This function uses event.get() with defaults so missing keys won't raise KeyError. The body can arrive as a JSON string, a dict, or None, and we handle all three cases: strings are parsed with json.loads (or left as {} if empty), dicts are used as-is, and None becomes an empty dict. queryStringParameters and pathParameters often arrive as None, so we coalesce to {} with or. The result is a clean, consistent dict you can use directly in your Lambda handler.
Common mistakes
- Forgetting that `event['body']` may be `None` or an empty string and crashing on `json.loads`
- Assuming `queryStringParameters` always exists; it's often `None` for requests without query strings
- Not checking `isBase64Encoded` before decoding binary payloads
- Using `event['body']` directly without a try/except for malformed JSON
Variations
- Use `event.get('isBase64Encoded', False)` to base64-decode the body before parsing for binary uploads
- Parse the body with `json.loads` inside a try/except to return a 400 error for invalid JSON
Real-world use cases
- Writing an AWS Lambda handler behind API Gateway that receives REST requests and needs to extract path, query, and body fields.
- Testing API Gateway integrations locally by feeding mock events into your Lambda logic during development.
- Building a small fleet of Lambdas that share a common event-parsing utility to standardize request handling.
Sponsored
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.