QA Interview Hub · Knowledge base · Quizzes · Українська

API › API design: resources, pagination, versioning, GraphQL

Error format: Problem Details and stable codes

An API error is described in Problem Details (RFC 9457) with a stable machine code. A test checks the code, status and field, not the detail text, which is edited and translated. The body status matches the HTTP status, and the shape is the same for 4xx and 5xx. Framework and gateway errors often stay HTML, so trigger them separately and check Allow and Retry-After.

API · Error format

A test compares the error text. After the message is translated it goes red. Who is to blame?

A test checks detail === "Field qty must be between 1 and 100". A week later a copywriter rewrites the message, or the server starts returning it depending on the language, and a dozen tests fail although the API behaviour did not change. The test is to blame: it tied itself to text for a human instead of the stable part a machine can check.

An error in an API is part of the contract too. The client must understand automatically what happened (show a form, retry, sign out), and a person must be able to read the reason. The lesson covers the standard format, stable codes and what to check in errors.

How it works and why it is designed so

Problem Details (RFC 9457, the successor to RFC 7807) describes one shape of an HTTP API error. The media type application/problem+json tells the client that the body is an error of this format, and it can be parsed the same way for any service.

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
Content-Language: en

{
  "type": "https://api.shop.test/errors/validation",
  "title": "Validation failed",
  "status": 422,
  "detail": "Field qty must be between 1 and 100, got 0",
  "instance": "/v1/orders",
  "code": "validation_failed",
  "errors": [{ "field": "qty", "code": "out_of_range" }]
}

The fields defined by the standard: type (a URI, a stable identifier of the error class; if absent, about:blank is implied), title (a short description of the class, the same for all cases), status (a copy of the HTTP status), detail (an explanation of this concrete case), instance (a reference to this occurrence of the problem). Everything else, including code and errors in the example, are extension members: the team adds them, and they must be described in the specification.

Why so. The HTTP status is not enough: 422 says “validation” but not which field and why. The detail text is meant for a person; it is changed, edited and translated. So a third thing is needed: a stable machine code (type or code) that client code and tests can rely on. It is like a public method in code: its name is not changed every week.

Not every API supports RFC 9457. Often there is a custom wrapper:

{ "error": { "code": "out_of_range", "message": "qty must be 1..100", "field": "qty" } }

That is fine if the shape is the same for all errors and described in OpenAPI. What is checked is consistency, not a “fashionable” format.

What to rely on when checking an error

Typical

The detail text

For a person. It changes with editing and translation and depends on the language. A test that compares it breaks without a behaviour change.

Better

type / code and the field

For a machine. Part of the contract, changes by the versioning rules. The test checks it, and the text only for presence.

Figure 1. What a person reads and what code reads live apart. We test the second.

Example: from comparing text to checking the contract

Before: a test on the message. It breaks on any editing.

// before: breaks when the message is reworded or translated
expect(body.detail).toBe('Field qty must be between 1 and 100, got 0');

After: we check the error type, the field and the field code, and for the text only that it exists. The same goes for the status: a shared function checks the shape, and the test adds the specifics.

// after: stable machine part, human text only checked to exist
expect(body.type).toBe('https://api.shop.test/errors/validation');
expect(body.errors).toContainEqual({ field: 'qty', code: 'out_of_range' });
expect(typeof body.detail).toBe('string');

A separate class of defects: errors generated not by business logic but by the framework or the gateway. An unknown route, an unsupported method, broken JSON, an oversized request, a wrong Content-Type, a gateway timeout. They are often returned in the framework's or proxy's “native” form, including an HTML page, and a client that expects JSON fails on parsing. This is visible only with a deliberate check:

curl -si "$BASE/v1/no-such-route"                       # unknown route
curl -si -X DELETE "$BASE/v1/orders"                    # method not allowed: Allow header?
curl -si -X POST "$BASE/v1/orders" \
  -H "Content-Type: application/json" -d '{"qty": '    # broken JSON
curl -si -X POST "$BASE/v1/orders" \
  -H "Content-Type: text/plain" -d 'qty=1'              # wrong media type
