Technical
FastAPI Dependency Injection: Clean Handlers, Testable Code
Dependency injection in FastAPI is one of those features that looks cute in the docs and transformative in real code. Every route handler in my backend got shorter once I committed to the pattern.
The Shape
A dependency is a function that returns a value. Routes declare what they need. FastAPI figures out the rest, including caching within a request.
from fastapi import Depends
def get_db():
db = DynamoClient()
try:
yield db
finally:
db.close()
def current_user(token: str = Depends(oauth2_scheme), db = Depends(get_db)):
return db.get_user_by_token(token)
@app.get('/posts')
def list_posts(user = Depends(current_user), db = Depends(get_db)):
return db.list_posts_for(user.id)Notice get_db is declared as a dependency of both current_user and list_posts. FastAPI runs it once per request and gives both consumers the same instance. No globals, no thread-locals, no manual wiring.
Testing Wins
Override any dependency in a test with one line: app.dependency_overrides[get_db] = fake_db. Now every route that needed the database uses the fake. Zero mocking libraries. Zero monkey-patching.
What To Make A Dependency
Anything that has a lifecycle (connections, transactions), anything that does auth or authorization, and anything that is shared across handlers. Things that are purely data transforms stay as regular functions.
The Composition Win
Dependencies compose. current_user depends on get_db. A require_admin dependency depends on current_user. Routes depend on require_admin. Each layer adds one concern. The call graph is explicit and testable.
See the FastAPI dependencies docs for the full taxonomy. Once you internalize this pattern, your handlers become three-to-five lines and the logic lives where it belongs.
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