Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Backend vs Frontend: What Runs Where, and Why the Server Is the One You Trust
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • File Upload and Download in FastAPI: multipart, UploadFile and FileResponse
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
  • A Layered FastAPI Project: Controllers, Services, Schemas and One Folder per Concern
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • An Auth Starter Kit with Keycloak: Build Sign In Once, Put the Backend Between React and the Identity Provider
  • Protecting a Python API with Keycloak: Check the JWT Signature, Issuer and Expiry in FastAPI, Django and Flask
  • How an Identity Provider Login Works: The OpenID Connect Code Flow vs a Backend Password Grant, with Keycloak
  • AWS Cognito vs Keycloak: User Pools, App Clients and When a Managed Identity Provider Wins
  • Migrating FastAPI from Keycloak to AWS Cognito: The Four Values, the JWKS Address and Every Check on an Access Token
  • Testing a Cognito Login End to End: Allow the Password Flow, Confirm the Email Code, and Reset a Forgotten Password
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  • Testing a FastAPI Blog with pytest: a Test Database through dependency_overrides, Login Fixtures and Reading a Failure
  • Smoke-Testing a Dockerized LLM App by Hand: Stage the Weights, Check Every Layer, Make Errors Say Why
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Fundamentals

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.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Fundamentals

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.

Same slots, different runner open_ticket repo: Repo notify: Notify get_repo() -> TicketRepo get_notifier() -> Email override: test_repo override: FakeNotifier in the app in a test the route never changes
Providers fill the slots in the app; dependency_overrides fills them in a test.

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; Depends puts the request for it in the signature.
  • dependency_overrides lets a test swap the provider for a fake. Clear it afterwards.
  • Each provider runs once per request, shared inside it.
  • A provider with yield sets up and cleans up around each request.

Keep going in FastAPI · 20 of 39

Previous
A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
Next post
A Layered FastAPI Project: Controllers, Services, Schemas and One Folder per Concern
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • A test that sends email
  • Why that hurts
  • Ask, don't build
  • Providers
  • Depends in the signature
  • Swap it in a test: dependency_overrides
  • One call per request
  • Set up, then clean up: yield
  • The trade-off
  • Say it in an interview
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.