Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request context in FastAPI?

Tags:

python

fastapi

In Flask, the request is available to any function that's down the call-path, so it doesn't have to be passed explicitly.

Is there anything similar in FastAPI?

Basically, I want to allow, within the same app, a request to be "real" or "dummy", where the dummy will not actually carry out some actions, just emit them (yes, I know that checking it down the stack is not nice, but I don't have control over all the code).

let's say I have

@app.post("/someurl")
def my_response():
  func1()

def func1():
  func2()

def func2():
  # access some part of the request

I.e. where I don't need to pass the request as a param all the way down to func2.

In Flask, I'd just access the request directly, but I don't know how to do it in FastAPI. For example, in Flask I could do

def func2():
 x = request.my_variable
 # do somethinh with x

Request here is local to the specific URL call, so if there are two concurrent execution of the func2 (with whatever URL), they will get the correct request.

like image 235
vlade Avatar asked Mar 01 '26 11:03

vlade


1 Answers

FastAPI uses Starlette for this.

(Code from docs)

from fastapi import FastAPI, Request


app = FastAPI()


@app.get("/items/{item_id}")

def read_root(item_id: str, request: Request):

    client_host = request.client.host

    return {"client_host": client_host, "item_id": item_id}

Reference:

Using Request Directly

Edit:

I do not think this is something FastAPI provides out of the box. Starlette also doesn't seem to, but there is this project which adds context middleware to Starlette which should be easy to integrate into a FastAPI app.

Starlette Context

like image 131
im_baby Avatar answered Mar 03 '26 02:03

im_baby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!