AUTOMATION FRAMEWORKS

API Tests That Catch Data Type Mismatches Early, With AI

Data type mismatches are one of the sneakiest failures in API work. The endpoint returns 200, the field is present, the happy-path test is green, and the value is the string "42" instead of the integer 42. Downstream, a calculation goes wrong or a conditional never fires, and by the time anyone notices, nobody remembers which deploy changed it.

I treat type assertions as part of the core test, not something to bolt on later. They sit next to status-code and business-rule checks because they're the first defence against contract drift. In a Python suite with pytest or Behave, they're easy to add once you have a consistent pattern.

There are two newer reasons this matters. Coding agents now write a lot of these tests, and they have a habit of loosening a type check to make a red build green. And if your product calls a model, the JSON it produces for tool calls or structured output is exactly where types drift. In this article I'll cover the assertion patterns, schema-level validation, a reusable Behave step, and how I keep both agents and LLM output honest about types.

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 isinstance() beats a truthy check

The most common weak assertion I see is this:

assert response.json()["user_id"]

That passes for 42, "42", "abc" and a non-empty list. It tells you the value is truthy, nothing more. When the API team changes user_id from an integer to a string, the test stays green and the bug ships. A direct type check with a useful message fixes that:

def assert_field_type(data: dict, field: str, expected: type | tuple) -> None:
    assert field in data, f"Field '{field}' missing from response"
    value = data[field]
    # bool is a subclass of int in Python, so reject it explicitly
    if expected in (int, float, (int, float)) and isinstance(value, bool):
        raise AssertionError(f"'{field}': expected number, got bool ({value!r})")
    assert isinstance(value, expected), (
        f"'{field}': expected {expected}, got {type(value).__name__} ({value!r})"
    )


def test_user_field_types(api_client, api_base_url):
    data = api_client.get(f"{api_base_url}/users/1", timeout=10).json()
    assert_field_type(data, "user_id", int)
    assert_field_type(data, "email", str)
    assert_field_type(data, "is_active", bool)
    assert_field_type(data, "score", (int, float))

The traps worth knowing:

  • bool vs int. isinstance(True, int) is True in Python. If a number field starts arriving as true, a plain int check won't notice. The helper above guards against it.
  • int vs float. JSON has one number type. Python's json module returns 10 as int and 10.5 as float, so asserting float on a price fails whenever the price is a whole number. Accept (int, float) unless the contract really says otherwise.
  • Nulls. Decide up front whether null is valid, then write it down: assert value is None or isinstance(value, str).
  • Strings by design. Some APIs send money or IDs as strings deliberately. That's fine as an explicit contract. Assert the string type; don't accept either.

Schema-level validation with jsonschema

Field-by-field checks are fine for small responses. Once you have nested objects and arrays, validate the whole body against a schema:

import jsonschema

USER_SCHEMA = {
    "type": "object",
    "required": ["user_id", "email", "is_active", "score"],
    "properties": {
        "user_id": {"type": "integer"},
        "email": {"type": "string"},
        "is_active": {"type": "boolean"},
        "score": {"type": "number"},
        "tags": {"type": "array", "items": {"type": "string"}},
    },
    "additionalProperties": False,
}


def test_get_user_matches_schema(api_client, api_base_url):
    response = api_client.get(f"{api_base_url}/users/1", timeout=10)
    assert response.status_code == 200
    jsonschema.validate(instance=response.json(), schema=USER_SCHEMA)

JSON Schema gets the edge cases right for you: "integer" rejects booleans and accepts 10.0, and "number" accepts both ints and floats. On failure, jsonschema.validate() raises a ValidationError that names the offending field, which is far more useful in a CI log than a bare assertion. additionalProperties: False is optional; use it when you want to know the moment a field appears that nobody told you about. I cover the wider approach in validating API response schemas automatically.

pydantic in strict mode

If your team already uses pydantic, you can reuse its models in tests. The catch is that pydantic coerces by default: lax mode will turn "42" into 42 and hide exactly the bug you're looking for. In a test, I want strict mode:

