skip to content

App Test Tooling

FastAPI apps are tested in process with TestClient or httpx's AsyncClient, with dependencies swapped through dependency_overrides. Interviewers ask how to test an endpoint without its database.

on this pageshow

explore

questions

11

In FastAPI, how do you test an endpoint with fastapi.testclient.TestClient, sending a JSON body and a request header?

level: juniorimportance: must knowfreq 70%

answer

  1. synchronous calls, no await
  2. httpx-style keyword arguments
  3. json= versus data=
  4. status_code and json() on the response
  5. default host testserver

basics

~10 s

Build TestClient(app) and call it from a plain def test like an httpx client: client.post("/items/", json={...}, headers={"X-Token": "..."}), then assert on response.status_code and response.json(). The app runs in process; no server starts.

solid answer

~40 s

`TestClient` (Starlette's client, re-exported as `fastapi.testclient.TestClient`) is an httpx-style client whose transport calls the ASGI app directly, so tests are ordinary `def` functions with no `await` and no running server. Path and query values go in the URL or `params=`, a JSON body in `json=` (form fields in `data=`, uploads in `files=`), headers in `headers=`, and you assert on `response.status_code`, `response.json()` and `response.headers`. `json=` takes JSON-ready data, not a Pydantic model, so convert with `jsonable_encoder` or `model_dump(mode="json")`. Relative paths go to `http://testserver` by default, redirects are followed, and an unhandled exception in the endpoint is re-raised into the test rather than returned as a 500.

code

python · 49 lines
python
from typing import Annotated

from fastapi import FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from pydantic import BaseModel


class Item(BaseModel):
    id: str
    title: str
    price: float | None = None


app = FastAPI()


@app.post("/items/", status_code=201)
async def create_item(item: Item, x_token: Annotated[str, Header()]) -> Item:
    if x_token != "secret-token":
        raise HTTPException(status_code=400, detail="Invalid X-Token header")
    return item


client = TestClient(app)


def test_create_item():
    response = client.post(
        "/items/",
        headers={"X-Token": "secret-token"},
        json={"id": "foo", "title": "Foo", "price": 9.5},
    )
    assert response.status_code == 201
    assert response.json() == {"id": "foo", "title": "Foo", "price": 9.5}


def test_create_item_bad_token():
    response = client.post(
        "/items/",
        headers={"X-Token": "wrong"},
        json={"id": "foo", "title": "Foo"},
    )
    assert response.status_code == 400
    assert response.json() == {"detail": "Invalid X-Token header"}


def test_create_item_missing_header():
    response = client.post("/items/", json={"id": "foo", "title": "Foo"})
    assert response.status_code == 422

go deeper

for a junior

Recall the shape: TestClient(app), plain def tests, json= for a body, headers= for headers, then assert on status_code and response.json().

for a middle

Explain that the client calls the ASGI app in process through an httpx transport, why json= needs JSON-ready data, and which defaults apply: the testserver host, followed redirects and re-raised exceptions.

for a senior

Show where these tests stop: no server process, a fixed client address and host, and cookies set on the client so the suite stays free of deprecation warnings.

for a principal

Set the team convention: which tests use TestClient, how shared clients and auth headers are built, and that warnings such as the httpx fallback get fixed rather than silenced.

## What `TestClient` is `TestClient` is the test client FastAPI re-exports from Starlette: `from fastapi.testclient import TestClient` gives you exactly `starlette.testclient.TestClient`. It is a subclass of an **httpx-style `Client`** whose transport does not open a socket. Instead, each request is turned into an **ASGI scope** and handed straight to your FastAPI app, which runs on an event loop the client starts for you. The response comes back as an ordinary response object. Two consequences shape every test you write with it: - **Tests are plain `def` functions.** Calls such as `client.get(...)` return when the response is complete, so there is no `await` and no async test runner involved. - **No server is started.** There is no Uvicorn process, no port and no network, so a test runs in milliseconds and needs no setup beyond importing `app`. ## Sending a request `TestClient` accepts the keyword arguments of an httpx request, so you describe the request exactly as you would to an HTTP client library: | Keyword | What it sends | Typical FastAPI parameter it reaches | |---|---|---| | URL path and `params=` | path segments and the query string | path and `Query` parameters | | `json=` | a JSON body with `Content-Type: application/json` | a Pydantic body model | | `data=` | form-encoded fields | `Form` parameters | | `files=` | a multipart upload | `File` / `UploadFile` parameters | | `headers=` | request headers | `Header` parameters, security schemes | `json=` takes **JSON-ready data** (dicts, lists, strings, numbers), not a Pydantic model. Passing a model instance raises `TypeError: Object of type Item is not JSON serializable`. Convert it first with FastAPI's `jsonable_encoder` or with `model_dump(mode="json")`. Mixing up `json=` and `data=` is the other classic slip: form fields sent to an endpoint that expects a JSON body model fail validation with a 422. ## Reading the response The result is an httpx response. The assertions you reach for are: - `response.status_code`, compared with the code the path operation declares (`201` for a `status_code=201` create, `422` for a validation failure); - `response.json()`, compared with a plain dict such as `{"detail": "Invalid X-Token header"}`; - `response.headers`, for things like `location` or a `WWW-Authenticate` challenge. ## Defaults worth knowing The constructor's defaults explain most surprises: - **`base_url="http://testserver"`**, so relative paths such as `"/items/"` go to host `testserver`. An app behind Starlette's `TrustedHostMiddleware` has to allow that host in its test configuration. - **`client=("testclient", 50000)`**, which is what `request.client` reports, and a `user-agent` of `testclient`. - **`follow_redirects=True`**, unlike a plain httpx client, so a redirect is followed unless you pass `follow_redirects=False` on the call. - **`raise_server_exceptions=True`**, so an unhandled exception in the endpoint is re-raised into the test instead of becoming a 500 response. - **`root_path=""`**, the ASGI root path the app sees; production values come from the server or proxy, not from the test. - Passing `timeout=` to a request emits a `StarletteDeprecationWarning`, and the in-process transport does not apply it: there is no network to time out. ## A worked test 1. Import `app` and build one `client = TestClient(app)` for the module. 2. Write a `def test_...` function per behaviour: the happy path, a bad header, a missing field. 3. Send the request with `json=` and `headers=` exactly as a real caller would. 4. Assert on `status_code` first, then on `response.json()`, so a failure tells you which part broke. Note what this client does **not** run. An app whose `lifespan` loads a model or opens a pool needs `with TestClient(app) as client:` for that code to run at all, and a test that must itself `await` something needs an async client instead. ## Common mistakes - **Awaiting the call.** `await client.get(...)` raises `TypeError`: the client returns a finished response, not an awaitable. - **Sending a model.** `json=item` with a Pydantic instance fails before the request leaves the test; send `jsonable_encoder(item)` instead. - **Form fields for a JSON body.** `data=` produces a form-encoded body, and a body model rejects it with a 422. - **Trusting a followed redirect.** A request to `"/items"` for a route declared as `"/items/"` is answered with a 307 and silently followed, so the test passes while real callers pay an extra round trip. - **Expecting a 500.** With the defaults an unhandled error is raised in the test; a test about the 500 itself needs `raise_server_exceptions=False`. ## Release notes for this stack FastAPI 0.143 installs Starlette 1.7.0, whose `TestClient` prefers the `httpx2` package and still works with plain `httpx`, the package `fastapi[standard]` installs, but emits a `StarletteDeprecationWarning` on import. Separately, httpx 0.28 warns that per-request `cookies=` is being deprecated: set cookies on the client (`TestClient(app, cookies={...})` or `client.cookies.set(...)`) instead. Neither changes what your assertions see, but a suite that turns warnings into errors will notice both.

  • How do you send cookies with FastAPI's TestClient without a deprecation warning?
    Set them on the client, not on each call: `TestClient(app, cookies={"session": "s1"})` or `client.cookies.set("session", "s1")`. httpx 0.28 warns that per-request `cookies=` is being deprecated because cookie persistence across calls is ambiguous. Client-level cookies are sent on every later request, which is also how a browser session behaves.
  • Why are TestClient tests written as def functions rather than async def?
    `TestClient` runs the async app on its own event loop in a blocking-portal thread and returns only when the response is complete, so each call is an ordinary blocking call. Inside an `async def` test it would still block and would run the app on a different loop from the test, so async tests use `httpx.AsyncClient` with `ASGITransport` instead.
  • What does a TestClient test never exercise in a FastAPI deployment?
    Everything the server process does: no Uvicorn, so no socket, no server-side HTTP parsing, no `--proxy-headers`, `--root-path` or timeouts. The client address defaults to `("testclient", 50000)` and the host to `testserver`, so code that reads `request.client` or the Host header sees test values, and those paths need a test against a running server.

  • TestClient calls must be awaited inside async def tests
  • Passing a Pydantic model to json= works because FastAPI serializes it
  • TestClient needs the app running under Uvicorn on port 8000
  • data= sends the dictionary as a JSON body
  • A crashing endpoint always comes back as a 500 response in TestClient

Assumes FastAPI 0.143 on Starlette 1.7.0, whose TestClient prefers httpx2 and warns when it falls back to the httpx package FastAPI's extras install.

open as a page

In a FastAPI test, how do you make an endpoint that depends on get_current_user run as a fixed test user?

level: juniorimportance: must knowfreq 62%

basics

~10 s

Add an entry to app.dependency_overrides keyed by the original get_current_user function, whose value is a callable returning the test user; FastAPI calls it instead on every request, and the test removes the entry afterwards.

open as a page

In FastAPI, what does wrapping TestClient(app) in a with block change for an app whose lifespan loads a model, and what breaks without it?

level: middleimportance: must knowfreq 60%

basics

~10 s

Entering with TestClient(app) runs the lifespan's startup, so the model loads and the yielded dict reaches request.state; leaving runs shutdown. Without the block the lifespan never runs, and reading request.state.model raises AttributeError.

open as a page

In FastAPI, what exactly must the key of app.dependency_overrides be, and why can a registered override silently never apply?

level: middleimportance: must knowfreq 52%

basics

~20 s

The key must be the exact callable given to Depends: the function, class, callable instance or lru_cache wrapper. FastAPI does a plain dict lookup, so an alias, a name or a look-alike never matches and raises no error.

open as a page

In a FastAPI test suite, when do you switch from TestClient to httpx.AsyncClient with ASGITransport, and what must that setup add?

level: middleimportance: should knowfreq 45%

basics

~20 s

Switch when the test must await something itself, such as an async database check. Write an async def test marked @pytest.mark.anyio, await an AsyncClient over ASGITransport(app=...) with a base_url, and run the lifespan through LifespanManager.

open as a page

In FastAPI's TestClient, what does raise_server_exceptions control, and how do you test the body of a 500 response?

level: middleimportance: should knowfreq 35%

basics

~20 s

raise_server_exceptions, True by default, re-raises an exception that escapes the app into the test instead of returning a 500. To assert on the 500 body, use TestClient(app, raise_server_exceptions=False); HTTPException and handled errors are ordinary responses either way.

open as a page

In FastAPI, when a test overrides get_db, which both get_current_user and the endpoint depend on, what runs during one request?

level: middleimportance: should knowfreq 40%

basics

~10 s

The override replaces get_db everywhere in the request's dependency graph, including inside the real get_current_user, and runs once per request so both receive the same fake session; get_db itself never runs.

open as a page

How do you override a FastAPI session dependency so tests use an in-memory SQLite database, and why does that need StaticPool?

level: middleimportance: should knowfreq 48%

basics

~10 s

A fixture builds a sqlite:// engine with StaticPool and check_same_thread=False, creates the tables and yields a Session; a second fixture maps get_session to a function returning it in app.dependency_overrides and removes the entry afterwards.

open as a page

An async FastAPI test that awaits a database call fails with "RuntimeError: ... attached to a different loop"; why does this happen, and how do you fix it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Asyncio objects belong to the loop that made them, and TestClient runs the app on its own portal loop, new per request outside a with block. Put test and app on one loop: AsyncClient with ASGITransport, resources created in the lifespan.

open as a page

In a FastAPI suite, why does an entry left in app.dependency_overrides reach later tests, and how should fixtures restore it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

app.dependency_overrides is a dict on the module-level FastAPI object, shared by every test and every TestClient, and nothing resets it. Set overrides in yield fixtures, remove them in teardown, and add an autouse guard that fails a test leaving entries behind.

open as a page

A FastAPI test overrides the lru_cache-wrapped get_settings, yet part of the app still uses production values; what does the override not reach?

level: seniorimportance: should knowfreq 33%

basics

~20 s

An override of get_settings only reaches values FastAPI resolves through Depends during a request. Direct get_settings() calls at import, in the lifespan or in helpers still run the real lru_cache function and keep the production Settings.

open as a page