Validating API Response Schemas Automatically, for Agents Too
One of the most common gaps I see in API suites is tests that check the status code and a field or two, and never the shape of the response. The API returns 200, the test passes, and nobody notices a required field was renamed, an ID changed from integer to string, or a nested object disappeared. Those are contract breaks, and the clients consuming the API find them first.
Schema validation closes that gap. You describe the response contract once (required fields, types, allowed values) and every test that touches the endpoint checks against it. I've found it matters more, not less, now that coding agents write a lot of test code. An agent tends to assert on whatever the response contains today. A schema written from the spec gives every generated test a fixed contract to check, and the same tooling can validate the structured output of an LLM feature.
Here's how I define schemas with JSON Schema, wire them into pytest with the jsonschema library, keep them maintainable, and use them as guardrails for agent-written tests and model output.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Define the contract with JSON Schema
JSON Schema is the practical standard for describing a JSON response. It's plain JSON, readable in a diff, and the Python jsonschema library validates against it. A schema for a user resource:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "username", "email", "created_at"],
"properties": {
"id": {"type": "integer"},
"username": {"type": "string", "minLength": 1},
"email": {"type": "string", "format": "email"},
"created_at": {"type": "string", "format": "date-time"},
"role": {"type": "string", "enum": ["admin", "user", "guest"]}
},
"additionalProperties": false
}
required is the part that catches a dropped field. The type constraints catch the quiet change where an ID becomes a string and typed clients break. additionalProperties: false is a choice: it flags undocumented fields, which is useful for public contracts and noisy for internal APIs that add fields often.
One detail that trips people up: format is an annotation by default. The validator only enforces email or date-time if you pass a format checker, and some formats need extra packages installed. If you rely on format checks, test that a bad value actually fails.
I keep one file per resource in a schemas/ directory. They diff cleanly in pull requests, and the backend team can read them as documentation.
Wire it into pytest once
The goal is one helper that every test calls, with a failure message that names the field:
# tests/schema_check.py
import json
from functools import cache
from pathlib import Path
import pytest
from jsonschema import Draft202012Validator, FormatChecker
SCHEMA_DIR = Path(__file__).parent / "schemas"
@cache
def validator_for(name: str) -> Draft202012Validator:
schema = json.loads((SCHEMA_DIR / f"{name}.json").read_text())
return Draft202012Validator(schema, format_checker=FormatChecker())
def assert_matches_schema(data, name: str) -> None:
errors = sorted(validator_for(name).iter_errors(data), key=lambda e: list(e.path))
if errors:
lines = [f"{'/'.join(map(str, e.path)) or '(root)'}: {e.message}" for e in errors]
pytest.fail(f"Response does not match schema '{name}':\n" + "\n".join(lines))
Using iter_errors instead of validate reports every problem at once, so a response with three broken fields gives you three lines, not one failure at a time. A test then reads cleanly:
def test_get_user_matches_contract(api_client):
response = api_client.get("/users/1")
assert response.status_code == 200
assert_matches_schema(response.json(), "user")
For list endpoints, define the item once under $defs and reference it. References inside the same schema resolve without any extra setup:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["data", "total", "page"],
"properties": {
"data": {"type": "array", "items": {"$ref": "#/$defs/user"}},
"total": {"type": "integer", "minimum": 0},
"page": {"type": "integer", "minimum": 1}
},
"$defs": {
"user": {"type": "object", "required": ["id", "username"]}
}
}
For references across files, current versions of jsonschema use the referencing library through a registry. Older examples use RefResolver, which is deprecated, so don't copy those.
Keep schemas maintainable as the API changes
The usual objection is upkeep. But a schema test failing because a field changed type is the test doing its job. The aim is to make updates cheap:
- Use the OpenAPI spec as the source when one exists. Tools like Schemathesis generate and run tests from an OpenAPI document, and the spec's component schemas can be extracted for the helper above. One source of truth, not two copies drifting apart.
- Keep structure and business rules separate. A schema answers "is the shape right?" not "is this the right user?" Put value checks in their own assertions so a schema failure always means a structural problem.
- Validate error responses too. A 400 or 404 should match a predictable error schema. Inconsistent error formats break clients as often as broken success responses do. Testing API error responses beyond the happy path covers what to check.
Schemas are one layer of contract protection. For catching breaking changes between services before they deploy, API contract testing covers the next step up.
Schemas as guardrails for agent-written tests
When Copilot or another coding agent writes API tests, its most common shortcut is calling the API, looking at what came back and asserting on that. The test passes today because it describes today's behaviour, right or wrong. A schema written from the spec breaks that loop, because the expected shape comes from the contract, not the response.
I make it a rule in the repository instruction file, such as .github/copilot-instructions.md:
- Every test that reads a JSON response calls assert_matches_schema with the
schema for that endpoint. If no schema exists, stop and ask; do not write
one from a live response.
- Never edit files in tests/schemas/ to make a test pass.
The second line matters. An agent that can edit the schema to match a broken response has quietly moved the contract. Changes to schemas should be deliberate, human-reviewed changes, and you can enforce that with CODEOWNERS on the directory.
The same check for LLM output and tool calls
If your API includes an LLM feature that returns structured JSON (a classification, an extraction, a tool-call argument object), the same helper applies. Model output can't be pinned to exact values, but its shape can and should be fixed. Validate every response against a schema, and because the output varies between runs, run the check several times and report how often it passes:
def test_ticket_triage_output_matches_schema(api_client):
runs = 10
passed = 0
for _ in range(runs):
body = api_client.post("/triage", json={"text": SAMPLE_TICKET}).json()
if not list(validator_for("triage_result").iter_errors(body)):
passed += 1
assert passed == runs, f"{passed}/{runs} responses matched the triage schema"
For a structural contract I expect every run to pass. A malformed response from a model is a bug your client code will hit. The content inside that shape is where you need evaluation and pass-rate thresholds, which is a separate topic. Getting the shape fixed first removes a whole class of failures.
Schema validation feels like overhead until the first time it catches a breaking change before production. After that it's a default. If you want to build a full API suite with this kind of contract checking, and with Copilot writing tests inside those limits, that's what my API testing courses walk through.