const framework = [
  { name: 'unknown route', method: 'GET', url: '/v1/no-such-route', status: 404 },
  { name: 'method not allowed', method: 'DELETE', url: '/v1/orders', status: 405 },
  { name: 'broken JSON', method: 'POST', url: '/v1/orders', body: Buffer.from('{"qty":'), status: 400 },
];

for (const c of framework) {
  test('error shape: ' + c.name, async ({ request }) => {
    const res = await request.fetch(c.url, {
      method: c.method,
      headers: { 'Content-Type': 'application/json' },
      data: c.body,
    });
    expect(res.status()).toBe(c.status);
    expect(res.headers()['content-type']).toContain('application/problem+json');
    const body = await res.json();
    expect(body.status).toBe(c.status);
    expect(JSON.stringify(body)).not.toMatch(/Exception|SELECT |at \w+\.\w+\(/);
  });
}
  • 405 comes with an Allow header listing the allowed methods (a requirement of RFC 9110).
  • 401 returns WWW-Authenticate; its absence contradicts the standard.
  • 429 and 503 may carry Retry-After, and the client relies on it.
  • The error body has one shape for 4xx and 5xx, whoever produced it.

What to check in every error response

  • Shape and content type: all errors have the same structure and the right Content-Type, not text/html.
  • Status match: status in the body equals the HTTP status. A body status and a header status that differ signal a response assembled by different layers.
  • A stable code: type or code is checked. For several distinct reasons the code differs, instead of one generic “Bad request”.
  • Per-field validation: the errors list shows all invalid fields at once, with the field name and the reason code, not just the first one.
  • Nothing extra: the body has no stack trace, SQL, internal hosts, class names or file paths. Those details go to the logs, and the client gets a request id (X-Request-Id, traceId).
  • The same response for “missing” and “not yours” where security demands it: a difference between 404 and 403 tells an attacker the resource exists.
  • Localization: if the text depends on Accept-Language, the code and type stay the same, and Content-Language matches the text.

Limits and alternatives

  • Problem Details does not require a list of validation errors; errors is the agreement of a concrete API. Other formats (JSON:API errors, Google error.details, custom ones) also have such arrays. Learn the shape of this API.
  • type is a URI, and it need not open anything, but it is good practice when documentation about the error is there.
  • In GraphQL errors live in the errors array with extensions.code, not in the HTTP status; the “stable code” principle is the same.
  • For internal services a code and a message are enough; for public APIs a standard shape saves time for all clients.

Common mistakes

  • Comparing the text of detail or message. The only exception: a test of the text itself (translation, absence of secrets).
  • Checking only the success path and never provoking framework errors (a non-existent route, broken JSON).
  • Not checking 5xx: some APIs return the shape only for 4xx, and for 500 and 502 return HTML.
  • Accepting any 4xx in a test. “Some error” does not mean “the right error”: 400 instead of 401 hides an authorization problem.
  • Not checking the headers that come with an error (Allow, WWW-Authenticate, Retry-After).

Check yourself

Why is expect(body.detail).toBe("…") a poor check, and what replaces it?

Answer

The detail text is meant for a person; it is changed, edited and translated, so the test breaks without a behaviour change. Instead check the stable machine parts: type or code, the status and the field in errors; for the text only its presence.

For a request with broken JSON the server returned 400, but with Content-Type: text/html and a framework page. Why is that a defect although the status is right?

Answer

The client expects an error body in one shape and tries to parse it as JSON, so it fails on parsing and cannot show the reason. Errors produced by the framework or the gateway must have the same shape and content type as business-logic errors.

In a 422 response the body contains "status": 400. What does it mean and why does it matter?

Answer

The body status and the HTTP status disagree: different layers built the response, or the error was only partly “translated”. The client may pick the wrong handling branch, so status in the body must match the HTTP status.

In an interview. Junior: An error is part of the contract: one shape, a clear code and a status that matches HTTP. The test looks at the error code, not at the message text. Middle/Senior: I standardize the check in a shared function (status, Content-Type, shape, no stack trace), run it on framework and gateway errors too (404, 405, broken JSON, 413), where HTML often remains, and verify the accompanying headers Allow, WWW-Authenticate, Retry-After.

More articles in this chapter