API TESTING

REST API Status Codes: What They Mean for Tests and Agents

Status codes look like the simplest part of an API test. Send a request, check for 200, move on. In practice, they're where a lot of weak tests hide. A test that only checks the status code can pass while the response body is wrong, and a test that expects the wrong code locks in behaviour nobody intended.

Each code is a short message from the server about what happened and what the caller should do next. Retry later. Fix your request. Log in again. You're not allowed. That second half, what the caller should do next, has become more important now that some of your callers are AI agents working through tools. A person reading an error can use judgement. An agent mostly acts on the signal you give it, so a 500 that should have been a 400, or a 200 wrapping an error, sends it down the wrong path.

In this article I'll go through what each class actually tells you, the specific codes that trip up test suites most often, how I assert them in pytest and Behave, and what changes when the client is an agent.

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

The five classes and what each one tells the caller

  • 1xx Informational. Interim responses such as 100 Continue. Your HTTP client usually handles these and you rarely assert on them.
  • 2xx Success. The request was received and handled. Which 2xx matters, as below.
  • 3xx Redirection. The caller needs to go somewhere else or use a cached copy. Note that requests follows redirects by default, so a test may see the final 200 rather than the 301 or 302 unless you pass allow_redirects=False.
  • 4xx Client error. The caller did something the server won't accept. Changing the request, credentials or timing is the fix; sending the same request again is not.
  • 5xx Server error. The server failed to handle a request that may have been valid. Some are temporary and worth retrying carefully; some are bugs.

The split between 4xx and 5xx is the most important one in a test suite. A 4xx says "the caller is wrong", a 5xx says "the server is wrong". An API that returns 500 for invalid input is reporting its own bug every time a client makes a mistake, and your tests should treat that as a defect.

The codes that trip up test suites

Success codes

  • 200 OK: generic success with a body.
  • 201 Created: a resource was created. APIs commonly include a Location header pointing to it, which is worth asserting if your API documents it.
  • 202 Accepted: the work was queued, not done. A test that asserts 202 and then checks the result immediately is a race. Poll or wait for the outcome; see testing async APIs when there is no immediate response.
  • 204 No Content: success with no body. Calling response.json() on it raises an error.

Client errors

  • 400 Bad Request: malformed or invalid request.
  • 401 Unauthorized: not authenticated. Missing, expired or invalid credentials.
  • 403 Forbidden: authenticated but not allowed.
  • 404 Not Found: no such resource. Some APIs return 404 instead of 403 on purpose so they don't reveal that a resource exists. Test what's documented.
  • 409 Conflict: the request conflicts with current state, such as a duplicate or a version mismatch.
  • 422 Unprocessable Content: well-formed but semantically invalid. Frameworks differ on whether they use 400 or 422 for validation errors, so assert the one your API documents, not the one you'd prefer.
  • 429 Too Many Requests: rate limited. Often sent with a Retry-After header.

Server errors

  • 500 Internal Server Error: an unhandled failure. Almost always a bug worth reporting.
  • 502 Bad Gateway and 504 Gateway Timeout: a proxy or gateway had trouble reaching the service behind it.
  • 503 Service Unavailable: temporarily unable to handle requests, sometimes with Retry-After.

The biggest trap isn't a specific code, though. It's the API that returns 200 with an error inside the body. Status-only assertions pass and the failure goes unnoticed. I cover that pattern in testing API responses that embed errors inside a 200.

Asserting status codes so failures explain themselves

Two habits make status assertions useful. Assert the exact code, not a range, unless the contract really allows a range. And include the response body in the failure message, because the code alone rarely tells you why:

import requests


def test_create_order_returns_201_with_location(api_base_url, auth_headers):
    response = requests.post(
        f"{api_base_url}/orders",
        json={"sku": "QA-001", "quantity": 1},
        headers=auth_headers,
        timeout=10,
    )
    assert response.status_code == 201, f"{response.status_code}: {response.text}"
    assert "Location" in response.headers
    assert response.json()["status"] == "pending"

Avoid response.ok or raise_for_status() as your only check in a test. Both treat every 2xx and 3xx as equal, so a 202 where you expected 201, or a 200 where you expected 204, slips through.

In Behave, one reusable step covers it, and the expected code stays visible in the scenario:

from behave import then


@then("the response status code is {status_code:d}")
def step_status_code(context, status_code):
    actual = context.response.status_code
    assert actual == status_code, f"expected {status_code}, got {actual}: {context.response.text}"

Pair every status assertion with at least one assertion about the body or headers. The code says what kind of outcome happened; the body says whether it was the right one. For error responses specifically, see testing API error responses beyond the happy path.

Status codes when the caller is an AI agent

When an agent calls your API through a tool, the status code is one of the few structured signals it gets. Whether the agent handles it well depends partly on the tool wrapper and partly on whether your API's codes are honest. Here's what I check:

  • The tool wrapper preserves the signal. A wrapper that turns every non-2xx into "request failed" throws away the most useful information. It should pass back the code and a short reason: 422 with the field errors, 403 with "not permitted", 429 with the retry delay.
  • Retries are bounded and code-aware. An agent that gets a 429 and immediately tries again in a loop makes the problem worse. The wrapper, not the model, should own retry policy: back off on 429 and 503, never retry 400, 401, 403, 404 or 422.
  • 4xx tells the agent to change something. A clear 400 or 422 lets the agent correct its arguments. A 500 for bad input tells it nothing, and it may keep sending the same request.
  • Success means success. A 200 carrying an error is even worse for an agent than for a person: it will report the task as done.

You can test the wrapper like any other code. Stub the HTTP layer to return each code, then assert the structured result the agent would receive:

import pytest

from tools.orders import create_order_tool


@pytest.mark.parametrize("status, expected_kind, retryable", [
    (201, "ok", False),
    (422, "invalid_arguments", False),
    (403, "not_permitted", False),
    (429, "rate_limited", True),
    (503, "unavailable", True),
])
def test_tool_maps_status_codes(stub_http, status, expected_kind, retryable):
    stub_http.respond(status=status, json={})
    result = create_order_tool(sku="QA-001", quantity=1)
    assert result["kind"] == expected_kind
    assert result["retryable"] is retryable

Here stub_http and create_order_tool stand in for your own fixture and wrapper. The point is that the mapping from code to agent-facing result is deterministic, so it gets ordinary, fast tests.

Codes are a contract

Status codes are part of your API's contract, for people, for test suites and now for agents. Assert the exact documented code, always check the body as well, and treat a 5xx for client mistakes as a bug. If you want to build API suites around assertions that hold up in CI, in Python with Behave or Node with Cucumber, my API testing courses walk through it with VS Code and GitHub Copilot.

Ready to level up your testing skills?

Python Course Node Course