Technical
FastAPI Dependency Injection for Real Projects
FastAPI's dependency injection is often shown with trivial examples: a get_db function, an auth check. Real projects need more. After shipping several APIs this year, these are the DI patterns I reach for daily.
Scope Matters More Than You Think
FastAPI dependencies default to request scope: they run once per request. That is usually what you want. But for expensive setup like boto3 clients or database engines, you want application scope instead. The trick is to create those at module level and yield them from a dependency.
I lost two hours once to a dependency that created a new boto3 client on every request. It worked but was slow. Moving the client to module scope and making the dependency a thin wrapper cut p50 latency by 40ms.
The Auth Pattern That Composes
Most tutorials show a get_current_user dependency. That is a good start, but real apps need fine-grained authorization. I layer dependencies: a base one that extracts the user, and permission-specific ones that build on it.
from fastapi import Depends, HTTPException
def get_current_user(token: str = Depends(oauth2_scheme)):
return verify_jwt(token)
def require_admin(user = Depends(get_current_user)):
if not user.is_admin:
raise HTTPException(403, 'Admin only')
return user
def require_owner(resource_id: str, user = Depends(get_current_user)):
if not user_owns_resource(user, resource_id):
raise HTTPException(403, 'Not your resource')
return user
@app.delete('/posts/{post_id}')
def delete_post(post_id: str, _ = Depends(require_owner)):
...This pattern scales. New permissions become new dependencies. They compose. They are testable in isolation.
Testing Dependencies Without a Real Service
app.dependency_overrides is the feature every FastAPI guide underuses. In tests I swap real dependencies for fakes with one line. No mocking library, no patching, just replace the function.
The official FastAPI dependency docs cover the mechanics. The patterns above are what survive contact with production traffic and client requirements that change weekly.
RELATED READING
The Consulting Shift I Am Making In Year Two
After a year of writing and building, my consulting practice is changing shape. Shorter engagements. Sharper outcomes.
ReadThe Frontend Shift: Shipping Less JavaScript In Year Two
A year ago I reached for Next.js for everything. This year I often reach for nothing.
ReadThe Serverless Lesson I Would Write On A Sticky Note
After a year of shipping serverless projects, one rule explains most of the wins and all of the losses.
Read