API Testing in Python: Build a Pytest and Requests Suite Step by Step
API testing in Python needs only pytest, requests and a few good habits. Build a real suite with fixtures, status code and header checks, JSON schema validation, a full create-read-delete flow, negative and auth tests, and see what happened when we planted a bug in the API.
- API testing in Python needs three libraries:
pytestto run tests,requeststo call the API, andjsonschemato check response shapes. - Put the base URL and an authenticated session in fixtures so every test stays short.
- Test far more than 200 OK: headers, schemas, bad payloads, missing auth and error codes. 9 of our 13 tests were negative or edge cases.
- When we planted a type bug in the API, schema validation caught it with a precise message. It also showed that JSON Schema treats
450.0as a valid integer.
APIs are the contract between your frontend, mobile apps, partners and microservices. A UI test can tell you a page broke; an API test tells you exactly which response changed, in milliseconds, without a browser. That makes API tests the fastest, most stable layer for most automation suites, as the test pyramid suggests.
In this tutorial we build a complete API testing in Python suite against a small book API we wrote with Python’s http.server, running on 127.0.0.1. We used pytest 9.2, requests 2.34.2 and jsonschema 4.26.0 on Python 3.13.6, and every result shown came from those runs.
Why test at the API level?
- Speed: our 13 tests finished in under 1.6 seconds.
- Stability: no selectors, rendering delays or browser quirks.
- Precision: a failure points at one endpoint and one field.
- Early feedback: APIs can be tested before the UI exists, which fits shift-left testing.
The tool stack
pip install pytest requests jsonschema
pytest discovers and runs tests and gives you fixtures and parametrisation. requests sends HTTP calls. jsonschema validates that a JSON body has the expected fields and types. Optional extras such as pytest-xdist for parallel runs and pytest-html for reports can come later. If you prefer a GUI first, our Postman API testing guide covers the same ideas without code.
The API under test
Our book API has these endpoints:
| Method and path | Behaviour |
|---|---|
GET /books |
List books, optional max_price filter |
GET /books/{id} |
One book, 404 if missing, 400 if the id is not a number |
POST /books |
Create; needs a bearer token; 201 with a Location header; 422 for invalid data; 400 for broken JSON |
DELETE /books/{id} |
Delete; needs a token; 204 on success |
GET /me |
Current user; 401 with WWW-Authenticate: Bearer without a token |
The token is a dummy value, test-token, that only exists in this local test server. Never put real credentials in test code; load them from environment variables in CI.
Fixtures: base URL and an authenticated session
# conftest.py
import pytest, requests
from server import start
@pytest.fixture(scope="session")
def base_url():
srv = start(8766) # start the local API once per run
yield "http://127.0.0.1:8766"
srv.shutdown()
@pytest.fixture
def api(base_url):
s = requests.Session()
s.headers["Authorization"] = "Bearer test-token"
s.base = base_url
yield s
s.close()
The base_url fixture runs once per session, starts the server and stops it at the end. The api fixture gives each test a fresh, authenticated Session. In a real project, base_url would read an environment variable such as API_BASE_URL so the same suite can target local, staging or a container. Our pytest fixtures guide explains scopes in depth.
Testing status codes and headers
def test_list_books_returns_json_array(api):
r = api.get(f"{api.base}/books", timeout=5)
assert r.status_code == 200
assert r.headers["Content-Type"].startswith("application/json")
for book in r.json():
validate(book, BOOK_SCHEMA)
def test_filter_by_max_price(api):
r = api.get(f"{api.base}/books", params={"max_price": 300}, timeout=5)
assert all(b["price"] <= 300 for b in r.json())
Assert the exact status code, not just “success”. A 200 where you expected 201 can signal a real bug, such as a create endpoint that silently updated an existing record. Checking Content-Type catches servers that return an HTML error page with a 200 status. Every call passes timeout=, so a hung API fails the test instead of freezing the run; our Python requests guide explains why.
Validating the JSON schema
from jsonschema import validate
BOOK_SCHEMA = {
"type": "object",
"required": ["id", "title", "price"],
"properties": {
"id": {"type": "integer"},
"title": {"type": "string", "minLength": 1},
"price": {"type": "integer", "minimum": 0},
},
"additionalProperties": False,
}
One schema check replaces a dozen individual asserts. It confirms required fields exist, types are right, values are in range and no unexpected fields leaked out, such as an internal cost_price. Keep schemas in a shared module so every test that touches a book uses the same contract. For contracts shared between teams, see our API contract testing guide.
A full create, read, delete flow
def test_create_then_fetch_then_delete(api):
r = api.post(f"{api.base}/books", json={"title": "API Testing", "price": 399}, timeout=5)
assert r.status_code == 201
new = r.json(); validate(new, BOOK_SCHEMA)
assert r.headers["Location"] == f"/books/{new['id']}"
assert api.get(f"{api.base}/books/{new['id']}", timeout=5).json() == new
assert api.delete(f"{api.base}/books/{new['id']}", timeout=5).status_code == 204
assert api.get(f"{api.base}/books/{new['id']}", timeout=5).status_code == 404
This one test proves the create response, the Location header, that the record can be read back unchanged, that delete works, and that the record is really gone. It also cleans up after itself, so the test can run repeatedly without polluting data. Self-cleaning tests are essential when suites run against shared environments.
Negative tests with parametrize
@pytest.mark.parametrize("payload,code", [
({"title": "No price"}, 422),
({"title": "Negative", "price": -5}, 422),
({"title": "Text price", "price": "10"}, 422),
([], 422),
])
def test_create_rejects_bad_payloads(api, payload, code):
r = api.post(f"{api.base}/books", json=payload, timeout=5)
assert r.status_code == code
assert "error" in r.json()
def test_invalid_json_body(api):
r = api.post(f"{api.base}/books", data="{bad json",
headers={"Content-Type": "application/json"}, timeout=5)
assert r.status_code == 400
Negative tests matter more than happy paths, because they guard the validation that protects your data. pytest parametrize turns one function into a test per payload, each reported separately. The ideas come straight from boundary value analysis and negative testing: missing fields, wrong types, out-of-range values and malformed bodies.
Authentication tests
def test_requires_auth(base_url):
r = requests.post(f"{base_url}/books", json={"title": "x", "price": 1}, timeout=5)
assert r.status_code == 401
assert requests.get(f"{base_url}/me", timeout=5).headers["WWW-Authenticate"] == "Bearer"
This test deliberately uses plain requests instead of the authenticated fixture. Always test that protected endpoints reject missing, expired and wrong tokens, and that one user cannot read another user’s data. Security bugs in APIs are often just missing authorisation checks.
Error codes
@pytest.mark.parametrize("path,code", [("/books/99", 404), ("/books/abc", 400), ("/nope", 404)])
def test_error_codes(api, path, code):
assert api.get(api.base + path, timeout=5).status_code == code
A missing resource should be 404, a malformed id 400, and an unknown route 404. Servers that return 500 for bad input are leaking unhandled exceptions. Our HTTP status codes cheat sheet lists what each code should mean.
A simple response time budget
def test_response_time_budget(api):
r = api.get(f"{api.base}/books/1", timeout=5)
assert r.elapsed.total_seconds() < 0.5
A loose budget catches big regressions, such as a missing database index that turns 50 ms into 5 seconds. Keep it generous to avoid flaky tests on busy CI machines, and use real tools for load testing, as covered in our load vs stress testing guide.
Running the suite
pytest -v test_books_api.py
test_list_books_returns_json_array PASSED
test_filter_by_max_price PASSED
test_create_then_fetch_then_delete PASSED
test_create_rejects_bad_payloads[payload0-422] PASSED
test_create_rejects_bad_payloads[payload1-422] PASSED
test_create_rejects_bad_payloads[payload2-422] PASSED
test_create_rejects_bad_payloads[payload3-422] PASSED
test_invalid_json_body PASSED
test_requires_auth PASSED
test_error_codes[/books/99-404] PASSED
test_error_codes[/books/abc-400] PASSED
test_error_codes[/nope-404] PASSED
test_response_time_budget PASSED
13 passed in 0.90s
Planting a bug: does the suite catch it?
A suite that never fails proves little. We changed the server so one book’s price came back as a string, "450", a common serialisation bug. The suite reported 2 failed, 11 passed, with a clear message from the schema check:
E jsonschema.exceptions.ValidationError: '450' is not of type 'integer'
E Failed validating 'type' in schema['properties']['price']:
E {'type': 'integer', 'minimum': 0}
The second failure came from the price filter test. The server’s filter code crashed with a TypeError comparing the string with a number and closed the connection, so the test saw requests.exceptions.ConnectionError: Remote end closed connection without response. One small type bug broke two features. Our first attempt at planting a bug was more surprising: we changed the price to 450.0 and every test still passed. JSON Schema defines an integer as any number with no fractional part, so 450.0 is valid. If your API must return true integers, add an explicit check such as isinstance(book["price"], int). Planting bugs on purpose, the idea behind mutation testing, is the best way to learn what your suite really guards.
Tip: run the suite against a deliberately broken build at least once. If nothing fails, your tests are checking too little.
Project structure for a growing suite
api-tests/
conftest.py # fixtures: base_url, api session, test data
schemas.py # shared JSON schemas
clients/books.py # small wrapper: create_book(), get_book()
tests/
test_books.py
test_auth.py
pyproject.toml # pytest settings and markers
As the suite grows, move repeated calls into a small client module, so tests read like book = books.create(title="x"). Group slow or destructive tests with pytest markers, and keep test data creation in fixtures.
Running API tests in CI
Start the API (or a container of it), set API_BASE_URL, and run pytest -q. Fail the pipeline on any test failure, publish a JUnit XML report with --junitxml=report.xml, and run the suite on every pull request. Our GitHub Actions guide shows a complete workflow.
Final thoughts
Good API testing in Python is not about clever code. It is about checking the full contract: status, headers, schema, behaviour, errors and security, with fixtures that keep each test short and self-cleaning. Start with the suite above, plant a bug to prove it bites, and grow it endpoint by endpoint. It will become the fastest and most trusted part of your automation.
FAQ
Which Python library is best for API testing?
Most teams use pytest with requests, plus jsonschema for response validation. httpx is a good alternative when you need async support.
How do I validate a JSON response in pytest?
Parse it with response.json and check it against a JSON schema using jsonschema.validate, then add asserts for specific values that matter.
What should an API test check besides the status code?
Headers such as Content-Type, the response schema, field values, error messages, authentication rules, side effects such as created records, and response time.
Should API tests hit a real server or a mock?
Both have a place. Tests against a real or containerised API catch integration bugs, while mocks keep client unit tests fast and isolated.
How do I keep API tests from leaving test data behind?
Create data inside the test or a fixture and delete it at the end, ideally in fixture teardown, so cleanup runs even when an assertion fails.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.