Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathShip Your First Model: From Notebook to a FastAPI Service
  1. 1
    Saving and Loading Models with joblib: One Pipeline, One File
  2. 2
    FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  3. 3
    Deploy a Machine Learning Model with FastAPI: POST /predict for a Saved Model
  4. 4
    Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
  5. 5
    Python Virtual Environments: One Project, One Toolbox
  6. 6
    Git and GitHub Fundamentals: Commits, Branches, Push and Pull
  7. 7
    Testing a FastAPI App with pytest: Three Small Tests
  8. 8
    Config and Logging Instead of Hard-Coded Values in ML Training
  9. 9
    SQL Essentials for Python: SELECT, WHERE, JOIN and GROUP BY
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. MLOps and Production ML

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.

Chaand Sheikh

·27 November 2026Engineering Basics

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:

RequestStatusBody
GET /200{"message": "Hello World"}
GET /hello/Chand200{"message": "Hello Chand"}
GET /hello/123400{"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.
  • assert means "this must be true". We assert the status code is 200 (the request worked) and the body is Hello World.
How a TestClient test runs test_hello_world assert 200 assert Hello World TestClient no server needed FastAPI app main.py client.get("/") 200, {"message": "Hello World"}
The test sends a request through 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:21 tells 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

PieceWhat it does
TestClient(app)Calls the app directly, no server
def test_...():A test pytest can find
assert response.status_code == 200The request worked
assert response.json() == {...}The body is exactly right
pytest -vRuns 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 →
← Previous
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
Next →
Config and Logging Instead of Hard-Coded Values in ML Training
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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.

On this page
  • The app
  • The first test
  • Running pytest
  • Testing good and bad names
  • Delete the validation and watch a test fail
  • Common mistakes
  • Recap
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.