Service & API testing
An instrumented HTTP client, service objects, response validation and a repeatable test-design checklist.
Building an instrumented HTTP client
One place owns timeouts, retries, logging and redaction — and retries only what is safe to repeat.
A single client class should own every transport concern so that service objects can stay about endpoints and models. Three details in that class repay the effort many times over. The first is an expected-status parameter, which collapses the ubiquitous two-line pattern of calling and then asserting a status into one call that also produces a useful message containing method, URL, expected status, actual status and body. Giving the resulting error assertion-flavoured behaviour (inheriting from AssertionError) is a matter of API taste, not test outcome — pytest reports FAILED vs ERROR based on which phase raised (the test body vs setup/teardown), not on the exception's type, so a plain exception from the call phase is already a failure. The second is a careful retry policy: retry-safety is a property of the operation and the failure mode, not just the HTTP method — repeating a POST can create a second order or double-charge a card unless the server guarantees idempotency (an idempotency key, for instance), so a method-based rule like "only GET/HEAD/OPTIONS/PUT/DELETE" is a reasonable default, not a law of HTTP. The same goes for status codes: a 500 usually means the defect you were hired to find, so it's excluded — but 502/503/504 are conventionally treated as transient infrastructure trouble (bad gateway, unavailable, gateway timeout) and are commonly retried under an explicit policy, which is a defensible choice, not a mistake. The third is redaction — authorization headers and cookies must be masked before anything is attached to a report that will be archived and shared.
Key points
- An expected-status parameter turns call-then-assert into one call with a useful failure message
- Retry-safety belongs to the operation, not just the HTTP verb: a policy usually excludes POST by default and always excludes genuine defects like 500, but transient 502/503/504 are commonly retried on purpose
- Redact authorization headers and cookies before attaching anything to a report
Code
Run the code to see the result.
The failure message alone is usually enough to file the ticket without reproducing anything.
See it in the framework
- Implementation · HTTP client implementation:
framework/http/client.py— live · reviewed - Used by · Retry-exhaustion regression test:
tests/framework/test_http_client.py— live · reviewed
Reviewed against commit f9ada16 (2026-08-14).
Common pitfalls
- A blanket retry policy that repeats POST requests and silently creates duplicate records, when the server hasn't proven the operation idempotent
- Attaching raw request headers to a report, which publishes a bearer token into an archived artifact
- Assuming the exception's type controls pytest's FAILED vs ERROR split — it's actually decided by which phase (call vs setup/teardown) raised, not what the exception inherits from
Practice exercise
Add an expected-status parameter to a client you maintain, then deliberately break an endpoint and check that the failure message contains the method, URL, both statuses and the response body.
Service objects: the API's page objects
One class per resource, with separate typed and raw methods for happy and negative paths.
Service objects do for an API what page objects do for a screen: one class per resource, owning its paths, payload shapes and response models, so tests read as business flow rather than as HTTP. A facade that gathers the resource classes together lets a test hold a single object and reach the whole API through it, which beats threading four fixtures into every signature. The design decision that keeps this layer from rotting is to provide two method styles rather than one clever method. A typed method covers the happy path, parses the response into a model and is what most tests use. A raw method returns the response untouched and is what negative tests use, because they care about status codes and error bodies rather than a parsed model. A single method that sometimes parses and sometimes does not accumulates flags and branches until nobody can predict its behaviour. It is also worth adding small helpers that express intent about data, with assertion messages that name the cause when fixture data changes.
Key points
- One class per resource, plus a facade so a test holds a single object
- Typed methods for happy paths, raw methods for negative paths — never one method doing both
- Data helpers should assert their preconditions with a message that names the cause
Code
class CartApi(BaseApi):
PATH = "/api/cart"
def add_item(self, product_id: int, quantity: int = 1) -> Cart:
"""Happy path: parsed, typed, ready to assert on."""
response = self.client.post(
f"{self.PATH}/items",
json={"product_id": product_id, "quantity": quantity},
expect=201,
)
return Cart.model_validate(response.json())
def add_item_raw(self, product_id: object, quantity: object = 1):
"""Negative path: status codes and error bodies, no parsing."""
return self.client.post(
f"{self.PATH}/items", json={"product_id": product_id, "quantity": quantity}
)
class ProductsApi(BaseApi):
def first_in_stock(self) -> Product:
products = self.list(in_stock=True)
assert products, "SUT has no in-stock products - fixture data is broken"
return products[0]That assertion message means twenty tests fail with a cause rather than with IndexError.
See it in the framework
- Implementation · Service object implementation:
framework/api/shop.py— live · reviewed - Used by · Used by:
tests/services/test_cart_flow.py— live · reviewed
Reviewed against commit f9ada16 (2026-08-14).
Common pitfalls
- A single method with a flag such as parse=False, which grows branches until its behaviour is unpredictable
- Helpers that fail with IndexError when demo data changes, instead of a message explaining that fixture data is broken
Practice exercise
Add a service object for one endpoint of an API you work with, including both method styles, then write one happy-path test and one boundary test that each use the appropriate style.
Validating responses: models, schemas and drift
Declare the suite's own models, forbid unknown fields, and use JSON Schema for contracts you do not own.
Validating a response with a typed model turns a whole category of assertions into one line: types, required fields and numeric ranges are all checked at once, and a failure names the exact field. The decision that gives this its power is to declare the suite's own models rather than importing the server's. Sharing the production models feels efficient and quietly destroys the value, because when a developer renames a field the shared model renames with it and every test still passes. A separate declaration is also what makes forbidding unknown fields meaningful: an undocumented new field in a response becomes a visible, discussable change rather than something nobody notices for six months. Configure models as strict and frozen so a test cannot accidentally mutate a shared response object. Raw JSON Schema still has a place, and it is for contracts you do not own — a partner API, or a schema published by another team — where the schema is an artifact you receive rather than a model you maintain.
Key points
- One model validation replaces a dozen field-by-field assertions and names the failing field
- Declare the suite's own models; importing the server's makes renames invisible to your tests
- Forbidding unknown fields turns undocumented API drift into a visible change
Code
class Strict(BaseModel):
"""Unknown fields are an error; instances cannot be mutated."""
model_config = ConfigDict(extra="forbid", frozen=True)
class Cart(Strict):
items: list[CartLine]
total: float
currency: str
# One line checks types, required fields, ranges and the absence of surprises.
cart = Cart.model_validate(response.json())
# For a contract you do NOT own, validate against the schema you were given:
PRODUCT_SCHEMA = {
"type": "object",
"required": ["id", "name", "price", "in_stock"],
"additionalProperties": False,
"properties": {
"category": {"type": "string", "enum": ["audio", "input", "display", "video"]},
"rating": {"type": "number", "minimum": 0, "maximum": 5},
},
}Models for what you maintain, JSON Schema for what you receive from somebody else.
See it in the framework
- Implementation · Response models:
framework/api/models.py— live · reviewed - Used by · Drift/contract tests:
tests/services/test_contract_and_properties.py— live · reviewed
Reviewed against commit f9ada16 (2026-08-14).
Common pitfalls
- Importing the application's own models, so any rename propagates and no test ever notices
- Leaving models permissive, which lets a response grow undocumented fields for months unnoticed
Practice exercise
Add a strict model for one API response in a suite you work with, then add a field to the server's response and confirm the test fails. Decide whether forbidding extra fields is right for that API and write down why.
A repeatable API test-design checklist
Happy path, boundaries, malformed input, the authorization matrix, idempotence, consistency and isolation.
Working through a fixed checklist for each endpoint takes about ten minutes and is far more systematic than anybody's intuition. Start with the documented happy path, then boundaries chosen by boundary-value analysis. Then malformed input: empty body, missing required fields, wrong types, oversized values, wrong content type. Every one of those must return a client error, because a server error on bad input means the input reached code that did not expect it, which is the shape of bug that becomes a security finding later. Next comes the authorization matrix — anonymous, wrong user, right user, administrator, against reading and modifying both your own and another user's resource. The cells covering another user's resource are broken object-level authorization, the top risk in the OWASP API list and a three-line test. Finish with idempotence, cross-endpoint consistency between a collection and its detail endpoint, and isolation proving two users cannot see each other's data.
Key points
- A server error on malformed input is always a bug, never an acceptable outcome
- The authorization matrix cell for another user's resource is BOLA — the top OWASP API risk
- Check idempotence, cross-endpoint consistency and two-user isolation on every resource
Code
# Authorization matrix. The bold cells are BOLA and are worth writing first.
#
# Anonymous Wrong user Owner Admin
# Read own 401 403/404 200 200
# Read other's 401 **403/404** 403/404 200
# Modify other's 401 **403/404** 403/404 200
def test_order_belongs_to_its_owner(cart_with_item, shop_as_second_user):
shop, _ = cart_with_item
order = shop.orders.create()
response = shop_as_second_user.client.get(f"/api/orders/{order.id}")
assert response.status_code in (403, 404), (
f"Another user read order {order.id} - broken object-level authorization"
)
@pytest.mark.parametrize("payload", [{}, {"username": "a"}, {"username": 12345}])
def test_malformed_login_never_returns_a_server_error(shop, payload):
response = shop.client.post("/api/auth/login", json=payload)
assert 400 <= response.status_code < 500Three lines find the most commonly exploited API vulnerability; write them for every resource-by-id endpoint.
See it in the framework
- Used by · Auth test design:
tests/services/test_auth.py— live · reviewed - Used by · Cart flow test design:
tests/services/test_cart_flow.py— live · reviewed - Used by · Product test design:
tests/services/test_products.py— live · reviewed
Reviewed against commit f9ada16 (2026-08-14).
Common pitfalls
- Testing only the happy path plus a single wrong-password case, and calling the endpoint covered
- Accepting a 500 on malformed input because the request was invalid anyway — that is the defect, not an excuse
Practice exercise
Apply the full checklist to one endpoint you own. Count how many tests you end up with, and how many of them fail — the malformed-input and authorization rows find defects surprisingly often.