API testing with pytest + requests: verify what the API really does, not what REST says
10 tests against Restful-booker, a public practice API: authentication, CRUD, schema validation and negative cases. Several of its responses do not follow REST, and the tests pin them exactly as they are.
The problem
An API suite written "from memory" about how REST services should respond fails for the wrong reasons: it expects 200, 201, 204, 401 or 400 that the API never returns, and the test gets tweaked until it passes without anyone knowing what the server actually does.
The approach
Every endpoint was first tried by hand (curl or Postman) and what was observed became the assertion. An HTTP client plays the role of a "Page Object" for the API, each test creates and deletes its own data, response shape is validated with pydantic, and the response is attached to the report only at the validation point.
What the API really answers
| Endpoint | What REST would expect | What it returns |
|---|---|---|
| GET /ping | 200 | 201 |
| POST /booking | 201 | 200 (and it creates the resource) |
| DELETE /booking/{id} | 204 | 201 |
| POST /auth with invalid credentials | 401 | 200 with {"reason": "Bad credentials"}: you must read the body, not just the status |
| PUT / DELETE without a token | 401 | 403; the token goes in the token=… cookie, not in Authorization |
| POST /booking missing a required field | 400 | 500: a real defect in the API |
Key decisions
Nothing is assumed by convention. Six behaviors that do not follow REST were documented and pinned in tests, not "fixed" in the suite.
BookingClient wraps the HTTP calls: a test never builds URLs or headers by hand, just like a Page Object in UI.
The fixture creates the booking and deletes it at the end; the API is public and shared, and another test's data cannot affect mine.
How it runs
def test_create_booking_missing_required_field_returns_500(api_client):
incomplete_payload = {
"lastname": "Gonzalez",
"totalprice": 150,
"depositpaid": True,
"bookingdates": {"checkin": "2026-08-01", "checkout": "2026-08-05"},
}
response = api_client.create_booking(incomplete_payload)
attach_response(response, "Respuesta de POST /booking sin firstname")
assert response.status_code == 500 # comportamiento real, aunque incorrecto
Real test from api-tests/restful-booker/tests/test_negative_cases.py (comments in Spanish).
Limits
- The API is public and shared: its data resets and it can be slow or down. That is why every test creates its own, and the suite still needs network access (the CI API job too).
- The tests pin the API's defects (for example the 500). If they ever fix it, those tests will fail: that is intentional, they flag the change.
- It covers the endpoints this portfolio uses; there is no load or security testing.