Your First Endpoint Test
Exit

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.

  1. Add two imports at the top of the file: TestClient from fastapi.testclient and app from main.
  2. Below the existing tests, create a client variable by calling TestClient(app).
  3. Define a function called test_create_expense.
  4. Inside it, call client.post("/expenses", json={"description": "Lunch", "amount": 12.50, "category": "food"}) and store the result in response. This sends a POST request to your API with a JSON body — the same as clicking "Try it out" in Swagger, but in code.
  5. Add three assertions, each on its own line:
    • response.status_code equals 201
    • response.json()["description"] equals "Lunch"
    • "id" in response.json()