API Testing with FastAPI and Pytest: A Practical Guide for Beginners

By Ezenwa Christian Chimeremeze
1. Introduction to API Testing
Let me tell you how I used to test my APIs.
I would start the server, open my browser, go to /docs, click "Try it out", type something, and see if it worked. If it returned 200, I would say "it works" and move on.
Then one day I changed one small thing in my code, and something else broke quietly. No error on my screen. No crash. Just wrong data coming back. My users noticed before I did.
That is when I learnt this: manual testing is not testing. It is checking.
API testing means you write code that calls your API for you, checks the response, and tells you immediately if something is wrong. You do not have to remember what to test. The test remembers for you.
In this tutorial, we will test a FastAPI app with Pytest. No big theory. Just practical tests you can run again and again.
If you followed my last article on Airbyte, PostgreSQL and FastAPI, this is the next step. Building the API is one job. Proving it works is another job.
2. What is FastAPI?
FastAPI is a Python framework for building APIs fast. And when I say fast, I mean two things: fast to write, and fast to run.
What I like about it:
You write normal Python functions, and FastAPI turns them into endpoints.
It validates your input automatically using Pydantic.
It gives you free interactive docs at
/docs.It is built on Starlette and Pydantic, so it is solid underneath.
Here is a small example we will test in this article. Create main.py:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI(title="Beginner Testing API") class Item(BaseModel): name: str price: float in_stock: bool = True items_db = {} @app.get("/health") def health_check(): return {"status": "healthy"} @app.post("/items", status_code=201) def create_item(item: Item): item_id = len(items_db) + 1 items_db[item_id] = item return {"id": item_id, **item.model_dump()} @app.get("/items/{item_id}") def get_item(item_id: int): if item_id not in items_db: raise HTTPException(status_code=404, detail="Item not found") return {"id": item_id, **items_db[item_id].model_dump()} That is our whole API for this tutorial. Three endpoints: health check, create item, get item. Small enough to understand, big enough to test properly.
3. Understanding Pytest
Pytest is a testing framework for Python. People like it because it is simple.
You do not need to write classes. You do not need to remember plenty of setup. You write a function that starts with test_, you use plain assert, and Pytest does the rest.
Compare it to this thinking:
Without Pytest: You manually call the API, look at the screen, and decide if it looks correct.
With Pytest: You write
assert response.status_code == 200and Pytest decides for you.
Three words you need to know:
Test: A function that checks one behaviour.
Assertion: A line like
assert response.status_code == 201that must be true, otherwise the test fails.Fixture: A reusable setup. For example, a fresh test client for every test, so one test does not pollute another.
We will use all three in this article.
4. Setting Up a FastAPI Testing Environment
Let us set up properly, so we do not have stress later.
Step 1: Create your environment
python -m venv .venv
source .venv/bin/activate
Step 2: Install dependencies
pip install fastapi uvicorn pytest httpx
Why httpx? FastAPI's TestClient is built on top of it. Without it, your tests will not run.
Step 3: Project structure
Keep it simple:
my_api/
main.py
test_main.py
That is it. main.py is your app. test_main.py is your tests. Do not put tests inside main.py. Keep them separate.
Step 4: Create your TestClient
At the top of test_main.py, add:
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
TestClient lets you call your API without actually starting a server. It is fast, and it is perfect for beginners. You do not need to run uvicorn to test.
But there is one problem with this simple setup: our items_db dictionary will keep data between tests. If one test creates an item, the next test will see it. That can cause confusing failures.
We will fix that in Section 9 with fixtures. For now, just know it is coming.
5. Writing Your First API Test
Let us write the simplest test possible. The health check.
`In `test_main.py`: def test_health_check(): response = client.get("/health") assert response.status_code == 200 assert response.json() == {"status": "healthy"} Run it: pytest -v You should see: test_main.py::test_health_check PASSED` That is your first automated test. One small thing, but it is powerful. From now on, every time you change your code, you can run pytest and know in seconds if your health endpoint still works.
Let me break down what happened:
client.get("/health")calls your API, like a browser would.response.status_codeis the HTTP code — 200 means OK.response.json()is the body as a Python dictionary.assertsays "this must be true, or fail the test."
If you can understand this one test, you can understand all the others. They are the same pattern, just with different endpoints and data.
6. Testing Successful and Unsuccessful Responses
A good test does not only check the happy path. It also checks what happens when things go wrong.
Test a successful creation:
def test_create_item_success(): response = client.post( "/items", json={"name": "Laptop", "price": 250000.0, "in_stock": True} ) assert response.status_code == 201 data = response.json() assert data["name"] == "Laptop" assert data["price"] == 250000.0 assert "id" in data *Test a successful fetch:* def test_get_item_success(): # First create an item create_response = client.post( "/items", json={"name": "Phone", "price": 150000.0} ) item_id = create_response.json()["id"] # Then fetch it response = client.get(f"/items/{item_id}") assert response.status_code == 200 assert response.json()["name"] == "Phone" *Test an unsuccessful fetch — item not found:* def test_get_item_not_found(): response = client.get("/items/9999") assert response.status_code == 404 assert response.json()["detail"] == "Item not found" This last one is important. Many beginners only test success. But users will request items that do not exist. Your API must return 404, not 500, not an empty 200. Your test proves it does.
7. Testing Request Validation
This is where FastAPI shines, and where many beginners get surprised.
FastAPI validates your input automatically because of Pydantic. If you send a wrong type, it will not crash. It will return 422 Unprocessable Entity.
Let us test that.
Test missing required field:
def test_create_item_missing_name(): response = client.post( "/items", json={"price": 1000.0} ) assert response.status_code == 422 We did not send `name`, which is required. FastAPI should reject it. *Test wrong type:* def test_create_item_wrong_price_type(): response = client.post( "/items", json={"name": "Book", "price": "not-a-number"} ) assert response.status_code == 422 Price should be a float. We sent a string that cannot be converted. FastAPI should reject it. *Test extra check — default value:* def test_create_item_default_in_stock(): response = client.post( "/items", json={"name": "Pen", "price": 500.0} ) assert response.status_code == 201 assert response.json()["in_stock"] is True We did not send in_stock, but our model says in_stock: bool = True. So FastAPI should fill it in. This test proves your defaults work.
Validation testing is not boring. It is how you prove your API will not accept rubbish data from the frontend or from a bad client.
8. Testing API Error Handling
Error handling is not just about status codes. It is about what your API tells the client when something goes wrong.
In our API, we have two main errors:
- 404: Item not found
- 422: Validation failed
We already tested both. Let us add one more layer: check the structure of the error.
def test_not_found_error_structure(): response = client.get("/items/9999") data = response.json() assert response.status_code == 404 assert "detail" in data assert isinstance(data["detail"], str) Why check the structure? Because your frontend will depend on it. If your frontend expects `data["detail"]` and you change it to `data["message"]` one day, the frontend will break. Your test will catch that change early. One more practical tip: never expose internal details in your error responses. A good error says "Item not found". A bad error says "KeyError: 9999 in items_db at line 24 in http://main.py". The first helps the user. The second helps an attacker.
In our test, we assert the detail is a clean string. That is a small way to enforce good error handling.
9. Organizing and Running Automated Tests
Now let us fix the problem I mentioned in Section 4 — tests polluting each other.
Our items_db is global. If test_create_item_success runs first and creates an item with id 1, then test_get_item_success will create an item with id 2, not id 1. That is confusing.
Solution: Use a fixture to reset the database before each test.
Update test_main.py to this clean version:
import pytest from fastapi.testclient import TestClient from main import app, items_db client = TestClient(app) @pytest.fixture(autouse=True) def reset_db(): # Runs before each test items_db.clear() yield # Runs after each test items_db.clear() `@pytest.fixture(autouse=True)` means "run this automatically before every test". Now every test starts with an empty database. No pollution. No guessing.
How to run your tests:
Run all tests
pytest
Run with details
pytest -v
Run only one file
pytest test_main.py -v
Run only tests with a keyword
pytest -k "not_found" -v
See coverage (optional but useful)
pip install pytest-cov
pytest --cov=main -v
How to organize when you grow:
my_api/
main.py
models.py
database.py
tests/
test_items.py
test_health.py
One file per feature. test_items.py for items, test_health.py for health. When you have 50 tests, you will thank yourself for organizing early.
10. Common Mistakes and Best Practices
These are mistakes I have made myself, and I see beginners make them often.
Mistake What To Do Instead
Only testing success cases Always test 404, 422, and invalid input
Hardcoding IDs that depend on test order Use fixtures to reset state, create fresh data in each test
Testing with a real database in unit tests Use TestClient and in-memory data for unit tests, use a separate test database for integration tests
Checking only status code Also check response body, fields, and error structure
Writing one giant test that checks everything One test = one behaviour. Small tests are easier to debug
Not running tests after every change Run pytest before you commit, every time
Exposing internal errors Return clean error messages, log the real error internally
Best practices I follow now:
One test, one behaviour. If a test fails, you should know immediately what broke.
Use descriptive names.
test_get_item_not_foundis better thantest_2.Test validation. If FastAPI gives you free validation, test that it works.
Keep tests fast. If tests are slow, you will stop running them. TestClient is fast. Use it.
Do not test FastAPI itself. You do not need to test that FastAPI can return JSON. Test your logic: your validation, your 404, your business rules.
11. Conclusion
API testing is not something you do after you finish building. It is part of building.
FastAPI gives you the API. Pytest gives you the proof that it works. Together, they give you confidence. You can change your code, run pytest, and know in seconds if you broke something.
In this tutorial, you learnt how to set up a testing environment, write your first test, test success and failure, test validation, test error handling, and organize your tests so they stay clean as you grow.
That is the foundation. The next step is to apply it to a real project — like the FastAPI + PostgreSQL API from my last article. Replace the in-memory items_db with a real database, use a test database, and write the same kinds of tests for your /records endpoints.
That is how I build now. One working endpoint, one passing test at a time.
Official Technical References
- FastAPI Tutorial — https://fastapi.tiangolo.com/
- FastAPI Testing — https://fastapi.tiangolo.com/tutorial/testing/
- Pytest Documentation — https://docs.pytest.org/
- Pydantic Documentation — https://docs.pydantic.dev/
- HTTPX Documentation — https://www.python-httpx.org/
I am Ezenwa Christian Chimeremeze, a Technical Writer and Python Engineer based in Imo State, Nigeria. I write about FastAPI, PostgreSQL, and AI systems — from what I have built, broken, fixed, and shipped myself, often from my phone using Termux.

