Why Test an API?
Understand why manual testing breaks down and how automated tests solve it
The problem with manual testing
In the previous course, you tested your API by starting the server, opening Swagger, and clicking "Try it out." That works when you have one or two routes. But your expense tracker now has six routes, each with multiple valid and invalid inputs.
Every time you change the code, you would need to retest every route by hand. Miss one, and a bug slips through. As the API grows, manual testing becomes slower and less reliable.
Automated tests fix this
An automated test is a function that calls your code, checks the result, and reports whether it passed or failed. You run all your tests with a single command. If any test fails, you know exactly what broke.
Two kinds of tests
There are two kinds of tests you will write in this lesson:
- Unit tests: test a single piece of logic in isolation — no server, no HTTP, no network. You call a function or create an object and check the result. If a unit test fails, you know the problem is in that one function.
- Endpoint tests: test a full HTTP request through your API using FastAPI's
TestClient. These are more realistic because they exercise the full request cycle: routing, validation, business logic, and response formatting.
When unit tests are worth writing
Not everything deserves a unit test. Your Expense model has built-in constraints like Field(gt=0) and Field(min_length=1). Testing that those work means testing Pydantic — a battle-tested library with its own extensive test suite. If you wrote Field(gt=0), it works. You do not need to verify that.
Unit tests become valuable when you write custom logic — a @field_validator that parses a date format, a function that calculates totals, or a helper that transforms data. That is your code, and it can have bugs.
Your expense tracker already has custom logic worth testing: the @field_validator on the date field that checks the YYYY-MM-DD format. In the next few chapters, you will write unit tests for that validator, then move on to endpoint tests for the rest of the API.
pytest
pytest is the most widely used testing framework in Python. You write functions that start with test_, use assert to check results, and run them with the pytest command. pytest discovers your test files automatically, runs every test function, and shows a pass/fail summary.