Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
A Help Desk route that emails the on-call agent sends that email from every test, because it builds its own mailer. Move the repository and the notifier into providers, inject them with Depends, swap in a FakeNotifier with dependency_overrides, and see per-request caching and yield cleanup.
What you will learn
- Spot a hardwired route that builds its own tools
- Write provider functions and ask for them with Annotated and Depends
- Swap a provider for a fake in a test with app.dependency_overrides, and clear it
- Know that FastAPI calls each provider once per request, and clean up with yield
Before you start
- FastAPI routes and TestClient
- SOLID in Python With Protocol and ABCs
The idea in one line: the route asks for its tools, and a test can hand it fakes instead. Three words carry it: Depends, providers and dependency overrides.
A test that sends email
A customer of our Help Desk opens a ticket called "VPN down". It goes into the POST /tickets route, the repository stores it as row 1, and the route emails the on-call agent so a human knows. Now we write a test for that route. The test calls the same code, and the email goes out again. A test just emailed a real person.
Here's the first version, hardwired.py. (The project pins fastapi==0.162.2 and httpx==0.28.1; EmailNotifier is a stand-in that prints instead of sending.)
from fastapi import FastAPI
from fastapi.testclient import TestClient
from services import EmailNotifier, TicketRepo
app = FastAPI()
repo = TicketRepo()
@app.post("/tickets")
def open_ticket(title: str):
mailer = EmailNotifier()
tid = repo.add(title)
mailer.send(f"#{tid} {title}")
return {"id": tid}
client = TestClient(app)
r = client.post("/tickets", params={"title": "VPN down"})
print(r.json())
EMAIL to agent@helpdesk: #1 VPN down
{'id': 1}
Why that hurts
The route is a box with two parts welded inside, the repository and the mailer. That has three costs:
- Every test sends an email.
- Every test shares the same global repository, so one test's tickets leak into the next.
- To swap anything, you have to edit the route itself.
The root is the line mailer = EmailNotifier(). The route creates the mailer, so the route decides which mailer you get.
Ask, don't build
Picture a chef's station with empty slots for a knife and a pan. The chef doesn't forge a knife. A runner brings the tools and drops them in the slots. The slots are our parameters, repo and notify. The runner is FastAPI. In a test, a different runner brings a plastic knife, a fake notifier, into the same slot, and the chef doesn't change at all. That's dependency injection: ask for it, don't build it.
Providers
First, the tools themselves, in services.py:
from typing import Protocol
class Notifier(Protocol):
def send(self, text: str) -> None: ...
class EmailNotifier:
def send(self, text: str) -> None:
print(f"EMAIL to agent@helpdesk: {text}")
class TicketRepo:
def __init__(self) -> None:
self.rows: dict[int, str] = {}
def add(self, title: str) -> int:
tid = len(self.rows) + 1
self.rows[tid] = title
return tid
def get(self, tid: int) -> str | None:
return self.rows.get(tid)
Notifier is a Protocol, the same idea as in SOLID in Python: anything with a send method fits. Then deps.py:
from services import EmailNotifier, Notifier, TicketRepo
_repo = TicketRepo()
def get_repo() -> TicketRepo:
return _repo
def get_notifier() -> Notifier:
return EmailNotifier()
These are providers: plain functions that return a tool. get_repo hands back the same TicketRepo every time. get_notifier returns a new EmailNotifier, typed as the Notifier Protocol.
Depends in the signature
app.py:
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from deps import get_notifier, get_repo
from services import Notifier, TicketRepo
app = FastAPI()
Repo = Annotated[TicketRepo, Depends(get_repo)]
Notify = Annotated[Notifier, Depends(get_notifier)]
@app.post("/tickets")
def open_ticket(title: str, repo: Repo, notify: Notify):
tid = repo.add(title)
notify.send(f"#{tid} {title}")
return {"id": tid}
@app.get("/tickets/{tid}")
def read_ticket(tid: int, repo: Repo):
title = repo.get(tid)
if title is None:
raise HTTPException(404)
return {"id": tid, "title": title}
Read Annotated[TicketRepo, Depends(get_repo)] in two halves: the type is TicketRepo, and Depends says who makes it. title is a normal query parameter, but repo and notify are injected: FastAPI sees Depends, calls the provider and passes the result in. read_ticket reuses the same Repo alias.
from fastapi.testclient import TestClient
from app import app
client = TestClient(app)
r = client.post("/tickets", params={"title": "VPN down"})
print(r.json())
print(client.get("/tickets/1").json())
print(client.get("/tickets/9").status_code)
EMAIL to agent@helpdesk: #1 VPN down
{'id': 1}
{'id': 1, 'title': 'VPN down'}
404
Same behaviour as the hardwired version, and the real notifier still runs here. The difference is that the wiring now lives outside the route.
Swap it in a test: dependency_overrides
test_override.py:
from fastapi.testclient import TestClient
from app import app
from deps import get_notifier, get_repo
from services import TicketRepo
class FakeNotifier:
def __init__(self):
self.sent = []
def send(self, text):
self.sent.append(text)
fake, test_repo = FakeNotifier(), TicketRepo()
app.dependency_overrides[get_notifier] = lambda: fake
app.dependency_overrides[get_repo] = lambda: test_repo
client = TestClient(app)
r = client.post("/tickets", params={"title": "Printer jam"})
print(r.json())
print("fake.sent:", fake.sent)
print("rows:", test_repo.rows)
app.dependency_overrides.clear()
print("overrides:", app.dependency_overrides)
{'id': 1}
fake.sent: ['#1 Printer jam']
rows: {1: 'Printer jam'}
overrides: {}
The key line is app.dependency_overrides[get_notifier] = lambda: fake. The key is the provider function itself. The test also gets a fresh repository, so it starts with no tickets. No email line is printed: the text lands in fake.sent. At the end, clear() removes the overrides.
One call per request
Dependencies can depend on other dependencies. cache.py:
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
calls = 0
def get_settings():
global calls
calls += 1
return {"hours": 4}
def get_sla(s=Depends(get_settings)):
return s["hours"]
@app.get("/sla")
def sla(h=Depends(get_sla), s=Depends(get_settings)):
return {"hours": h, "calls": calls}
client = TestClient(app)
print(client.get("/sla").json())
print(client.get("/sla").json())
{'hours': 4, 'calls': 1}
{'hours': 4, 'calls': 2}
The route depends on get_settings twice, once directly and once through get_sla. You might expect two calls on the first request. It's one: inside a request, FastAPI calls each provider once and shares the result. The second request gets a fresh call, so the counter moves to 2.
Set up, then clean up: yield
Some tools need cleanup, like the database session from the repository lesson. yield_dep.py:
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
class Session:
def close(self):
print("close session")
def get_session():
print("open session")
s = Session()
try:
yield s
finally:
s.close()
@app.get("/ok")
def ok(s=Depends(get_session)):
print("handler runs")
return {"ok": True}
print(TestClient(app).get("/ok").json())
open session
handler runs
close session
{'ok': True}
Code before yield sets up; FastAPI hands the session to the route; after the route is done, FastAPI comes back past the yield and the finally block closes the session. Even if the route raises an error, finally still runs.
The trade-off
For one FastAPI app, Depends is usually enough: providers are plain functions and tests use overrides. A separate DI container starts to pay off when several entry points share the same wiring, say an API, a background worker and a command-line tool.
The rule that matters most: use Depends at the edge, in the routes. Below the route, your service should take the notifier as a plain constructor argument, so you can test it without FastAPI at all. Two costs to keep in mind: overrides sit on the app object, so they're global and you have to clear them; and the wiring is spread across many signatures, so it takes a moment to see the whole graph. For Depends alongside schemas and the lifespan in an AI service, see FastAPI for AI services.
Say it in an interview
"How do you test a FastAPI route that sends email?" Three steps: I put the notifier behind a provider function; the route asks for it with Depends in the signature; in the test I set dependency_overrides to a fake and clear it afterwards. Then the design-sense line: below the route, the service takes the notifier as a constructor argument, so the business logic is testable without the framework. Name the seam, the swap and the cleanup.
Recap
- A hardwired route builds its own tools, so tests can't swap them.
- A provider is a plain function that returns the tool;
Dependsputs the request for it in the signature. dependency_overrideslets a test swap the provider for a fake. Clear it afterwards.- Each provider runs once per request, shared inside it.
- A provider with
yieldsets up and cleans up around each request.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
The smallest FastAPI app: two routes in main.py, started with uvicorn. Follow one request from the browser to the route table and back as JSON, see a 404, and try the routes on the free Swagger page at /docs.
RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
An API is the waiter between your program and a server. REST gives each resource an address and uses the HTTP method for the action. Send GET, POST, PUT, PATCH and DELETE to a tiny local server with urllib, see why requests are stateless, and read 200, 201, 204, 400 and 404.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.
