Install & Compatibility
Where this runs
tested against v0.5.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.340s · 20.8MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 1.9s · import 0.312s · 21MB
19MB installed
● package 19MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
ContextMiddleware
✓ from starlette_context.middleware import ContextMiddleware
RawContextMiddleware
✓ from starlette_context.middleware import RawContextMiddleware
Use RawContextMiddleware for streaming or file responses, or when avoiding BaseHTTPMiddleware limitations.
context
✓ from starlette_context import context
✗ from starlette_context.context import context
The context object is directly available from the top-level package.
plugins
✓ from starlette_context import plugins
Provides access to built-in plugins like RequestIdPlugin and CorrelationIdPlugin.
request_cycle_context
✓ from starlette_context import request_cycle_context
A context manager for manual context management, often used in tests or FastAPI dependencies.
This example demonstrates how to set up `ContextMiddleware` with basic plugins (`RequestIdPlugin`, `CorrelationIdPlugin`) and access/modify the `context` object within a Starlette route. When you access '/', the response will include the generated request and correlation IDs, along with any custom data added to the context. To run, save as `example.py` and execute `uvicorn example:app --port 8000`.
import uvicorn
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette_context import context, plugins
from starlette_context.middleware import ContextMiddleware
async def homepage(request):
# Access and modify context data
context["user_id"] = "123"
context["custom_data"] = "Hello from Starlette Context!"
return JSONResponse(context.data)
routes = [
Route("/", endpoint=homepage)
]
middleware = [
Middleware(
ContextMiddleware,
plugins=(
plugins.RequestIdPlugin(),
plugins.CorrelationIdPlugin(),
)
)
]
app = Starlette(routes=routes, middleware=middleware)
if __name__ == "__main__":
# Run with `uvicorn example:app --port 8000`
uvicorn.run(app, host="0.0.0.0", port=8000)
Debug
Known issues
breakingPython 3.9 and Python 3.8 support has been dropped in recent versions. Version 0.5.0 requires Python 3.10+, and v0.4.0 required Python 3.9+. Ensure your environment uses Python 3.10 or newer.fixUpgrade your Python environment to 3.10 or higher.
affects: >=0.4.0, >=0.5.0
breakingSupport for Starlette versions below 0.27.0 was dropped in `starlette-context` v0.4.0. Ensure your Starlette installation is up-to-date.fixUpgrade Starlette to version 0.27.0 or newer (e.g., `pip install 'starlette>=0.27.0'`).
affects: >=0.4.0
breakingIn v0.5.1, the `HeaderKeys` enum was changed to `StrEnum` to ensure consistent `str()` behavior across Python versions (e.g., `str(HeaderKeys.api_key)` now consistently returns `'X-API-Key'`). Code relying on the prior inconsistent string representation (e.g., `'HeaderKeys.api_key'` on Python 3.11+) might break.fixReview any code that explicitly converts `HeaderKeys` enum members to strings and ensure it expects the header key string (e.g., 'X-API-Key').
affects: >=0.5.1
gotchaAccessing the `context` object outside of a request-response cycle (i.e., when no middleware is active or `request_cycle_context` is not used) will raise a `ContextDoesNotExistError`. This can happen during application startup or in background tasks not tied to a request.fixAlways use `if context.exists():` before accessing `context.data` or `context[...]` outside of a guaranteed request cycle. For tests or specific asynchronous tasks, wrap the code with `async with request_cycle_context():` to establish a temporary context.
affects: >=0.3.2
breakingAs of v0.3.2, attempting to access a non-existent context now raises `ContextDoesNotExistError` instead of a generic `RuntimeError`. While `ContextDoesNotExistError` inherits from `RuntimeError` for backward compatibility, specific `except RuntimeError` blocks might need to be updated to `except ContextDoesNotExistError:` for clearer exception handling.fixUpdate exception handling for context access from `except RuntimeError` to `except ContextDoesNotExistError` where applicable.
affects: >=0.3.2
breakingVersion 0.3.0 introduced a 'small refactor of the base plugin' which involved moving directories and removing a redundant method. This was noted as 'potentially breaking changes' for users upgrading from very early versions who might have custom plugins or direct imports to internal plugin modules.fixIf migrating from versions older than 0.3.0 and using custom plugins or internal plugin imports, review the changelog and documentation for `v0.3.0` for necessary adjustments.
affects: >=0.3.0
Errors
Common errors & fixes
RuntimeError: No context data available. Make sure you are accessing context within an active request and that ContextMiddleware is installed.
This error occurs when an attempt is made to access `starlette_context.context` (e.g., `context.get()` or `context.set()`) outside of an active HTTP request or when the `ContextMiddleware` has not been properly added to the Starlette/FastAPI application.
fixEnsure `ContextMiddleware` is added to your application using `app.add_middleware(ContextMiddleware)` and that all context access happens within a request that is processed by this middleware.
KeyError: 'my_key_name'
This error occurs when trying to retrieve a value from the request context using `context.get('my_key_name')` without providing a default value, and 'my_key_name' has not been previously set in the context during the current request.
fixEither ensure the key is set using `context.set('my_key_name', some_value)` before retrieval, or provide a default value to avoid the error: `context.get('my_key_name', default=None)`. ModuleNotFoundError: No module named 'starlette.context'
This import error happens when developers incorrectly try to import `context` or `ContextMiddleware` from the `starlette` package, confusing it with the `starlette-context` library.
fixCorrect the import statement to use the `starlette_context` library directly: `from starlette_context import context, ContextMiddleware`.
Upgrade
Version history
0.5.1latest on PyPI · released Feb 28, 2026
Audit
Dependencies
starletterequiredCore framework dependency; requires >=0.27.0 since v0.4.0.
pythonrequiredRequires Python 3.10+ since v0.5.0 (dropped Python 3.9 support).