Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

FastAPI – How can I modify request from inside dependency?

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."}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading