Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

DJ
Django & FastAPI
0/12 completed
Beginner
How Python web frameworks workYour first FastAPI appRequest bodies and Pydantic models
Intermediate
FastAPI with a databaseDependencies, routers and testingDjango: projects, apps and the ORMDjango views, URLs and templatesForms, the admin and class-based views
Advanced
APIs with Django REST frameworkAuthentication in Django and FastAPIBackground tasks and async
Pro
Deploying Python web apps
Tracks / Django & FastAPI / Intermediate

Dependencies, routers and testing

As an API grows, three FastAPI features keep it manageable: dependency injection to share logic (database sessions, the current user, pagination) across routes, routers to split the app into modules, and a testing approach that lets you replace any dependency in tests.

Dependencies

A dependency is a function whose result FastAPI computes and passes into your route. You declare it with Depends:

Python · editable

The dependency's own parameters (page, size) became query parameters of every route that uses it, with validation, and they appear in the docs.

Dependencies that guard routes

Dependencies can raise errors, which makes them perfect for authentication and permissions. They can also depend on other dependencies:

Python · editable

Header() reads a request header; FastAPI converts the parameter name x_api_key to the header X-API-Key automatically.

Routers: splitting the app

Put each area of the API in its own module with an APIRouter, then include the routers in the main app:

Python · editable

A typical project layout:

app/
├── main.py            creates the app, includes routers, adds middleware
├── config.py          settings (pydantic-settings reads environment variables)
├── db.py              engine and the session dependency
├── models.py          SQLModel / Pydantic models
├── deps.py            shared dependencies (current_user, pagination)
└── routers/
    ├── products.py
    └── users.py
tests/
└── test_products.py

Testing

FastAPI apps are tested by sending requests to the app in-process, exactly as the "try it" sections in these lessons do. With pytest you'd usually use TestClient (a synchronous wrapper around httpx):

python
# tests/test_products.py
from fastapi.testclient import TestClient
from app.main import app

client = TestClient(app)

def test_get_product():
    response = client.get("/products/42")
    assert response.status_code == 200
    assert response.json()["id"] == 42

def test_product_id_must_be_a_number():
    assert client.get("/products/mug").status_code == 422

Run them with pytest. Since browsers can't start threads, the editors here use the async client instead, but the assertions are the same.

Overriding dependencies

The killer feature for testing: app.dependency_overrides replaces any dependency, so tests can use a fake user, a test database or a mock payment service, without touching the route code:

Python · editable

In a real project you'd let pytest find and run these (with the anyio pytest plugin for async tests, or TestClient for sync ones), and override get_session to use a fresh test database for each test.

Practice

  1. Write a get_settings() dependency that returns {"currency": "INR"} and use it in a route; override it in a test to return "EUR".
  2. Move the current_user and require_admin dependencies into a deps.py file and use them from a router.
  3. Write a test proving that /products/7 can't be deleted without an API key.
✎ Check your understanding

1.What does Depends(current_user) do in a route's parameters?

2.Why use APIRouter?

3.What is app.dependency_overrides mostly used for?

← FastAPI with a database