starlette-context

Store and access per-request context data anywhere in a Starlette or FastAPI app.

Library
PyPI
v0.5.1
611stars
MIT License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum.How we score it →
48/100Fair
Development Activity24
Maintenance32
Community48
Maturity60
Momentum28

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation.How we score it →
83/100Excellent
Architecture85
Code Quality84
Innovation80
Learning Curve82

starlette-context is middleware for Starlette (and by extension FastAPI) that captures data about the current request — headers, correlation IDs, request IDs, and anything else you choose — and makes it available from anywhere in your code without threading a Request object through every function call. It solves the common problem of needing request-scoped context deep in your business logic or logging without polluting function signatures.

At its heart is a global context object backed by Python’s contextvars, so each concurrent request sees only its own data even under async concurrency. A pluggable system of plugins extracts standard values such as X-Request-ID, X-Correlation-ID, forwarded-for addresses, and user agents from incoming headers, and it integrates cleanly with the logging module so every log line can automatically carry request identifiers.

What You Get

  • ContextMiddleware / RawContextMiddleware for Starlette and FastAPI apps
  • A global context object safe under async concurrency via contextvars
  • Built-in plugins for request ID, correlation ID, forwarded-for, API key, date, and user agent
  • A base plugin class for extracting your own custom request-scoped values
  • Seamless integration with the standard logging module for contextual logs

Common Use Cases

  • Attaching a correlation/request ID to every log line for a request
  • Propagating trace identifiers across services in a distributed system
  • Accessing request metadata deep in business logic without passing Request around
  • Enriching error reports and metrics with per-request context

Under The Hood

Architecture — The core is ctx.py, which exposes a context proxy over a contextvars.ContextVar so reads and writes are isolated per request/task. The middleware/ package sets the ContextVar at the start of each request and tears it down afterward, running each configured plugin’s extraction on the way in and enrichment on the way out. The plugins/ package holds a base.py plugin contract plus concrete implementations (request_id.py, correlation_id.py, forwarded_for.py, api_key.py, user_agent.py, date_header.py), keyed by the constants in header_keys.py. errors.py guards against accessing context outside a request.

Tech Stack — Pure Python (3.10+) with a single runtime dependency, starlette (>=0.27). Packaged with a modern pyproject.toml and a uv.lock.

Code Quality — Mature and well-tested: a full tests/ suite with codecov reporting, a py.typed marker for strict typing, documentation on Read the Docs, and runnable examples under example/. The plugin abstraction keeps concerns cleanly separated.

API Design — Ergonomic: add one middleware and import a single global context. Plugins provide sensible defaults for common headers, and writing a custom plugin only requires subclassing the base class and implementing a couple of methods.

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers

Search