Your First Endpoint Test
Use TestClient to send a POST request and verify the response
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
From model tests to endpoint tests
Unit tests check your models in isolation. Endpoint tests check the full request cycle — HTTP method, URL, request body, status code, and response body. If a unit test catches a validation bug, an endpoint test catches a routing bug, a missing field in the response, or a wrong status code.
TestClient
FastAPI provides a TestClient that sends HTTP requests to your app without starting a real server. You import your app object, wrap it in TestClient, and call methods like client.post() and client.get().
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)The client object has methods that mirror HTTP methods: .get(), .post(), .patch(), .delete(). Each method returns a response object with .status_code and .json().
Isolating tests
Each test function should be independent. Creating test data inside the test (rather than sharing data across tests) means tests can run in any order without affecting each other. You will create a fresh expense inside each test that needs one.
Instructions
Add a TestClient and write your first endpoint test.
- Add two imports at the top of the file:
TestClientfromfastapi.testclientandappfrommain. - Below the existing tests, create a
clientvariable by callingTestClient(app). - Define a function called
test_create_expense. - Inside it, call
client.post("/expenses", json={"description": "Lunch", "amount": 12.50, "category": "food"})and store the result inresponse. This sends a POST request to your API with a JSON body — the same as clicking "Try it out" in Swagger, but in code. - Add three assertions, each on its own line:
response.status_codeequals201response.json()["description"]equals"Lunch""id" in response.json()
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding