pythonfastapiloguru

How to access request_id defined in fastapi middleware in function


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?


Solution

  • 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()