Skip to main content

Access context in Starlette

Project description

Build Status PyPI version PyPI license codecov

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.


I use FastAPI. I needed something that will allow me to log with context data. Right now I can just'Message') and I have log (in ELK) with request id and correlation id. I don't even think about passing this data to logger. It's there automatically.


$ pip install starlette-context


Python 3.7+

For Python 3.6 only:
contextvar came out with python3.7 and is required for this to run. If you need to use Starlette with python3.6, there is a backport of contextvar for py36.


  • starlette

All other dependencies from requirements-dev.txt are only needed to run tests or examples. Test/dev env is dockerized if you want to try them yourself.



from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse

import uvicorn
from starlette_context import context, plugins
from starlette_context.middleware import ContextMiddleware

app = Starlette(debug=True)
app.add_middleware(ContextMiddleware.with_plugins(  # easily extensible
    plugins.RequestIdPlugin,  # request id
    plugins.CorrelationIdPlugin  # correlation id

async def index(request: Request):
    return JSONResponse(context.dict()), host="")

In this example the response containes a json with


Context can be updated and accessed at anytime if it's created in the middleware.


All tickets or PRs are more than welcome.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for starlette-context, version 0.1.6
Filename, size File type Python version Upload date Hashes
Filename, size starlette_context-0.1.6.tar.gz (6.8 kB) File type Source Python version None Upload date Hashes View hashes

Supported by

Elastic Elastic Search Pingdom Pingdom Monitoring Google Google BigQuery Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page