What if you could write shared setup code once and have it run everywhere automatically?
Why Global dependencies in FastAPI? - Purpose & Use Cases
Imagine building a web app where many routes need the same setup, like checking user login or connecting to a database. You write the same code again and again inside each route.
Copying the same code everywhere makes your app messy and hard to fix. If you want to change the login check, you must update every route. This wastes time and causes bugs.
Global dependencies let you write shared code once and apply it automatically to many routes. FastAPI runs this code before your route handlers, keeping your app clean and easy to update.
def route1(): check_user() # route logic def route2(): check_user() # route logic
from fastapi import FastAPI, Depends app = FastAPI(dependencies=[Depends(check_user)]) def route1(): # route logic def route2(): # route logic
You can enforce common rules or setup across your whole app effortlessly, making your code DRY and reliable.
In a social media app, you want to verify the user is logged in before any page loads. Global dependencies handle this once, so every page is safe without repeating code.
Manual repetition of shared code is error-prone and hard to maintain.
Global dependencies run shared logic automatically for many routes.
This keeps your app clean, consistent, and easy to update.