FastAPI – How can I modify request from inside dependency?
Question:
How can I modify request from inside a dependency? Basically I would like to add some information (test_value
) to the request and later be able to get it from the view function (in my case root()
function).
Below is a simple example:
from fastapi import FastAPI, Depends, Request
app = FastAPI()
def test(request: Request):
request['test_value'] = 'test value'
@app.get("/", dependencies=[Depends(test)])
async def root(request: Request):
print(request.test_value)
return {"test": "test root path."}
Answers:
You can store arbitrary extra state on the request
instance, as shown below (the relevant implementation of Starlette’s State
class can be found here):
from fastapi import FastAPI, Depends, Request
app = FastAPI()
def test(request: Request):
request.state.test_value = 'test value'
@app.get('/', dependencies=[Depends(test)])
def root(request: Request):
return request.state.test_value
If you would like that state to be accessible from other endpoints as well, you might want to store it on the application instance, as described in this answer, as well this and this answer.
How can I modify request from inside a dependency? Basically I would like to add some information (test_value
) to the request and later be able to get it from the view function (in my case root()
function).
Below is a simple example:
from fastapi import FastAPI, Depends, Request
app = FastAPI()
def test(request: Request):
request['test_value'] = 'test value'
@app.get("/", dependencies=[Depends(test)])
async def root(request: Request):
print(request.test_value)
return {"test": "test root path."}
You can store arbitrary extra state on the request
instance, as shown below (the relevant implementation of Starlette’s State
class can be found here):
from fastapi import FastAPI, Depends, Request
app = FastAPI()
def test(request: Request):
request.state.test_value = 'test value'
@app.get('/', dependencies=[Depends(test)])
def root(request: Request):
return request.state.test_value
If you would like that state to be accessible from other endpoints as well, you might want to store it on the application instance, as described in this answer, as well this and this answer.