Request Context Middleware (middleware/request_context.py)

poco-claw · executor/app/core/middleware/request_context.py · python · MIT
integration, infra, lang:python, fw:fastapi

Injects and manages request ID and trace ID headers for FastAPI applications using context vars. Reuse to enable request tracing and observability.

# Source: https://github.com/poco-ai/poco-claw | License: MIT | Copyright 2026 poco-ai
# Provided via justclaw.it.com; keep this notice with the code.
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware

from app.core.observability.request_context import (
    generate_request_id,
    generate_trace_id,
    get_trace_id,
    reset_request_id,
    reset_trace_id,
    set_request_id,
    set_trace_id,
)

REQUEST_ID_HEADER = "X-Request-ID"
TRACE_ID_HEADER = "X-Trace-ID"


class RequestContextMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        request_id = request.headers.get(REQUEST_ID_HEADER) or generate_request_id()
        trace_id = (
            request.headers.get(TRACE_ID_HEADER)
            or get_trace_id

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key