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.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 13 views 0 copies

Python code

36 lines
Python 3.9+
import 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

stdout
{
  "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

  1. Use `event.get('isBase64Encoded', False)` to base64-decode the body before parsing for binary uploads
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.