Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 50 ยท Testing and production

Testing FastAPI apps

Learn to test FastAPI apps: call endpoints in-process, assert on status and JSON, override dependencies, isolate databases per test and cover auth and errors.

An API that you only check by clicking around in the docs page is an API that will break the day you change a shared dependency. Tests turn "I think it still works" into a command that answers in a second. FastAPI is unusually easy to test, because an application is just an ASGI callable: you can send requests to it in the same process, with no server, no port and no network.

In this lesson you will write real assertions against an app, replace dependencies with dependency_overrides, give every test a fresh database, and cover the two things people forget: authentication and error responses. The live examples use a tiny test runner written in plain Python so they run in your browser; the second half shows how the same tests look under pytest in a real project.

What a good API test looks like

Every API test has the same three parts: arrange (build the app state), act (send one request) and assert (check the status code, the JSON body and sometimes the headers). Because the call is in-process, a test costs milliseconds, so you can afford hundreds of them.

Anatomy of an API test

Arrange Build the app and its data.
Act Send one request in-process.
Assert Check status, body and headers.
1 / 2

Two rules keep tests reliable. First, a test must not depend on another test: each one builds what it needs. Second, a test must not touch real services such as your production database or a payment provider: swap them out.

Assertions against an in-process client

The site's runner calls apps with httpx.ASGITransport, exactly like earlier lessons. Here the calling code is wrapped in a helper, and a few test functions use plain assert. A small loop plays the role of the test runner: it calls each test, catches AssertionError and prints the result.

Python Plain asserts and a tiny test runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the last test: it fails on purpose so you can see what a failure message looks like. Notice also that the first two tests share state through the module-level ITEMS dictionary. test_read_returns_what_was_created only passes because the test before it ran first. That is the exact trap the rules above warn about, and the next two sections remove it.

Replacing dependencies

When an endpoint gets something through Depends, you can substitute it in tests. FastAPI keeps a dictionary called app.dependency_overrides: the key is the original dependency function and the value is the replacement. Whenever the original would be called, FastAPI calls the replacement instead, with the same rules for its parameters. Dependencies themselves are introduced in Dependencies.

This is how you remove the outside world from a test:

  • the clock (a dependency that returns "now") becomes a fixed time;
  • the current user becomes a known user, with no token to craft;
  • the email sender becomes a list that records what would have been sent.

Always clear overrides when the test ends, otherwise they leak into the next test. In pytest you would do that in a fixture; in the example below a try/finally plays that part.

A fresh database for every test

The cleanest isolation is to build a new app state for each test. With a real database that usually means an in-memory SQLite database, or a transaction that is rolled back at the end. Here a dependency yields a sqlite3 connection, a helper creates a brand-new in-memory database with the schema, and the test overrides the dependency to use it.

Python dependency_overrides with a fresh database per test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Both the database and the clock were replaced, so the note carries the fixed date 2024-02-29, and test_still_starts_empty_again proves that nothing leaked from the previous test. The overrides are small async def functions because the in-browser runner has no threads (a plain def dependency would need one); on a normal server lambda: db works too. An override may take parameters and have its own dependencies.

Testing authentication and errors

Protected endpoints deserve at least three tests: no credentials (401), wrong credentials (401), and valid credentials (200). If the endpoint also checks who you are, add a test for the user who is signed in but not allowed (403, see Roles, scopes and permissions).

You have two choices for the signed-in case. Either create a real token the way a client would, which tests the whole chain, or override the "current user" dependency, which tests only the endpoint. A good suite does both: one or two end-to-end tests of login, and many quick tests that use an override.

Python Testing 401, 403 and 200 with an overridden user

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same idea applies to every error path. Validation errors (422), missing records (404) and conflicts (409) are part of your API's contract, and clients depend on their shape. Assert on the status code and on the detail, not only on "it failed".

The same tests in a real project

On your own machine you do not write a runner. You install pytest and httpx, and the tests above become ordinary functions. For synchronous tests, FastAPI re-exports Starlette's TestClient, which wraps the app and handles the event loop for you. Read-only, because the site cannot run pytest:

Python
# test_items.py
from fastapi.testclient import TestClient
from app.main import app, get_db
from tests.helpers import fresh_database

def test_create_and_read(client):
    created = client.post("/items", json={"name": "Lamp", "price": 19.5})
    assert created.status_code == 201
    assert client.get("/items/1").json()["name"] == "Lamp"

# conftest.py
import pytest

@pytest.fixture
def client():
    db = fresh_database()
    app.dependency_overrides[get_db] = lambda: db
    with TestClient(app) as test_client:     # "with" also runs the lifespan
        yield test_client
    app.dependency_overrides.clear()
    db.close()

When the test itself must await something (for example, to inspect a database with an async driver), use an async test with the pytest-asyncio or anyio plugin and httpx.AsyncClient(transport=httpx.ASGITransport(app=app)), which is exactly what the live examples do. Run everything with pytest -q; a failing test prints the assertion and the values involved.

Use the with TestClient(app) form when your app has a lifespan, because only then do startup and shutdown run. Lifespan events and app state explains why.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is app.dependency_overrides used for in tests?

    It maps an original dependency to a replacement. FastAPI calls the replacement wherever the original would have been called.
  2. 2. Why should you call app.dependency_overrides.clear() after a test?

    The dictionary lives on the app object, so an override set in one test is still active in the next unless you remove it.
  3. 3. A signed-in user without admin rights calls an admin-only endpoint. Which status code should the test expect?

    401 means the caller is not authenticated. 403 means the caller is known but not allowed.
  4. 4. Why does each test in the lesson get a new in-memory database?

    Isolated state makes tests repeatable and lets you run them in any order, or in parallel.

Summary

  • Apps are ASGI callables, so tests send requests in-process: no server, no port, milliseconds per test.
  • Structure each test as arrange, act, assert, and check status code, JSON body and error shape.
  • Use app.dependency_overrides to replace databases, clocks, users and email senders, and clear it afterward.
  • Build a fresh database (in-memory SQLite or a rolled-back transaction) for every test.
  • Test 401, 403, 404, 409 and 422 responses, not just the happy path.
  • In a real project use pytest with TestClient (as a context manager when you have a lifespan) or an async test with httpx.AsyncClient.

Next, make the app fast in Performance and caching.