Learning path: Ship Your First Model: From Notebook to a FastAPI Service · Step 7 of 9
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
What you will learn
- Call a FastAPI app from a test with TestClient, without starting a server
- Write test functions that assert the status code and the JSON body
- Test both a valid input and an input the app must refuse
- Run pytest -v and read a failing test's output
Before you start
- FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
- Python Virtual Environments: One Project, One Toolbox
You've built a FastAPI route (see FastAPI Hello World) and checked it in the browser. It works. Then you change something next week. Does it still work? You could open the browser and check by hand after every change. Or you can write a small test once and let it check for you, every time.
We'll keep this simple: one small app, three small tests.
The app
Here's main.py. It has two routes.
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello World"}
@app.get("/hello/{name}")
def hello(name: str):
if not name.isalpha():
msg = "Name must contain only letters"
raise HTTPException(400, msg)
return {"message": f"Hello {name}"}
The first route, /, returns a message that says Hello World. The second, /hello/{name}, says hello to a name, but first it checks the name:
name.isalpha()is true only when every character is a letter. A number fails, and a symbol fails too.- When it fails,
HTTPException(400, msg)sends back status 400, which means the request was bad, along with a clear message.
Here's what the app sends back for three requests:
| Request | Status | Body |
|---|---|---|
GET / | 200 | {"message": "Hello World"} |
GET /hello/Chand | 200 | {"message": "Hello Chand"} |
GET /hello/123 | 400 | {"detail": "Name must contain only letters"} |
The first test
Tests go in test_main.py, next to main.py.
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_hello_world():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}
TestClient(app)calls our app for us, so we don't need to start a server.- A test is just a small function whose name starts with
test. That's how pytest finds it. client.get("/")calls the route and gives back a response.assertmeans "this must be true". We assert the status code is 200 (the request worked) and the body is Hello World.
TestClient straight into the app, gets the response back, and checks it with assert.Running pytest
The project needs three packages (in a virtual environment):
fastapi
httpx
pytest
Install them with pip install -r requirements.txt, then run pytest. -v shows each test by name:
pytest -v
collecting ... collected 3 items
test_main.py::test_hello_world PASSED [ 33%]
test_main.py::test_valid_name PASSED [ 66%]
test_main.py::test_invalid_name PASSED [100%]
======================== 3 passed, 1 warning in 1.30s =========================
It found three tests in the file. We've only looked at the first one so far; the other two come next. All three passed.
The one warning comes from a library (FastAPI's test client), not from our code, so we can leave it for now.
Testing good and bad names
Here are the other two tests in test_main.py:
def test_valid_name():
response = client.get("/hello/Chand")
assert response.status_code == 200
assert response.json() == {"message": "Hello Chand"}
def test_invalid_name():
response = client.get("/hello/123")
assert response.status_code == 400
assert response.json() == {
"detail": "Name must contain only letters"}
The first sends Chand and expects 200 and Hello Chand. The second sends 123 and expects 400 and the error message. So we check both sides: what should work, and what should be refused.
Delete the validation and watch a test fail
Why does this matter? Let's remove the three validation lines, as if we deleted them by mistake:
@app.get("/hello/{name}")
def hello(name: str):
return {"message": f"Hello {name}"}
The app still runs, and nothing crashes. But now GET /hello/123 returns status 200 and {"message": "Hello 123"}. Run pytest again:
test_main.py::test_hello_world PASSED [ 33%]
test_main.py::test_valid_name PASSED [ 66%]
test_main.py::test_invalid_name FAILED [100%]
================================== FAILURES ===================================
______________________________ test_invalid_name ______________________________
def test_invalid_name():
response = client.get("/hello/123")
> assert response.status_code == 400
E assert 200 == 400
E + where 200 = <Response [200 OK]>.status_code
test_main.py:21: AssertionError
=========================== short test summary info ===========================
FAILED test_main.py::test_invalid_name - assert 200 == 400
=================== 1 failed, 2 passed, 1 warning in 1.27s ====================
Two passed, one failed. Read the failure from the top:
- The
>marks the line that failed: the status code check. assert 200 == 400: the test wanted 400 and got 200.test_main.py:21tells you the file and line.
Put the validation back, run pytest again, and you're back to 3 passed. The test caught the mistake before anyone else saw it. That's why we write tests.
Test both sides. If we had only tested /hello/Chand, deleting the validation would have gone unnoticed. The test for the bad input is the one that caught it.
Common mistakes
- A test name that doesn't start with
test. pytest won't find it, and it silently never runs. - Checking only the status code. Assert the body too, so a wrong message also fails.
- Testing only the happy path. Add a test for each input the app must refuse.
Recap
| Piece | What it does |
|---|---|
TestClient(app) | Calls the app directly, no server |
def test_...(): | A test pytest can find |
assert response.status_code == 200 | The request worked |
assert response.json() == {...} | The body is exactly right |
pytest -v | Runs every test and names each one |
For typed request and response bodies in FastAPI, see Pydantic request and response models.
Try it yourself: add one more test with your own name, and check for status 200 and Hello with your name. The project files for this lesson are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Git and GitHub Fundamentals: Commits, Branches, Push and Pull
Next →Config and Logging Instead of Hard-Coded Values in ML Training
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.
SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
The SQL a Python developer needs, on a tiny shop with four customers and eight orders: CREATE TABLE, INSERT with placeholders, SELECT with WHERE, JOIN, GROUP BY, pandas.read_sql, and why values never go in f-strings.