5. Testing, Background Jobs & Deployment

Testing APIs with pytest, TestClient & Isolated Databases

Test FastAPI endpoints automatically without launching a server: use TestClient, override Depends(get_db) with isolated per-test SQLite fixtures, and verify status codes and JSON.

4 min readUpdated 2026-11-30
In This Lesson
  • Run full HTTP route tests cleanly in memory using FastAPI TestClient
  • Swap production databases for isolated per-test databases via app.dependency_overrides
  • Verify happy paths, 422 validation failures, and 401/404 responses automatically

Never test your backend only by clicking around in /docs! Manually clicking 15 endpoints every time you edit a file is slow, error-prone, and misses subtle regressions.

FastAPI ships with TestClient (powered by httpx), which dispatches real HTTP requests straight into your ASGI app in milliseconds—without needing uvicorn listening on a port.

1. Architecture: How TestClient & dependency_overrides Work

When TestClient(app) runs client.post("/courses", json=...), your request passes through the entire production stack—middleware, routing, Pydantic validation, auth guards, and response schemas—except app.dependency_overrides intercepts Depends(...) calls:

Isolating Tests with app.dependency_overrides

Production Runtime

Depends(get_db)app.db (Real Data)

Pytest + TestClient

dependency_overridestmp_path/test.db

TestClient swaps production get_db() for a fresh per-test temporary SQLite database, then clears overrides after each test.

This means you test real SQL, real HTTP status codes, and real JSON serialization in one fast, deterministic integration test.

2. Isolating the Database with app.dependency_overrides

The golden rule of API testing: tests must never touch your real app.db, and every test function must start with a clean, empty database.

Because our routes receive their connection via Depends(get_db), we swap get_db inside a pytest fixture using tmp_path (a unique temporary directory pytest creates and cleans up per test) and app.dependency_overrides:

python
# test_api.py
import sqlite3
import pytest
from fastapi.testclient import TestClient
from main import app, get_db, init_schema

@pytest.fixture
def client(tmp_path):
    test_db_path = str(tmp_path / "test.db")
    init_schema(test_db_path)

    def override_get_db():
        conn = sqlite3.connect(test_db_path, check_same_thread=False)
        conn.row_factory = sqlite3.Row
        conn.execute("PRAGMA foreign_keys = ON")
        try:
            yield conn
        finally:
            conn.close()

    app.dependency_overrides[get_db] = override_get_db

    with TestClient(app) as c:
        yield c

    app.dependency_overrides.clear()

Why tmp_path / "test.db" instead of ":memory:"? In SQLite, calling sqlite3.connect(":memory:") twice creates two separate empty databases—and TestClient may run def routes in a worker thread! Using a per-test tmp_path file gives every request in that test the same isolated database while still running in milliseconds.

Always Clear dependency_overrides & Mock External APIs
  1. Always call app.dependency_overrides.clear() after yield c—if a test crashes or finishes without clearing, overrides leak into subsequent test files!
  2. Never hit real Stripe, OpenAI, or GitHub APIs during pytest. Override your external service dependency or pass httpx.MockTransport so tests stay fast, offline, and deterministic.

3. What Every Endpoint Test Suite Should Cover

Always test four buckets for every critical endpoint:

  1. Happy paths (201 Created returns new resource ID; GET reads it back accurately).
  2. Validation errors (422 when required fields are blank, wrong type, or negative).
  3. Auth & ownership (401 without Bearer token; 403 or 404 when user B touches user A's record).
  4. Missing/conflict edge cases (404 for nonexistent ID; 409 on duplicate unique email/slug).
python
def test_create_and_fetch_course(client):
    res = client.post("/courses", json={"slug": "py-api", "title": "Python APIs", "hours": 16})
    assert res.status_code == 201
    created_id = res.json()["id"]

    fetch = client.get(f"/courses/{created_id}")
    assert fetch.status_code == 200
    assert fetch.json()["slug"] == "py-api"

def test_invalid_hours_returns_422(client):
    res = client.post("/courses", json={"slug": "py-api", "title": "Python APIs", "hours": -3})
    assert res.status_code == 422

def test_missing_course_returns_404(client):
    assert client.get("/courses/9999").status_code == 404
Use with TestClient(app) as c: to Run Lifespan Events

Wrapping TestClient(app) in a with block triggers FastAPI @app.on_event("startup") / lifespan setup and teardown cleanly—skipping with skips startup hooks!

Try It Yourself in the Playground

Practice writing isolated, per-test SQLite fixtures and asserting 201, 404, and 422 flows directly in Python:

Python 3Try It Live: Isolated DB Test Runner
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Why is calling app.dependency_overrides.clear() in fixture teardown important when testing a FastAPI app?

Quick Checkpoints

Check Your Understanding

How do you swap out FastAPI's production database dependency (get_db) for an isolated test database during pytest?

Check Your Understanding

Why should every API test fixture create a fresh database or roll back changes per test?