AUTOMATION FRAMEWORKS

API Tests That Catch Missing Fields Before Prod Does

Missing fields are one of the quietest kinds of API breakage. The response comes back 200, the status assertion passes, the suite goes green, and somewhere in the payload a field your frontend or a downstream service depends on has disappeared. No exception, no error log, just a blank element in the UI or a null that blows up later. The test never asked the right question.

Most suites I see start by asserting status codes, then add a value or two someone cared about at the time. What gets skipped is the structural contract: is every field the consumer expects actually there? That's a different assertion from checking a value, and it needs to be explicit.

It matters more now that coding agents do a lot of refactoring. An agent asked to "clean up the user serializer" can drop a field without noticing who reads it, and an agent asked to write tests will usually check the fields it happens to see. In this article I'll show the field-presence helpers I use with pytest and Behave, how I keep the contract in one place, and how that contract becomes guidance for agents rather than something they guess at.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

Why status-code tests let missing fields through

Here's the starting point in a lot of suites:

def test_get_user_returns_200(client, api_base_url):
    response = client.get(f"{api_base_url}/users/42", timeout=10)
    assert response.status_code == 200

That passes if the body is {}. It passes if account_status, the field your billing logic reads, vanished in a refactor. Adding assert data["email"] == "test@example.com" helps a little, but only for that one field. What you need is an assertion on the shape: every required key present, whatever its value.

A field-presence helper that handles nesting and nulls

Flat key checks miss the field one level down, so I use dot-notation paths. One detail matters: "missing" and "present but null" are different contract violations, and the helper shouldn't confuse them. Many quick versions return None for a missing path, which makes a legitimately nullable field look absent.

_MISSING = object()


def get_path(payload, path: str):
    """Follow 'address.postal_code'; return _MISSING if any key is absent."""
    current = payload
    for key in path.split("."):
        if not isinstance(current, dict) or key not in current:
            return _MISSING
        current = current[key]
    return current


def assert_fields(payload: dict, required: list[str], non_null: list[str] = ()):
    missing = [p for p in required if get_path(payload, p) is _MISSING]
    assert not missing, f"Response is missing required fields: {missing}"
    nulls = [p for p in non_null if get_path(payload, p) is None]
    assert not nulls, f"Fields must not be null: {nulls}"

The failure message names every missing path at once, so the person reading CI output knows exactly what broke. For arrays, check every item, not just the first. An API can return a perfect first element and drop fields further down:

def assert_fields_on_all_items(items: list, required: list[str]):
    for i, item in enumerate(items):
        missing = [p for p in required if get_path(item, p) is _MISSING]
        assert not missing, f"Item {i} is missing fields: {missing}"

Keep the contract in one module

I keep required fields per endpoint in a contracts.py module. Tests stay short, and the contract lives in one place that's easy to review:

# tests/contracts.py
USER_REQUIRED = [
    "id", "email", "role", "created_at", "account_status",
    "address.street", "address.postal_code",
    "subscription.tier", "subscription.expires_at",
]
USER_NON_NULL = ["id", "email", "account_status"]

# tests/api/test_users.py
import pytest
from contracts import USER_REQUIRED, USER_NON_NULL
from helpers import assert_fields


@pytest.mark.contract
def test_get_user_contract(client, api_base_url):
    response = client.get(f"{api_base_url}/users/42", timeout=10)
    assert response.status_code == 200
    assert_fields(response.json(), USER_REQUIRED, USER_NON_NULL)

Register the contract marker in pytest.ini so CI can select these tests with pytest -m contract.

In Behave, the field list belongs in the step, not the feature file. The scenario states the business intent; the step enforces the structure:

@contract
Scenario: User profile includes all required fields
  Given I am authenticated as a standard user
  When I request the profile for user 42
  Then the user response includes all required profile fields
# features/steps/user_steps.py
from behave import then
from contracts import USER_REQUIRED, USER_NON_NULL
from helpers import assert_fields


@then("the user response includes all required profile fields")
def step_user_required_fields(context):
    assert_fields(context.response.json(), USER_REQUIRED, USER_NON_NULL)

A non-engineer can read that scenario and know what it protects. That's the same idea behind API tests that document business rules.

Where the list comes from matters

A required-field list goes stale if nobody owns it. I tie its review to API changes: when the OpenAPI spec or changelog changes, the contracts module gets reviewed in the same PR. Generating the list from the spec is a good option if the spec is reliable.

Watch for fields that are optional in the spec but every consumer treats as always present. The spec says optional, so nobody tests for it, and then a client breaks when it's gone. If consumers depend on a field, test for it. The spec documents intent; the contract module documents what consumers actually rely on.

That's also where agents go wrong. Ask a coding agent to write contract tests and it will often call the endpoint and list whatever keys came back. If a field is already missing, it's missing from your contract too. I ask agents to build the list from the spec or the ticket, and I review it against what consumers read, not against the current response.

Making the contract work for agents

Once the contract is a module, it's useful context for agents, not just a test fixture. A few rules in .github/copilot-instructions.md, or whatever instructions file your agent reads, go a long way:

## Response contracts
- Required response fields live in tests/contracts.py. Treat them as the API contract.
- When changing a serializer or response model, run: pytest -m contract
- Never remove a field from tests/contracts.py to make a test pass.
  If a field should go, say so in the PR description so a human can decide.

The last rule is the important one. When an agent's refactor drops a field and the contract test fails, the path of least resistance is to delete the field from the list. That turns a caught bug into a silent one. I also put tests/contracts.py under CODEOWNERS so every change to it gets a human reviewer.

The same helper is useful if your product depends on model output. Structured output and agent tool calls drop required keys more often than a typical API does, and the failures are intermittent. Run assert_fields over a fixed set of prompts and track how many outputs pass, rather than trusting one green run. The application should reject an incomplete tool call too, but the test tells you how often it happens.

Run it everywhere the field could disappear

Field-presence tests earn their keep when they run on every merge to main and against every environment you deploy to. A field present in staging but missing in production because of a feature flag or a data migration is exactly what bites teams who only test in one place. I cover stage placement in where API tests belong in a CI/CD pipeline.

A failing contract test also forces a useful conversation. When someone, or some agent, proposes removing a field, the test makes it a deliberate decision: who depends on this, and what's the migration plan? If you'd like to build this kind of suite with pytest or Behave, VS Code and GitHub Copilot, my API testing courses cover it from the ground up.