from pydantic import BaseModel, ConfigDict


class UserResponse(BaseModel):
    model_config = ConfigDict(strict=True)

    user_id: int
    email: str
    is_active: bool
    score: float
    tags: list[str] = []


def test_user_parses_strictly(api_client, api_base_url):
    body = api_client.get(f"{api_base_url}/users/1", timeout=10).json()
    UserResponse.model_validate(body)  # raises ValidationError on a type mismatch

That's pydantic v2 syntax. In strict mode a float field still accepts an int, which matches JSON, but a string for an int field fails. Keep these models or schema dicts in a tests/schemas/ folder rather than inline in tests, so one change covers the whole suite. If you have an OpenAPI spec, generating them from it is even better, because then the test schema comes from the source of truth instead of someone's memory.

A reusable Behave step for types

In Behave, the scenario makes the contract visible and the step does the precise check:

Scenario: User profile fields have the documented types
  When I request the profile for user 1
  Then the response status is 200
  And the "user_id" field is of type integer
  And the "is_active" field is of type boolean
  And the "score" field is of type number
# features/steps/type_steps.py
from behave import then

TYPES = {"integer": int, "string": str, "boolean": bool, "number": (int, float)}


@then('the "{field}" field is of type {type_name}')
def step_field_type(context, field, type_name):
    expected = TYPES[type_name]
    data = context.response.json()
    assert field in data, f"'{field}' missing from response"
    value = data[field]
    if type_name in ("integer", "number"):
        assert not isinstance(value, bool), f"'{field}': got bool ({value!r})"
    assert isinstance(value, expected), (
        f"'{field}': expected {type_name}, got {type(value).__name__} ({value!r})"
    )

I word the step "is of type integer" on purpose. A step written as is a {type_name} won't match "is an integer", which is the natural English, and you end up with undefined steps or awkward grammar. Write one step that reads well for every type and reuse it everywhere.

Where agents come in

Two things change once agents are involved.

Agents writing the tests. Ask a coding agent to "add schema tests for /users" and it will often call the endpoint and build the schema from whatever came back. If the API is already returning "42", that bug is now the contract. I ask for schemas derived from the OpenAPI spec or the ticket, never from a live response. The other habit to watch is the "fix": a type test fails, and the agent widens int to int | str or drops strict mode. I put a rule in .github/copilot-instructions.md (or the agent's equivalent file): never loosen a schema or type assertion to make a test pass; report the mismatch instead. Then I check diffs to tests/schemas/ by hand.

Testing agents and LLM features. If your product asks a model for structured output, or an agent calls your API through tools, the arguments it produces are untrusted input. Models are especially prone to quoting numbers and returning "true" as a string. The same strict validation applies, run over many outputs rather than one:

from pydantic import ValidationError


def test_tool_call_arguments_are_typed(generate_tool_call, eval_prompts):
    failures = []
    for prompt in eval_prompts:
        args = generate_tool_call(prompt)  # dict parsed from the model's tool call
        try:
            CreateOrderArgs.model_validate(args)  # strict pydantic model
        except ValidationError as exc:
            failures.append((prompt, str(exc)))
    assert not failures, failures

Here generate_tool_call is an injected fixture, so the test doesn't depend on a particular vendor SDK, and CreateOrderArgs is a strict model for the tool's arguments. For a model-calling test, I usually track the pass rate over a fixed prompt set rather than expecting perfection on one run, but the validation itself stays strict. The same check belongs in the application, which should reject a badly typed tool call before it reaches the API.

Keep the contract from quietly disappearing

The way this breaks in practice is human, not technical. The API changes, someone updates the application model, nobody updates the test schema, the test fails, and someone loosens it to get the build through. Make schema updates part of the API change checklist, and run type checks where they'll be seen, as I describe in where API tests belong in a CI/CD pipeline.

Type bugs are boring, which is exactly why they ship. A few deliberate assertions, a shared schema and a rule that nobody, human or agent, weakens them without review is all it takes. My API testing courses build these patterns into a full pytest or Behave suite with VS Code and GitHub Copilot.