starlette-request-id

raw JSON →
1.2.1 verified Fri May 01 auth: no python

A Starlette middleware that adds a unique request ID to each incoming request, typically used for logging and tracing. Current version 1.2.1 with a release cadence of occasional updates. Requires Python >=3.7.

pip install starlette-request-id
error ModuleNotFoundError: No module named 'starlette_request_id'
cause Package not installed or installed in wrong environment.
fix
Run 'pip install starlette-request-id' in your active environment.
error ImportError: cannot import name 'RequestIDMiddleware' from 'starlette_request_id'
cause Incorrect import path (likely an older version's submodule).
fix
Use 'from starlette_request_id import RequestIDMiddleware'.
error AttributeError: 'Request' object has no attribute 'id'
cause Trying to access request.id which is deprecated or not available in this version.
fix
Use 'request.headers.get('X-Request-ID')' instead.
gotcha The middleware automatically adds a request ID header, but it does not override an existing one from the client unless explicitly configured. By default, if the incoming request already has a 'X-Request-ID' header, that value is used instead of generating a new one. This can be surprising if you expect a fresh ID for every request.
fix To force generation of a new ID regardless, pass force_new_uuid=True to the middleware constructor: app.add_middleware(RequestIDMiddleware, force_new_uuid=True).
deprecated The attribute 'request.id' used in some older examples is deprecated. Use the 'X-Request-ID' header or the middleware's provided property instead.
fix Access the request ID via request.headers.get('X-Request-ID') or the middleware's helper function.
gotcha The middleware must be added before any other middleware that might read request headers, otherwise the request ID might not be available in those middlewares.
fix Add the RequestIDMiddleware as the first middleware in your application.

A minimal Starlette app that adds request ID middleware and returns the ID in the response.

from starlette.applications import Starlette
from starlette.routing import Route
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette_request_id import RequestIDMiddleware

async def home(request: Request):
    request_id = request.headers.get('X-Request-ID')
    return JSONResponse({'request_id': request_id})

app = Starlette(debug=True, routes=[Route('/', home)])
app.add_middleware(RequestIDMiddleware)

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='0.0.0.0', port=8000)