What if you could write shared setup code once and have it run everywhere automatically?
Why Global dependencies in FastAPI? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
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.
Practice
Solution
Step 1: Understand what global dependencies do
Global dependencies are functions or classes that run for every request to apply shared logic.Step 2: Identify their main use
They help with tasks like authentication, database connections, or validations that apply to all routes.Final Answer:
To run shared logic automatically for every request -> Option DQuick Check:
Global dependencies = shared logic for all requests [OK]
- Thinking global dependencies are for styling
- Confusing global with route-specific dependencies
- Assuming they create database models
Solution
Step 1: Recall FastAPI global dependency syntax
Global dependencies are passed as a list to the 'dependencies' parameter when creating the FastAPI app.Step 2: Match the correct syntax
app = FastAPI(dependencies=[Depends(common_dependency)]) uses 'dependencies=[Depends(common_dependency)]', which is the correct pattern.Final Answer:
app = FastAPI(dependencies=[Depends(common_dependency)]) -> Option AQuick Check:
Global dependencies use dependencies=[Depends(...)] [OK]
- Using wrong parameter names like global_dep or use_global
- Calling the dependency function instead of passing Depends()
- Passing a single dependency without a list
/items/42?
from fastapi import FastAPI, Depends
app = FastAPI()
def common_dep():
print("Global dependency called")
@app.get("/items/{item_id}")
def read_item(item_id: int, dep=Depends(common_dep)):
return {"item_id": item_id}Solution
Step 1: Check how common_dep is used
common_dep is used as a route dependency only on the read_item function, not as a global dependency.Step 2: Understand when common_dep runs
It runs only when the /items/{item_id} route is called, printing the message once per request to that route.Final Answer:
Global dependency called printed once per request -> Option BQuick Check:
Route dependency prints only when route is called, not global [OK]
- Assuming common_dep is global when it's route-specific
- Expecting multiple prints per request
- Confusing global and route dependencies
from fastapi import FastAPI, Depends
def common_dep():
print("Running global dependency")
app = FastAPI(dependencies=Depends(common_dep))Solution
Step 1: Check the dependencies parameter type
The 'dependencies' argument expects a list of Depends instances, not a single Depends object.Step 2: Identify the fix
Wrap Depends(common_dep) inside a list: dependencies=[Depends(common_dep)]Final Answer:
dependencies parameter expects a list, not a single Depends -> Option CQuick Check:
dependencies=[Depends(...)] requires a list [OK]
- Passing Depends(...) directly without list
- Defining dependency after app creation
- Confusing Depends usage with function call
Solution
Step 1: Understand global dependencies list
FastAPI allows multiple global dependencies by passing a list to the dependencies parameter.Step 2: Combine auth and logging as separate dependencies
Adding both as separate Depends in the list keeps concerns separated and runs both for every request.Step 3: Evaluate other options
Create one dependency function that calls both auth check and logging, then add it globally mixes concerns in one function, B is inconsistent, D mixes middleware and dependencies unnecessarily.Final Answer:
Add both auth check and logging as separate global dependencies in the dependencies list -> Option AQuick Check:
Multiple global dependencies = dependencies=[Depends(...), Depends(...)] [OK]
- Combining unrelated logic in one dependency
- Using middleware instead of dependencies for all tasks
- Adding some logic only per route, not globally
