Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.
Project Links
Meta
Author: Tom Wojcik
Requires Python: >=3.9,<4.0
Classifiers
Development Status
- 4 - Beta
Intended Audience
- Developers
- Information Technology
- System Administrators
License
- OSI Approved :: MIT License
Programming Language
- Python :: 3
- Python :: 3.9
- Python :: 3.10
- Python :: 3.11
- Python :: 3.12
Topic
- Internet
starlette-context
Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.
Resources
- Source: https://github.com/tomwojcik/starlette-context
- Documentation: https://starlette-context.readthedocs.io/
- Changelog: https://starlette-context.readthedocs.io/en/latest/changelog.html
Installation
# Python 3.9+
pip install starlette-context
Dependencies
starlette>=0.27.0
Example
import uvicorn
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette_context import context, plugins
from starlette_context.middleware import ContextMiddleware
async def index(request: Request):
# Access and store data in context
context["custom_value"] = "example"
return JSONResponse(context.data)
# Define routes
routes = [
Route("/", endpoint=index)
]
# Configure middleware
middleware = [
Middleware(
ContextMiddleware,
plugins=(
plugins.RequestIdPlugin(),
plugins.CorrelationIdPlugin()
)
)
]
# Create application with routes and middleware
app = Starlette(
routes=routes,
middleware=middleware
)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0")
In this example the response contains a JSON with:
{
"X-Correlation-ID": "5ca2f0b43115461bad07ccae5976a990",
"X-Request-ID": "21f8d52208ec44948d152dc49a713fdd",
"custom_value": "example"
}
Context can be updated and accessed at anytime if it's created in the middleware.
Sponsorship
A huge thank you to Adverity for sponsoring the development of this OSS library.
Contribution
See the contributing guide.
0.4.0
Mar 04, 2025
0.3.6
Feb 16, 2023
0.3.5
Nov 26, 2022
0.3.4
Jun 22, 2022
0.3.3
Jun 28, 2021
0.3.2
Apr 22, 2021
0.3.1
Oct 17, 2020
0.3.0
Oct 10, 2020
0.2.3
Jul 26, 2020
0.2.2
Apr 26, 2020
0.2.1
Apr 18, 2020
0.2.0
Feb 21, 2020
0.1.6
Jan 02, 2020
0.1.5
Jan 01, 2020
0.1.4
Dec 31, 2019
0.1.3
Dec 30, 2019
0.1.1
Dec 28, 2019
0.1
Dec 27, 2019
Wheel compatibility matrix
Files in release
Extras:
None
Dependencies:
starlette
(>=0.27.0)