Testing API Error Responses Beyond the Happy Path
The happy path is the easiest thing to test and the least interesting place for bugs to live. The failures I see teams miss usually come from error responses: a 400 that returns HTML instead of JSON, a 404 with an empty body, a 422 that names the wrong field, or a 500 that leaks a stack trace. These are the paths real clients hit when they mistype a field, send a stale token, or call a service that's partly down.
Two things have raised the stakes. First, AI assistants write a lot of API tests now, and their error-path tests tend to stop at assert response.status_code == 422. It looks like coverage and checks almost nothing. Second, more of your API's callers are agents. When an LLM-driven tool calls your endpoint and gets a validation error, the error body is the only thing it has to correct the request and try again. A vague or malformed error doesn't just annoy a developer; it sends an agent into a retry loop.
This article covers asserting on error bodies, systematically triggering every documented 4xx and 5xx, the error cases that don't fit a status code, and how I steer coding agents toward error tests that actually check something. Examples use Python with requests and pytest, but the patterns carry over to any stack.
Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.
Assert on the error body, not just the status code
The most common weak error test looks like this:
response = client.post("/users", json={"email": "not-an-email"})
assert response.status_code == 422
That proves the server didn't crash. It doesn't test the error response. A useful error tells the client what went wrong and where, so the test should verify exactly that:
def test_invalid_email_returns_validation_error(client):
response = client.post("/users", json={"email": "not-an-email"})
assert response.status_code == 422
content_type = response.headers.get("Content-Type", "")
assert "json" in content_type, f"Expected a JSON error body, got {content_type!r}"
body = response.json()
assert "errors" in body, "Error body must contain an 'errors' key"
assert any(e.get("field") == "email" for e in body["errors"]), \
"Validation error must reference the 'email' field"
assert all(e.get("message") for e in body["errors"]), \
"Every error entry needs a non-empty message"
Now the test pins the contract: the shape of the body, the field it blames, and a readable message. If a refactor renames field to field_name, this fails before anyone ships it.
Notice the Content-Type check uses "json" in content_type rather than an exact match. Many APIs use the standard problem-details format, which is served as application/problem+json, and a strict startswith("application/json") would reject a perfectly correct response. Match whatever your API documents. The check itself matters because reverse proxies and framework exception handlers love to return HTML error pages when the application falls over, and a status-only assertion never notices. That same failure mode is behind most of the cases in catching silent API failures when status codes lie.
Trigger every documented 4xx and 5xx
If your API has an OpenAPI spec, every documented error response is a test target. Here's how I trigger the common ones reliably:
- 400: malformed JSON, a missing required body, or the wrong top-level type (an array where an object is expected).
- 401: no Authorization header, an expired token, a token with a bad signature.
- 403: a valid user who lacks permission for this resource. You need fixtures for more than one role.
- 404: a well-formed ID that doesn't exist. Sending garbage may trigger a 400 instead and test the wrong thing.
- 409: create something that already exists, or update with a stale version.
- 422: valid JSON that breaks a business rule: a past date, a quantity below the minimum.
- 5xx: hard to trigger against a real service. Use a mocked dependency, a feature flag or fault injection in a test environment.
Parametrising keeps the cases readable and easy to extend:
import pytest
INVALID_PAYLOADS = [
pytest.param({}, id="empty_body"),
pytest.param({"email": 12345}, id="wrong_type_for_email"),
pytest.param({"email": None}, id="null_email"),
pytest.param([], id="array_instead_of_object"),
]
@pytest.mark.parametrize("payload", INVALID_PAYLOADS)
def test_post_user_rejects_invalid_body(client, payload):
response = client.post("/users", json=payload)
assert response.status_code in (400, 422), \
f"Expected 400 or 422, got {response.status_code} for {payload!r}"
assert "json" in response.headers.get("Content-Type", "")
assert response.json(), "Error body must not be empty"
The roles and token states these cases need are much easier to manage with good fixtures; pytest fixtures for API testing beyond the basics covers the patterns I use. And don't assume a 4xx means the error was handled gracefully. A 422 with an empty body, a 401 with a plain-text string, or a 404 that returns the home page are all bugs a status-only test will never catch.
Errors that don't fit a status code
Some of the most useful error tests check responses that are valid HTTP but wrong in substance.
Internal details leaking. A 500 that includes a database error, a traceback, or an internal hostname is a security problem, not just a bad message:
FORBIDDEN_FRAGMENTS = ["Traceback", "SQLException", "/var/app", "internal.local"]
def test_server_error_does_not_leak_internals(client, simulated_db_failure):
response = client.get("/orders/999")
assert response.status_code == 500
for fragment in FORBIDDEN_FRAGMENTS:
assert fragment not in response.text, f"Error body leaks {fragment!r}"
Rate limits without guidance. A 429 should tell clients when to try again. Retry-After can be either a number of seconds or an HTTP date, so don't blindly call int() on it:
from email.utils import parsedate_to_datetime
def assert_valid_retry_after(response):
value = response.headers.get("Retry-After")
assert value, "429 response must include Retry-After"
if value.isdigit():
assert int(value) >= 0
else:
parsedate_to_datetime(value) # raises if it isn't a valid HTTP date
Trigger the 429 against a test environment with a low configured limit rather than hammering a shared one.
Errors hidden inside a 200. Some APIs return {"success": false, "error": "quota_exceeded"} with a 200. If that's the documented design, assert on the body's success flag every time, not on the status code alone.
Timeouts. If a gateway returns 504 when an upstream is slow, check that the body is still something a client can parse, not an empty response or a connection reset.
Error bodies are now an interface for agents
This is where the agentic side of testing changes the priorities. When a coding agent or an LLM-backed tool calls your API, it reads the error body and decides what to do next. A message like {"field": "start_date", "message": "must be today or later"} lets it fix the request on the next attempt. A bare 400, or an HTML page from the proxy, gives it nothing, so it guesses, retries, or reports a confusing failure to the user. If agents are among your API's callers, the clarity of error messages is functional behaviour, and it deserves tests like any other contract.
The same applies in the other direction when an assistant writes your error tests. Left alone, Copilot and similar agents usually generate status-code-only assertions, because that's what most example code online does. I put the expectation in the repository instructions (.github/copilot-instructions.md for Copilot, or your agent's equivalent):
## Error-path tests
- Every error test asserts status code, a JSON Content-Type, and the documented error body shape.
- Validation errors must assert which field is blamed and that a message is present.
- 5xx tests must assert the body contains no stack traces, SQL errors or internal hostnames.
- Derive expected errors from the OpenAPI spec, not from the current response.
The last line is the important one. An agent that writes expectations by calling the endpoint and copying the result will encode today's bugs as the specification. When I review generated error tests, I check each expected value against the spec or the ticket, then break the validation on purpose to confirm the test actually fails.
Treat errors as part of the contract
The thread through all of this is the same: decide what a correct error response looks like for your API, write it down as assertions, and run them on every path that can produce an error. Error handling is part of the API contract, and now that agents both write your tests and call your endpoints, it's a part that gets read more closely than ever. For more on how this fits real debugging and auth scenarios, see the real-world testing scenarios guide, and if you'd like to build a suite like this step by step, my API testing courses walk through it with Behave or Cucumber and GitHub Copilot.