💭 FastAPI - dependency inside Middleware? - Stack Overflow ========================================================== !https://stackoverflow.com/questions/72243379/fastapi-dependency-inside-middleware#answer-72480781 Date: December 17, 2023 FastAPI - How to use dependencies inside a Middleware? I am building a browser game where every user has 4 types of resources and each user produces more resources based on the level of their farms. What I am trying to do, is whenever a given user is l... Stack Overflow · stackoverflow.com [1] After struggling to get dependencies inside of middleware I learned that you can make global dependencies at the app level. I used this to set the user on every single route of the application without needing Depend on getting the user on each route. ``` python from fastapi import Depends, FastAPI, Request def get_db_session(): print("Calling 'get_db_session(...)'") return "Some Value" def get_current_user(session=Depends(get_db_session)): print("Calling 'get_current_user(...)'") return session def recalculate_resources(request: Request, current_user=Depends(get_current_user)): print("calling 'recalculate_resources(...)'") request.state.foo = current_user app = FastAPI(dependencies=[Depends(recalculate_resources)]) @app.get("/") async def root(request: Request): return {"foo_from_dependency": request.state.foo} ``` !!! note This post is a thought [2]. It's a short note that I make about someone else's content online #thoughts [3] References: [1]: https://stackoverflow.com/questions/72243379/fastapi-dependency-inside-middleware#answer-72480781 [2]: /thoughts/ [3]: /tags/thoughts/