TestClient
A test client for testing FastAPI applications. It allows you to make requests to your application without running a server, making it perfect for unit and integration tests. TestClient is based on Starlette’s TestClient, which uses thehttpx library under the hood.
Constructor
FastAPI
required
The FastAPI application instance to test.
str
default:"http://testserver"
The base URL to use for requests.
HTTP Methods
TestClient provides methods for all standard HTTP verbs:get
post
put
delete
patch
options
head
Common Parameters
All request methods accept these common parameters:str
required
The URL path to request (e.g., “/items/1”).
dict
Query parameters to include in the URL.
dict
HTTP headers to send with the request.
dict
Cookies to send with the request.
Any
JSON data to send in the request body (automatically serialized).
dict
Form data to send in the request body.
dict
Files to upload (e.g.,
{"file": open("test.txt", "rb")}).Response Object
The response object provides:response.status_code- HTTP status code (e.g., 200, 404)response.json()- Parse response body as JSONresponse.text- Response body as textresponse.content- Response body as bytesresponse.headers- Response headersresponse.cookies- Response cookies
Testing Examples
Testing with Authentication
Testing File Uploads
Testing with Dependencies
Usage Notes
- No need to run a server - tests run synchronously
- Startup and shutdown events are triggered automatically
- You can override dependencies for testing
- Context managers are supported:
with TestClient(app) as client: - WebSocket testing is also supported via
client.websocket_connect() - All requests are synchronous, even if your path operations are async