In FastAPI, how do you test an endpoint with fastapi.testclient.TestClient, sending a JSON body and a request header?
answer
- synchronous calls, no await
- httpx-style keyword arguments
- json= versus data=
- status_code and json() on the response
- default host testserver
basics
~10 sBuild 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 linesfrom 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 == 422go deeper
Recall the shape: TestClient(app), plain def tests, json= for a body, headers= for headers, then assert on status_code and response.json().
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.
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.
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.