FastAPI Dependency Global Fix
In this tutorial, you'll learn about FastAPI Dependency Global Fix. We cover key concepts, practical examples, and best practices.
The Problem
Adding the same dependency (auth, logging, DB session) to every route handler is repetitive and error-prone. FastAPI supports global dependencies applied to all routes.
Quick Fix
Wrong — repeating dependency on every route
@app.get("/items")
async def items(db=Depends(get_db), user=Depends(get_current_user)):
...
@app.post("/items")
async def create_item(item: Item, db=Depends(get_db), user=Depends(get_current_user)):
...
@app.get("/users")
async def users(db=Depends(get_db), user=Depends(get_current_user)):
...
Output: Three routes, each repeating the same two dependencies. Adding a new dependency requires editing every route.
Correct — global dependencies on the app
from fastapi import FastAPI, Depends, HTTPException
async def verify_token(request: Request):
token = request.headers.get("Authorization")
if not token:
raise HTTPException(status_code=401, detail="Missing token")
return token
app = FastAPI(dependencies=[Depends(verify_token)])
Output: Every route automatically runs verify_token before the handler. No need to add Depends to each route.
Router-level global dependencies
from fastapi import APIRouter, Depends
admin_router = APIRouter(
prefix="/admin",
dependencies=[Depends(verify_admin)],
)
@admin_router.get("/dashboard")
async def dashboard():
return {"message": "Admin dashboard"}
Output: Only routes under /admin require admin verification.
Combining global and per-route deps
app = FastAPI(dependencies=[Depends(log_request)])
@app.get("/public")
async def public():
return {"message": "Public"}
@app.get("/protected")
async def protected(user=Depends(get_current_user)):
return {"user": user}
Output: log_request runs on every route. get_current_user runs only on /protected.
Dependency with yield (lifespan)
from contextlib import asynccontextmanager
async def get_db():
db = Database()
try:
yield db
finally:
await db.close()
app = FastAPI()
@app.get("/items")
async def items(db=Depends(get_db)):
return await db.fetch_all("SELECT * FROM items")
Output: Database connection created per request, closed after response.
Prevention
- Use app-level dependencies for cross-cutting concerns: auth, logging, rate limiting.
- Use router-level dependencies for group-specific logic.
- Use per-route dependencies for handler-specific needs.
Common Mistakes with dependency global
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world FASTAPI code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro