13

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.

2
  • It might be helpful to provide the flask code for clarity. Commented Mar 22, 2021 at 14:13
  • You could use class based handlers, like in django.(of course we have implement them by ourselves) Commented Mar 22, 2021 at 15:10

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I know I can access the request directly, but in Flask I can access it anywhere in the call stack w/o passing it explicitly as a parameter i.e. flask.palletsprojects.com/en/1.1.x/reqcontext I've updated the question to make this explicit.
2

I provided an answer that may be of help, here. It leverages ContextVars and Starlette middleware (used in FastAPI) to make request object information globally available. It doesn't make the entire request object globally available -- but if you have some specific data you need from the request object, this solution may help!

1 Comment

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.