Testing API Responses That Embed Errors Inside a 200
HTTP status codes are supposed to tell you what happened. A 200 means success, a 400 means you did something wrong, a 500 means the server did. That's the contract. But in practice, plenty of APIs break that contract quietly — they return a 200 with a body that says something like {"status": "error", "message": "User not found"}. Your HTTP client sees a 200 and moves on. Your test passes. The operation failed.
This pattern shows up more often than you'd expect. It's common in older SOAP-based services, in some GraphQL implementations, in payment and third-party integration APIs, and in homegrown REST APIs that conflate "the request was received" with "the request succeeded." If your test suite only checks status codes, it will miss every one of these failures — and so will your monitoring. I've seen teams spend hours debugging a production incident only to find their tests had been asserting a 200 and ignoring a body-level error field for months.
In this article I'll walk through how to recognize this pattern, how to write assertions that actually catch it, and how to structure your test suite so these checks don't become an afterthought. The examples use Python with requests and pytest, but the concepts apply regardless of your tooling.
Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.
Why APIs Return Errors Inside a 200 and How to Spot the Pattern
Before you can test for this pattern, you need to recognize it. There are a few common shapes it takes in the wild.
The most obvious is an explicit error envelope — the API always returns the same top-level structure, and you have to read a field like success, status, or code to know whether the operation actually worked:
# A "success" response
{"success": true, "data": {"id": 42, "name": "Alice"}}
# A "failure" response — still a 200
{"success": false, "error": "Invalid account state", "code": "ACCOUNT_LOCKED"}
A subtler variant is the partial-failure response, common in batch or bulk endpoints. You send ten records, the API processes eight, and it returns a 200 with a body that includes both a results array and an errors array. The HTTP layer looks fine. The business logic is not.
GraphQL is a well-known case of this by design. A GraphQL response always returns 200 (in most implementations) and puts any execution errors in a top-level errors key alongside whatever partial data was resolved. If you only assert that the HTTP status is 200 and that data is non-null, you'll miss resolver errors entirely.
The root cause is usually one of two things: either the API was designed around a "transport success vs. business logic success" split (intentional, if inconsistent), or the error handling was bolted on after the fact and nobody updated the status code behavior. Either way, when status codes lie, the burden falls on your test suite to look deeper.
The first step in your test strategy is to read the API documentation — or, if there isn't any, to probe the API manually and map out every field that could signal a failure state. Build that list before you write a single assertion.
Writing Assertions That Reach Past the Status Code Into the Body
Once you know which fields carry error signals, the fix is straightforward: assert on them explicitly. The mistake most teams make is stopping at assert response.status_code == 200. That check is necessary but not sufficient.
Here's a minimal pytest example for an API that uses a success boolean envelope:
import requests
import pytest
BASE_URL = "https://api.example.com"
def test_create_order_succeeds():
payload = {"item_id": 99, "quantity": 2}
response = requests.post(f"{BASE_URL}/orders", json=payload)
assert response.status_code == 200
body = response.json()
assert body["success"] is True, f"API returned error: {body.get('error')}"
assert "data" in body
assert body["data"]["order_id"] is not None
That assertion message matters. When the test fails in CI, you want the log to immediately show the error message the API returned, not just "AssertionError." Embedding body.get('error') in the message gives you that for free.
For GraphQL, the pattern is slightly different because errors can coexist with partial data:
def test_graphql_query_has_no_errors():
query = {"query": "{ user(id: 999) { name email } }"}
response = requests.post(f"{BASE_URL}/graphql", json=query)
assert response.status_code == 200
body = response.json()
assert "errors" not in body, f"GraphQL errors: {body.get('errors')}"
assert body.get("data") is not None
For batch endpoints with partial failures, decide upfront what your acceptance criteria actually is. Should zero errors be tolerated? Is one error in a hundred acceptable? Make that explicit in your assertion rather than leaving it implicit:
def test_bulk_import_has_no_errors():
response = requests.post(f"{BASE_URL}/bulk/import", json={"records": records})
body = response.json()
errors = body.get("errors", [])
assert len(errors) == 0, f"Bulk import had {len(errors)} errors: {errors[:3]}"
A pattern that scales well is a small helper function that centralizes this logic so every test in your suite benefits from it without repeating the same checks. Something like:
def assert_api_success(response):
assert response.status_code == 200
body = response.json()
assert body.get("success") is not False, f"API error: {body.get('error')}"
assert "errors" not in body or body["errors"] == [], f"Errors: {body['errors']}"
return body
This approach is especially valuable when you're working across responses that change shape by user role — the envelope structure may stay consistent even when the payload inside it varies, so your helper can handle the envelope while individual tests handle the payload.
Structuring Your Test Suite to Treat Body-Level Errors as First-Class Failures
Writing individual assertions is step one. The harder problem is making sure this discipline holds across the whole suite as it grows. A few structural habits make a real difference here.
Document the error contract in your test file, not just in your head. Add a comment or docstring near the top of each test module that describes what error fields this API uses and what values signal failure. Future maintainers — including you in six months — will thank you. This is especially important for third-party APIs where the documentation may be sparse or change without notice.
Test the error path directly, not just the happy path. If an API embeds errors in a 200, you should have explicit test cases that trigger those errors and assert on the error fields. This serves two purposes: it confirms your assertions actually fire when they should, and it documents the error contract as executable code. If you've only ever seen the "success": true path in your tests, you don't actually know your assertions work. This connects directly to the broader practice of testing error responses beyond the happy path — the same mindset applies whether the error arrives via a 4xx status code or buried inside a 200 body.
Use fixtures or parametrize to cover multiple error scenarios without duplicating setup code. Here's a quick parametrize example for an API that returns different embedded error codes:
@pytest.mark.parametrize("payload,expected_error_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(payload, expected_error_code):
response = requests.post(f"{BASE_URL}/orders", json=payload)
assert response.status_code == 200
body = response.json()
assert body["success"] is False
assert body["code"] == expected_error_code
Include these checks in your CI pipeline, not just local runs. A body-level error assertion that only runs when someone remembers to execute it locally isn't a safety net — it's a suggestion. Wire these tests into your pipeline the same way you would any other integration test.
Finally, keep an eye out for APIs that mix the patterns. I've worked with services that return proper 4xx codes for some errors and embed others in a 200 depending on which endpoint you're hitting. This is messy, but it happens. When you're building out real-world API test coverage, mapping this inconsistency explicitly — and testing both paths — is part of what separates a suite that catches real bugs from one that just confirms the happy path works.
The core principle is simple: your tests should reflect what "success" actually means for the operation, not just what the HTTP layer reports. If the API can lie to you with a 200, your assertions need to be smarter than the status code.