How to access request_id defined in fastapi middleware in function

4.2k Views Asked by At

Hi i have my middleware written like this

@app.middleware("http")
async def request_middleware(request, call_next):
    end_point = request.url.path
    global request_id
    request_id = get_request_id()
    with logger.contextualize(request_id=request_id, end_point=end_point):
        logger.info("----------Request started----------")
        try:
            response = await call_next(request)

        except Exception as ex:
            logger.error(f"Request failed: {ex}")
            response = JSONResponse()


        finally:
            response.headers["X-Request-Id"] = request_id
            logger.info("----------Request ended----------")
            return response

i want the request_id defined in middleware to be accessible in other function defined , how can we do that?

2

There are 2 best solutions below

0
Ron Serruya On BEST ANSWER

Instead of a global request_id, you can use a context variable, which is not shared between async tasks

from contextvars import ContextVar

req_id: ContextVar[str] = ContextVar('req_id', default='')

# Inside your middleware
req_id.set(get_request_id())

# Inside other functions, even different files, you import that variable
req_id.get()
0
ImPerat0R_ On

Another 2 solutions:

from starlette_context import context
from starlette_context.middleware import RawContextMiddleware


app.add_middleware(RawContextMiddleware)


@app.middleware("http")
async def request_middleware(request, call_next):
    request_id = get_request_id()
    context['request_id'] = request_id


@router.post('foobar')
async def foorbar():
    context['request_id']