Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set attribute to request object in FastAPI from middleware?

How can I set an arbitrary attribute to the Request object from the middleware function?

from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def set_custom_attr(request: Request, call_next):
    request.custom_attr = "This is my custom attribute"
    response = await call_next(request)
    return response


@app.get("/")
async def root(request: Request):
    return {"custom_attr": request.custom_attr}

This setup is raising an exception,

AttributeError: 'Request' object has no attribute 'custom_attr'

So, how can I get the "This is my custom attribute" value in my router?

like image 412
JPG Avatar asked Jan 23 '26 13:01

JPG


1 Answers

We can't attach/set an attribute to the request object (correct me if I am wrong).

But, we can make use of the Request.state--(Doc) property

from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def set_custom_attr(request: Request, call_next):

    request.state.custom_attr = "This is my custom attribute" # setting the value to `request.state`

    response = await call_next(request)
    return response


@app.get("/")
async def root(request: Request):
    return {"custom_attr": request.state.custom_attr} # accessing the value from `request.state`
like image 160
JPG Avatar answered Jan 26 '26 03:01

JPG