Catching Silent API Failures When Status Codes Lie
A 200 OK is not a passing test. I've seen suites stay green while a feature was broken, because every test checked the status code and moved on. Meanwhile the body said {"error": "user not found"}, or the list that should have held results came back empty, or a write was accepted and never persisted. The status code was a starting point, and the tests treated it as a verdict.
These silent failures matter in two ways now. First, AI assistants writing API tests tend to produce exactly this kind of status-only assertion unless you tell them otherwise. Second, more APIs are being called by agents as tools. A human developer might notice something odd in a response. An agent that gets a 200 with an error tucked inside will usually carry on as if the call worked, and build its next step on a result that never happened.
Here's why APIs return success codes when they've failed, how I write body-level assertions that expose the real outcome, and how to make silent-failure detection the default in a framework rather than something each test remembers.
Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.
Why APIs return 200 when something went wrong
It's rarely malice and usually design. The patterns I run into most:
- Error envelopes. Every response is a 200 and the outcome lives in a field like
success,statusorerrors. GraphQL works this way by design: errors arrive in anerrorsarray, frequently alongside a 200. - Partial success. A batch endpoint processes some items and rejects others, and returns 200 because "the request" succeeded.
- Swallowed exceptions. A handler catches an error, logs it, and returns an empty result instead of failing.
- Async acceptance. A 202 or 200 means "received", not "done". The work can fail later where the client never sees it.
- Gateways and proxies. An upstream failure is wrapped into a friendly 200 page or default payload.
Whatever the cause, the test needs to check what the client actually cares about: did the thing happen? I go through the envelope case in detail in testing API responses that embed errors inside a 200, and the meaning of the codes themselves in REST API status codes: what they actually mean.
Building body-level assertions that expose the real outcome
I think about three levels of assertion. Status says the transport worked. Shape says the response is the kind of thing you expected. Outcome says the business result is right. Silent failures pass the first and sometimes the second, so the third is what catches them.
def test_create_user_actually_creates_user(api, unique_email):
response = api.post("/users", json={"email": unique_email, "name": "Test User"})
# Status: the transport worked
assert response.status_code == 201, response.text
body = response.json()
# Shape: no error envelope, and the fields we need exist
assert not body.get("errors"), body
assert isinstance(body.get("id"), int), body
# Outcome: the user exists and has what we sent
fetched = api.get(f"/users/{body['id']}")
assert fetched.status_code == 200, fetched.text
assert fetched.json()["email"] == unique_email
The follow-up read is the part people skip. It's the only thing in this test that proves the write persisted rather than just being acknowledged.
Empty results deserve the same suspicion. A search that returns [] with a 200 is a valid response, and also exactly what a broken query looks like. If the test controls the data, assert on what should be there:
def test_search_finds_seeded_product(api, seeded_product):
response = api.get("/products", params={"q": seeded_product["name"]})
assert response.status_code == 200
ids = [p["id"] for p in response.json()["items"]]
assert seeded_product["id"] in ids, f"seeded product missing from {ids}"
For batch endpoints, check per-item results rather than the overall status, and assert the count of failed items is what you expect, usually zero.
Making silent-failure detection the default
Relying on every test author to remember all this doesn't scale, especially when some of those authors are coding agents. I move the checks into the API client so they happen on every call:
import requests
class SilentFailure(AssertionError):
pass
class ApiClient:
def __init__(self, base_url, headers, timeout=10):
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update(headers)
self.timeout = timeout
def request(self, method, path, expect_error=False, **kwargs):
response = self.session.request(
method, f"{self.base_url}{path}", timeout=self.timeout, **kwargs
)
if not expect_error and response.ok:
self._check_envelope(response)
return response
def _check_envelope(self, response):
if "application/json" not in response.headers.get("Content-Type", ""):
return
body = response.json()
if isinstance(body, dict):
if body.get("errors") or body.get("success") is False or "error" in body:
raise SilentFailure(
f"{response.request.method} {response.url} returned "
f"{response.status_code} with an error body: {body}"
)
def get(self, path, **kwargs):
return self.request("GET", path, **kwargs)
def post(self, path, **kwargs):
return self.request("POST", path, **kwargs)
Adjust _check_envelope to your API's actual error conventions. The expect_error flag lets negative tests opt out explicitly, which makes those tests easier to spot in review.
Then tell your assistant the rule. In .github/copilot-instructions.md or your agent's equivalent file:
## API assertions
- Never assert on status_code alone. Every test must also check the body
for the business outcome.
- After any write, read the resource back and assert on the stored values.
- Use tests/api_client.py; do not bypass it with raw requests calls.
That one rule changes a lot of what gets generated. Without it, status-only tests are what I see most often from assistants.
When the caller is an agent, not a test
If an agent uses your API through an MCP server or a function-calling tool, a silent failure becomes a correctness problem in the agent's behaviour. The agent reads the 200, reports "done" to the user, and moves on. So I test the tool layer for it directly:
- The tool wrapper must turn error bodies into errors. Feed it a 200 with an error envelope and assert that it returns a failure the agent can see, not a success.
- Empty results should be explicit. "No orders found for this customer" is far more useful to a model than
[], and it's testable. - Check the agent's next step. In an end-to-end agent test, stub the API to return a silent failure and assert the agent doesn't claim success. Run it several times, because the agent's output varies, and track how often it gets it right rather than relying on one pass.
The underlying principle is the same for tests and agents: never let the status code stand in for the outcome. Assert on the body, confirm writes with a read, and make the client refuse to treat an error envelope as success. Checking for missing fields is the natural next step, covered in writing API tests that catch missing fields before prod does. And if you want to build a client and suite like this from the ground up, that's what my API testing courses do, in Python with Behave or Node with Cucumber.