Track: test automation in depth · Lesson 31 of 41 · 18 min

API test automation in depth: JSON Schema, auth, negative scenarios

How to write API tests that catch real defects: response schema validation, tokens and roles, IDOR, idempotency, a client wrapper.

From "status 200" to real checks

An API test that only checks the status misses most defects: a missing field, null instead of a number, a string instead of a date, someone else's data in the response. The API layer is the best place for automation: tests there are 10–50 times faster and more stable than UI tests (the test pyramid).

A client wrapper

class Api:
    def __init__(self, base_url, session):
        self.base, self.s = base_url, session

    def request(self, method, path, token=None, **kw):
        headers = kw.pop("headers", {})
        if token:
            headers["Authorization"] = f"Bearer {token}"
        r = self.s.request(method, self.base + path, headers=headers, timeout=10, **kw)
        r.elapsed_ms = r.elapsed.total_seconds() * 1000
        return r

    def post(self, path, **kw):
        return self.request("POST", path, **kw)

Timeout, base URL, token and logging live in one place. The tests stay short.

Schema validation

Validating a response against a JSON SchemaAPI response"id": 42"status": "paidd""total": "112.50""items": [ … ]"internalCost": 61Schema violationscreatedAt — required field missingstatus — not in the enumtotal — string instead of numberinternalCost — extra fieldstatus was 200 — a test without a schema passes
Validating a response against a JSON Schema. A schema catches what a status check misses: missing fields, wrong types, invalid values and leaked internal fields.
from jsonschema import validate

ORDER_SCHEMA = {
    "type": "object",
    "required": ["id", "status", "total", "items", "createdAt"],
    "properties": {
        "id": {"type": "integer"},
        "status": {"enum": ["new", "paid", "shipped", "cancelled"]},
        "total": {"type": "number", "minimum": 0},
        "items": {"type": "array", "minItems": 1},
        "createdAt": {"type": "string", "format": "date-time"},
    },
    "additionalProperties": False,
}

def test_order_schema(api, user, order):
    r = api.request("GET", f"/orders/{order['id']}", token=user.token)
    validate(r.json(), ORDER_SCHEMA)

additionalProperties: False also catches extra fields — say, accidentally exposed internal data. Schemas can often be generated from the OpenAPI spec — then the test also checks that the documentation tells the truth.

Authentication and roles

Scenario Expected
No token 401
Another user's token on someone else's resource 403 or 404
A "manager" role on an admin endpoint 403
An expired token 401, not 500
A token after logout 401
@pytest.mark.parametrize("who", ["anonymous", "other_user", "manager"])
def test_cannot_read_foreign_order(api, order, tokens, who):
    r = api.request("GET", f"/orders/{order['id']}", token=tokens.get(who))
    assert r.status_code in (401, 403, 404)
    assert "total" not in r.text          # no data leaked, even in the error body

This is an automated IDOR check from the OWASP lesson.

Idempotency and concurrency

def test_payment_idempotent(api, user, order):
    key = str(uuid4())
    r1 = api.post("/payments", json={"orderId": order["id"]}, token=user.token, headers={"Idempotency-Key": key})
    r2 = api.post("/payments", json={"orderId": order["id"]}, token=user.token, headers={"Idempotency-Key": key})
    assert r1.json()["paymentId"] == r2.json()["paymentId"]

For races, fire 10 identical requests in parallel (ThreadPoolExecutor) and check that exactly one resource was created. More on races in the API track: transactions and race conditions.

What else to automate

  • Pagination and sorting — properties of the list, not specific values.
  • Response time as a soft check (a warning, not a failure).
  • Contracts between services — Pact.

Key takeaways

  • JSON Schema validation catches missing, extra and wrongly typed fields.
  • Access control is a parametrized test across all roles, not one positive case.
  • Idempotency and races are checked with repeated and parallel requests.

Check yourself

  1. 1. What does additionalProperties: False in a schema do?

  2. 2. User A requests user B's order and gets 200 with the data. This is…

  3. 3. How do you test payment idempotency?

Practice: API testing in depth