API TESTING

Testing API Responses That Embed Errors Inside a 200

Status codes are supposed to tell you what happened. But plenty of APIs return a 200 with a body like {"status": "error", "message": "User not found"}. The HTTP client sees a 200 and moves on. The test passes. The operation failed.

The pattern is common in older services, in GraphQL, in bulk endpoints, in payment and third-party integrations, and in homegrown APIs that treat "request received" as "request succeeded." It has also become a problem for two new kinds of code. AI assistants writing tests copy the status-code-only assertion they've seen in a thousand examples, so the generated test happily asserts 200 on a failed operation. And when an LLM agent calls one of these APIs as a tool, a wrapper that only checks the status code hands the error body to the model as if it were data. The agent then reasons confidently about a result that never happened.

In this article I'll cover how to recognise the pattern, how to assert past the status code, how to centralise those checks so they don't get forgotten, and how to test agent tool wrappers so an embedded error reaches the model as an error. Examples use Python with requests and pytest.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

Recognising the pattern

It shows up in a few recurring shapes. The most obvious is an envelope where a field tells you whether the operation worked:

# success
{"success": true, "data": {"id": 42, "name": "Alice"}}

# failure, still HTTP 200
{"success": false, "error": "Invalid account state", "code": "ACCOUNT_LOCKED"}

A subtler variant is partial failure in batch endpoints: you send ten records, eight succeed, and the 200 response carries both a results array and an errors array.

GraphQL is the well-known case. Many GraphQL servers return 200 for any request they could parse and execute, putting resolver failures in a top-level errors array next to whatever partial data resolved. Some newer servers following the GraphQL-over-HTTP conventions use non-200 codes for certain failures, so check how yours behaves rather than assuming. Either way, asserting only on status and a non-null data misses resolver errors.

Before writing assertions, list every field that can signal failure for the API you're testing: from the docs if they exist, by probing it if they don't. That list is the error contract. It's the same problem I describe in catching silent API failures when status codes lie.

Assertions that reach into the body

Once you know where errors live, assert on them explicitly. For a success envelope:

def test_create_order_succeeds(api):
    response = api.post("/orders", json={"item_id": 99, "quantity": 2})
    assert response.status_code == 200

    body = response.json()
    assert body["success"] is True, f"API reported an error: {body.get('code')} {body.get('error')}"
    assert body["data"]["order_id"]

The assertion message matters. When this fails in CI you want the log to show the API's own error code and message, not a bare AssertionError.

For GraphQL, check the errors array as well as the data:

def test_user_query_has_no_errors(api):
    response = api.post("/graphql", json={"query": "{ user(id: 42) { name email } }"})
    assert response.status_code == 200

    body = response.json()
    assert not body.get("errors"), f"GraphQL errors: {body.get('errors')}"
    assert body["data"]["user"] is not None

For batch endpoints, decide the acceptance rule up front and make it explicit:

def test_bulk_import_has_no_record_errors(api, valid_records):
    body = api.post("/bulk/import", json={"records": valid_records}).json()
    errors = body.get("errors", [])
    assert errors == [], f"{len(errors)} record errors, first few: {errors[:3]}"
    assert len(body["results"]) == len(valid_records)

Centralise the check so nobody forgets it

Individual assertions are step one. The harder problem is keeping the discipline as the suite grows, especially when part of it is written by an assistant. A small helper makes the right check the easy check:

def assert_api_success(response) -> dict:
    assert response.status_code == 200, f"HTTP {response.status_code}: {response.text[:300]}"
    body = response.json()
    assert body.get("success") is not False, f"API error {body.get('code')}: {body.get('error')}"
    assert not body.get("errors"), f"Embedded errors: {body.get('errors')}"
    return body

Tests call body = assert_api_success(response) and then assert on the payload. Because the envelope check lives in one place, it covers every endpoint, including the ones where the payload shape varies by role.

Then test the error path on purpose. If you've only ever seen "success": true in your tests, you don't know your assertions work. Parametrise the documented failure codes:

import pytest


@pytest.mark.parametrize("payload, expected_code", [
    ({"item_id": -1, "quantity": 1}, "INVALID_ITEM"),
    ({"item_id": 99, "quantity": 0}, "INVALID_QUANTITY"),
    ({"item_id": 99, "quantity": 9999}, "EXCEEDS_STOCK"),
])
def test_create_order_embedded_errors(api, payload, expected_code):
    response = api.post("/orders", json=payload)
    assert response.status_code == 200  # documented API behaviour, not our choice
    body = response.json()
    assert body["success"] is False
    assert body["code"] == expected_code

These cases are the executable version of the error contract, and they belong in CI next to everything else. The same mindset applies whether an error arrives as a 4xx or inside a 200, which is why I'd read this alongside testing API error responses beyond the happy path.

Agent tool wrappers: don't hand an error to the model as data

This is where the pattern becomes an agentic quality problem. Say your product has an assistant with a place_order tool that calls the orders API. If the wrapper does response.raise_for_status() and returns response.json(), a locked account comes back as an ordinary result. The model receives {"success": false, ...} as tool output and may well tell the user their order is placed, because nothing marked it as a failure.

The fix is to translate the envelope at the tool boundary, and to test that translation without any model involved:

class ToolError(Exception):
    """Raised so the agent framework reports a failed tool call to the model."""


def place_order(api, item_id: int, quantity: int) -> dict:
    response = api.post("/orders", json={"item_id": item_id, "quantity": quantity})
    body = response.json()
    if response.status_code != 200 or body.get("success") is False or body.get("errors"):
        raise ToolError(f"{body.get('code', response.status_code)}: {body.get('error', 'request failed')}")
    return body["data"]


def test_place_order_surfaces_embedded_error(fake_api):
    fake_api.respond("/orders", 200, {"success": False, "code": "ACCOUNT_LOCKED",
                                      "error": "Invalid account state"})
    with pytest.raises(ToolError, match="ACCOUNT_LOCKED"):
        place_order(fake_api, item_id=99, quantity=2)

How a raised exception is reported back to the model depends on your agent framework, so check that part once by hand. The wrapper test itself is deterministic and runs on every pull request. On top of it I'd add an end-to-end check, run several times because model output varies, asserting that when the tool fails the assistant never claims the order succeeded.

Tell your coding agent about the envelope

The last piece is the instructions file. Copilot reads .github/copilot-instructions.md, and other agents have an equivalent. A few lines prevent most generated status-only tests:

## Orders and billing APIs
- These APIs return HTTP 200 for business failures. Success = body.success is true.
- Always use assert_api_success(response) for happy-path tests; never assert status alone.
- Error-path tests assert body.success is False and the documented body.code.
- Tool wrappers must raise ToolError on success == false; add a test for each wrapper.

Watch for APIs that mix both styles too: proper 4xx codes on some endpoints and embedded errors on others. Map the inconsistency explicitly and test both paths. More real-world patterns like this live in the real-world testing scenarios guide.

The principle is simple: your tests, and your agent's tools, should reflect what success means for the operation, not just what the HTTP layer reports. If you'd like to build that habit into a full suite with Behave or Cucumber and GitHub Copilot, that's what my API testing courses cover.