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."}
Asked By: Mike Olszak

||

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.

Answered By: Chris
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.