---
title: "💭 FastAPI - dependency inside Middleware? - Stack Overflow"
description: "!https://stackoverflow.com/questions/72243379/fastapi-dependency-inside-middleware#answer-72480781"
date: 2023-12-17
published: true
tags:
  - fastapi
  - webdev
  - thought
template: link
---


<div class="embed-card embed-card-external">
  <a href="https://stackoverflow.com/questions/72243379/fastapi-dependency-inside-middleware#answer-72480781" class="embed-card-link" target="_blank" rel="noopener noreferrer">
    <div class="embed-card-content">
      <div class="embed-card-title">External Link</div>
      <div class="embed-card-meta">stackoverflow.com</div>
    </div>
  </a>
</div>


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 <a href="/thoughts/" class="wikilink" data-title="Thoughts" data-description="These are generally my thoughts on a web page or some sort of url, except a rare few don&#39;t have a link. These are dual published off of my..." data-date="2024-04-01">thought</a>. It's a short note that I make
    about someone else's content online <a href="/tags/thoughts/" class="hashtag-tag" data-tag="thoughts" data-count=2 data-reading-time=3 data-reading-time-text="3 minutes">#thoughts</a>
