API design: resources, pagination, versioning, GraphQL
Pagination: offset vs cursor
Offset pagination names a position from the start of the list, while cursor pagination names the place after a page's last item. Offset is simple and allows jumping to any page, but it is slow on large offsets, and inserts or deletes shift records and cause duplicates or gaps. Cursor is more stable, but cannot jump to an arbitrary page and needs a unique key in the sort.
API · API design
A user scrolls the payment history: one payment is on two pages, another vanished. Is it a bug?
On a “Transaction history” screen the client taps “more” and the same transfer appears twice. Someone added a record between the two requests and the pages shifted. The server answered both requests “correctly”; the paging scheme itself broke. When a list is not returned whole, the contract gets one more part: how to read the second, the third and the last page.
Below: the two approaches (offset and cursor), why they behave differently, how to test a walk through all pages and what to do with the boundaries.
How it works and why it is designed so
Thousands of records in one response hurt both the server (memory, response time) and the client (parsing, rendering), so collections are returned in portions. There are two main ways to say “which portion”.
Offset pagination:GET /transactions?limit=20&offset=40 or ?page=3&size=20. The client names a position. It is simple to implement, you can jump to any page and show “page 3 of 50”. The price: the database has to walk past all the skipped rows, so a large offset is slow; and the position is counted from the start of the list, so any insert or delete shifts everything after it.
Cursor pagination:GET /transactions?limit=20&cursor=eyJpZCI6MTAyNH0. The server returns nextCursor pointing to the last element of the page, and the next page starts after it. The cursor is usually opaque to the client (often an encoded id plus the sort value), and the client must not parse or invent it. The request becomes “everything after id 1021”, so an index jumps straight there, and inserts before the cursor shift nothing.
offset: SELECT * FROM tx ORDER BY id DESC LIMIT 20 OFFSET 100000
-- the database walks past 100000 rows and throws them away
cursor: SELECT * FROM tx WHERE id < 1021 ORDER BY id DESC LIMIT 20
-- an index jumps straight to id 1021
What happens if a record is added between the requests
Offset
Sorted newest first. Page 1 (offset=0&limit=3): E, D, C. F is added. Page 2 (offset=3): C, B, A. Record C is shown twice, and the client never saw F.
Cursor
Page 1: E, D, C, cursor “after C”. F is added. Page 2: everything older than C: B, A. No duplicates. F shows up on the next refresh of the first page.
Figure 1. Both approaches are legitimate, but offset does not guarantee a consistent walk over a changing collection. Cursor does, if the order is unambiguous.
A cursor works only with an unambiguous order. If the sort is by createdAt and several records share the same time, the server does not know where it stopped. So a unique key is added to the order: ORDER BY createdAt DESC, id DESC. Without it, records with equal time can get lost on a page boundary.
The shape of the response is also part of the contract. Common variants: a wrapper with items and nextCursor, or a Link header with rel="next" (RFC 8288), where the server returns a ready URL of the next page:
HTTP/1.1 200 OK
Link: <https://api.bank.test/v1/transactions?cursor=eyJpZCI6MTAyMX0>; rel="next"
Check the shape that this API's specification describes, not the one you know from another project.
Example: from “the first page works” to a walk over the whole list
Before: the test takes one page and counts the items. It is green even if the third page returns duplicates or nextCursor never becomes empty.
// before: checks one page onlytest('transactions: first page', async ({ request }) => {
const res = await request.get('/v1/transactions?limit=20');
expect(res.status()).toBe(200);
expect((await res.json()).items).toHaveLength(20);
});
After: the test walks all pages to the end, collects the ids and compares them with an independent source (a counter, a separate request, or test data the test created itself). The iteration cap is needed so that a “cursor never ends” bug gives an error, not an endless test.
import { expect, typeAPIRequestContext } from'@playwright/test';
asyncfunctionwalkAll(request: APIRequestContext, path: string) {
const ids: number[] = [];
let cursor: string | undefined;
for (let page = 0; page < 500; page++) {
const q = newURLSearchParams({ limit: '20' });
if (cursor) q.set('cursor', cursor);
const res = await request.get(path + '?' + q);
expect(res.status()).toBe(200);
const body = await res.json();
ids.push(...body.items.map((i: { id: number }) => i.id));
cursor = body.nextCursor ?? undefined;
if (!cursor) return ids;
}
thrownewError('pagination never ends: nextCursor does not become empty');
}
test('walk all pages: no duplicates, count matches', async ({ request }) => {
const ids = awaitwalkAll(request, '/v1/transactions');
expect(newSet(ids).size).toBe(ids.length); // no duplicatesconst total = (await (await request.get('/v1/transactions/count')).json()).total;
expect(ids).toHaveLength(total); // no gaps
});
The second test reproduces the scenario from the beginning of the article: after the first page we create a record and read the second. For cursor there must be no duplicates. For offset this test will show a duplicate, and that is a documented property of the approach, not a bug: then the test only checks that the server does not fail and returns the documented behaviour.
test('insert between pages does not shift the next page', async ({ request }) => {
const first = await (await request.get('/v1/transactions?limit=3')).json();
await request.post('/v1/transactions', { data: { amount: 10, currency: 'UAH' } });
const second = await (
await request.get('/v1/transactions?limit=3&cursor=' + first.nextCursor)
).json();
const seen = newSet(first.items.map((i: { id: number }) => i.id));
for (const item of second.items) expect(seen.has(item.id)).toBe(false);
});
Limits and boundary values
The pagination parameters need negative cases themselves. A quick run:
for q in "limit=0""limit=-1""limit=abc""limit=100000""cursor=garbage"; do
echo "== $q"
curl -s -o /dev/null -w "%{http_code}\n" \
-H "Authorization: Bearer $TOKEN""$BASE/v1/transactions?$q"
done
limit=0, negative, non-numeric: usually 400 (or 422, depending on the API's distinction), not 500 and not an empty success.
limit above the maximum: either 400 or the server silently lowers it to the maximum. Both are legitimate if documented, but the response must say which limit was applied.
limit not given: the default applies, not “everything”.
The last page: an empty or absent nextCursor (null), not an error. An empty list after the last page gives 200 with an empty array.
A forged, corrupted or expired cursor: 400 with a clear reason. A cursor taken from another request (different filter or sort) must not return foreign data. A cursor must not be a way around authorization: the server checks permissions on every request.
A filter together with pagination: the cursor is tied to the filter, and changing the filter mid-walk must either reset the walk or give 400.
Limits and alternatives
Cursor cannot “jump to page 50” and does not make counting pages easy. If the product needs page numbers (admin panels, tables), offset stays justified, especially for small, almost static lists.
total in the response needs a separate COUNT, which is expensive on a large table. That is why some APIs do not return it, or return it approximately. Do not demand an exact total if the contract does not promise it.
Keyset (seek) pagination, which cursor is built on, is fast only with an index on the sort fields. Sorting by an arbitrary unindexed field is slow again.
In GraphQL the common standard is Relay connections (edges, pageInfo, endCursor); the idea is the same.
Common mistakes
Checking only the first page. Duplicates, gaps and an endless cursor are visible only on a walk to the end.
Not fixing the data. If other tests or users change the list in parallel, a duplicate can be a real coincidence. Test on a collection the test created itself.
Parsing the cursor in the test. It is a private detail of the server, and after an encoding change the test breaks while the contract is intact.
Expecting total where it is not promised, and the reverse: not checking that total equals the real count where it exists.
Check yourself
A test takes limit=20, checks 200 and 20 items. Why is that not enough for pagination?
Answer
It sees only the first page. Duplicates between pages, missing records, a cursor that never ends and an error on the last page are visible only on a walk to the end that compares ids with a known set.
Between the first and second page requests someone created a record. Why does offset show a duplicate and cursor does not?
Answer
Offset counts the position from the start of the list, so an insert at the top shifts every element by one, and the last element of page one becomes the first on page two. Cursor says “after this element”, so an insert before the cursor shifts nothing.
The sort is by createdAt and two records have equal time on a page boundary. What can go wrong and how to fix it?
Answer
The server cannot tell whether the second of the two was already returned, so it may skip it or return it twice. The fix: add a unique key to the order, for example createdAt DESC, id DESC, and build the cursor from both fields.
Related lessons: “Filtering, sorting and versioning”, “Data: pagination, time zones, truncation, caching of private data”, “Equivalence classes and boundary values for fields and parameters”.
In an interview.Junior: Offset is simple and allows a jump to any page, but it is slow on large offsets and duplicates or skips records on inserts. Cursor is stable and fast, but cannot jump to an arbitrary page. I check the limit boundaries, the last page and the absence of duplicates. Middle/Senior: I walk all pages in an automated test on a collection the test created, compare ids with a known set and cap the iterations so that a cursor that never ends fails the test. For cursor I check an unambiguous order (a unique key in the sort), the reaction to a forged cursor and that the cursor does not bypass authorization.
Filtering, sorting and versioning
Filters and sorting go in the query, and versioning lets a contract change without breaking clients you do not control. The version goes in the path, a header or the query, and the key question is what counts as a breaking change: removing or renaming a field, changing a type, a new required request field, stricter validation. Contract tests run on every supported version.
API · API design
In v2 the balance field became a string. The mobile app on v1 is already in users' hands. What breaks?
The team shipped v2: new fields appeared in the response and the amount type changed from a number to a string, which is more precise. The new web client works. But users do not update the mobile app for months, and the old client calls v1. If the change landed in v1, or one code base serves both versions with a bug, the app crashes parsing the amount. Filters and sorting have similar traps: an unknown field, letter case, date boundaries.
This lesson covers three things that together decide how a client “selects” data and how an API changes over time: filtering, sorting and versioning.
How it works and why it is designed so
Filters and sorting live in the query. The path identifies a resource (/transactions), the query refines the selection. This follows from the GET semantics in RFC 9110: the same resource, with parameters only describing which part of it to take, so a response can be cached by the full URL.
GET /v1/transactions?status=completed¤cy=UAH&from=2026-01-01&to=2026-01-31&sort=-createdAt,id HTTP/1.1
Host: api.bank.test
Conventions differ between APIs: a minus before a field (-createdAt) often means descending, several fields are separated by commas, a date range may be from and to or createdAt[gte]. There is no standard, so the source of truth is the specification of the concrete API.
Sorting by a field from a parameter is dangerous if the server puts it into a database query. So the allowed fields must be a closed list (allowlist), and everything else is rejected. A test with sort=password and with values containing quotes checks this.
Versioning is needed to change the contract without breaking clients you do not control. Three common places for the version number:
In the path: /v1/accounts, /v2/accounts. The most visible, the easiest to test and route.
In a header: a custom Api-Version: 2 or a version in the media type in Accept. Cleaner URLs, but a client forgets the header more easily, and caches must take it into account through Vary.
In the query: ?version=2. Rarer, easy to lose.
The main question is not “where” but “what counts as breaking”. A breaking change: removing or renaming a field, changing a type (number to string), a new required field in the request, stricter validation, a changed meaning of a value (status done now means something else), a new enum value for clients that do not know it. Not breaking: a new optional response field, a new endpoint, a new optional request field. Even here there is a nuance: clients with a strict schema (additionalProperties: false) can fail on a new field, so “adding” should be agreed too.
What fits inside a version and what needs a new one
Same version
A new optional response field. A new endpoint. A new optional request field. A bug fix that does not change the documented contract.
New version
The type of balance from number to string. A removed or renamed field. A new required request field. A changed meaning of a value. Stricter validation.
Figure 1. The line between “add” and “change” matters more than where the version number is written. An old client does not see an addition, but feels a change to an existing thing at once.
An outdated version is retired gradually. The Sunset header (RFC 8594) announces the shutdown date, and Deprecation (RFC 9745) says that a resource is deprecated. These are only signals: clients must read them, and the team must agree on a deadline.
Example: from “works on v2” to a contract on both versions
Before: tests are written only for the new version. After the v2 release the old client breaks while CI is green. After: shared contract checks run on every supported version, and the differences between versions are described by separate tests.
for (const v of ['v1', 'v2']) {
test('account contract holds on ' + v, async ({ request }) => {
const res = await request.get('/' + v + '/accounts/42');
expect(res.status()).toBe(200);
const body = await res.json();
expect(typeof body.id).toBe('string');
expect(typeof body.balance).toBe(v === 'v1' ? 'number' : 'string'); // v1 keeps number, v2 changed it on purpose
});
}
The v1 test after the v2 changes catches exactly the case from the beginning: the amount type changed in the wrong place. In addition we check a request without a version (the default must be documented behaviour, not “the latest one released”) and a non-existent version /v9/accounts: 404 or 400 in the standard error shape, not 500.
For filters and sorting, run through the boundaries one by one:
curl -s "$BASE/v1/transactions?status=nope"# unknown value
curl -s "$BASE/v1/transactions?sort=password"# not an allowed sort field
curl -s "$BASE/v1/transactions?status=completed&status=failed"# repeated parameter
curl -s "$BASE/v1/transactions?status=COMPLETED"# letter case
curl -s "$BASE/v1/transactions?from=2026-02-30"# impossible date
curl -s "$BASE/v1/transactions?q=100%25"# a literal percent sign
A filter with no results gives 200 and an empty array, not 404: the “collection” resource exists.
An unknown field in a filter or sort: either 400 or ignored, but whatever is documented. Silent ignoring is dangerous: the client thinks it filtered and gets everything.
Letter case and spaces:status=COMPLETED and completed give the same result or 400, but not a different one silently.
A repeated parameter:status=a&status=b means “or” or “the last one wins”. It has to be known from the documentation.
Special characters:%, _, quotes in a search value must not act as a wildcard or break the database query.
Date boundaries: is to inclusive or exclusive, and in which time zone. A record at 23:59:59 of the last day must land where the documentation puts it.
Stable sorting: without a unique key the order of records with an equal value may float between requests (see the pagination lesson).
test('sort=-createdAt gives newest first, ties are stable', async ({ request }) => {
const res = await request.get('/v1/transactions?sort=-createdAt,id&limit=100');
const items: { id: number; createdAt: string }[] = (await res.json()).items;
for (let i = 1; i < items.length; i++) {
const a = items[i - 1];
const b = items[i];
expect(a.createdAt >= b.createdAt).toBe(true); // ISO 8601 UTC strings of one format compare correctlyif (a.createdAt === b.createdAt) expect(a.id).toBeLessThan(b.id);
}
});
Limits and alternatives
A version in the URL multiplies code and tests. The alternative: evolve the API only additively and not change the version until a real break is needed. This works when you control the clients or design fields carefully.
For public APIs and mobile apps versioning is almost unavoidable: an app can be force-updated only partly. Then “supported versions” have a cost that must be planned into regression.
Consumer contracts (Pact) let you know which fields clients really use, and break only what nobody reads.
GraphQL usually has no versions: the schema evolves through @deprecated and new fields.
Complex filters (filter[status]=…, query languages, OData) have their own rules; learn them from the specification instead of guessing.
Common mistakes
Testing only the latest version. Old clients live long, and shared code can break them unintentionally.
Assuming that “adding a field” is always safe. For strict clients and for enums it can be a breaking change.
Checking a filter on a single value. The bug often sits in a combination of filters or in the absence of a filter.
Not checking that the result is really sorted. Comparing neighbouring elements of the response is enough, as in the test above.
Trusting the documentation on date boundaries without trying a record exactly on the boundary.
Check yourself
GET /v2/accounts now returns balance as a string. Who suffers and how should it be handled?
Answer
Clients that parse the amount as a number suffer, first of all those that stayed on v1 if the change landed there. A type change is a breaking change, so it is made only in a new version, and v1 stays unchanged until the announced shutdown date.
A request ?status=complete (a typo) returned 200 and all records. Why is that a bug even without an exception?
Answer
The server silently ignored an unknown value, and the client believes the selection was filtered. It should be 400 (or at least documented ignoring), because otherwise a mistake in a parameter quietly produces wrong data.
Why do Sunset and Deprecation not force anything on a client by themselves?
Answer
They are informational headers: they announce a shutdown date or the fact of deprecation, but do not block the request. Protection from breakage comes only from process (deadlines, communication) and monitoring: who still calls the old version.
Related lessons: “Pagination: offset vs cursor”, “Consumer-driven contracts and breaking changes”, “Parameter combinations, resource states and CRUD flows”, “Service headers: Retry-After, rate limits, Vary and security”.
In an interview.Junior: I test filters and sorting in combinations, with an empty result, with unknown fields and values. If the API is versioned, I regress the old version too, because real clients, especially mobile ones, are still on it. Middle/Senior: I ask separately what counts as a breaking change: a type change, a removed field, a new required field, stricter validation. I run the shared contract tests on every supported version, and check the retirement of an old version through the Deprecation and Sunset signals and through traffic.
GraphQL: basics and testing
GraphQL describes an API with a typed schema, usually with one endpoint where the client chooses the fields it needs. A response has data and errors keys, so it can be partial: a failed field becomes null, the rest of the data arrives, and status 200 says almost nothing. A test checks errors, their path and code, authorization at every field level, and limits on depth, complexity and aliases.
API · GraphQL
A query returned 200, the response has errors, yet some data is there. Is the test green or red?
A GraphQL test checks status === 200 and goes green. Meanwhile the response body contains "owner": null and an errors array with “Not authorized”. The client shows an empty owner name. REST habits do not work here: the status says almost nothing, and part of a response can be correct together with an error.
The lesson: how GraphQL is built, where errors live in it, what to check at field level and how to stop a client from bringing the server down with one query.
How it works and why it is designed so
GraphQL (the specification is on graphql.org) describes an API with a typed schema. The server usually has one endpoint, POST /graphql, and the client says in the query exactly which fields it needs. This solves two REST problems: over-fetching (more came than needed) and under-fetching (several requests were needed). There are three operations: query reads, mutation changes, subscription subscribes to events. Top-level mutation fields run serially, query fields may run in parallel.
The query and the variables travel separately: the client passes variables typed ($id: ID!) instead of gluing them into a string, which protects against injection into the query itself.
The response has the keys data and errors. The idea is that every field is resolved separately, and the failure of one need not cancel the rest. If a field could not be obtained, it becomes null and errors gets an entry with message, path (where exactly) and usually extensions with a code. If the field is declared non-null in the schema (String!), the null “bubbles up” to the nearest parent field that may be null, and a bigger chunk of data disappears.
The status says what happened: 403, 404, 422. The body describes details. One request, one result, success or error.
GraphQL
The transport is often 200. Success, error and a partial response are in the body: data + errors. An error is tied to a field through path.
Figure 1. A GraphQL error is looked for in the body, not in the status. Some servers return 4xx for an invalid request, but for a field error the response is still 200.
Status-code rules in GraphQL over HTTP are evolving: the newer variant introduces the media type application/graphql-response+json, where an invalid request (a syntax error, a schema validation failure) gets 4xx. For application/json many servers still return 200 even in these cases. So fix the behaviour of a concrete API from its documentation, not from memory.
Example: from “checked the status” to checking data and errors
Before: a REST-style test. It passes even when the server returned an error (and it will fail on data.account if there is no data at all).
// before: REST habitsconst res = await request.post('/graphql', { data: { query: ACCOUNT, variables: { id: '42' } } });
expect(res.status()).toBe(200); // true even when the query failedexpect((await res.json()).data.account.id).toBe('42');
After: a helper returns both the status and the body, and the test checks errors, path, data and the behaviour of the other fields. This is a “field-level authorization” case: access to account exists, but access to the nested owner must be forbidden.
asyncfunctiongql(request: APIRequestContext, query: string, variables = {}, token = '') {
const res = await request.post('/graphql', {
headers: token ? { Authorization: 'Bearer ' + token } : {},
data: { query, variables },
});
return { status: res.status(), body: await res.json() };
}
test('owner field is forbidden for a non-owner, the rest still comes', async ({ request }) => {
const { body } = awaitgql(request, ACCOUNT, { id: '42' }, OTHER_USER_TOKEN);
expect(body.errors?.[0].path).toEqual(['account', 'owner']);
expect(body.data.account.owner).toBeNull();
});
Order of checks: first whether errors is there and whether the code in extensions matches; then data (fully null or partial); then that foreign data did not leak through a nested field. This is where BOLA (access to another user's object) hides most often: in REST the endpoint is authorized, in GraphQL every field and every nested relation must be.
What else to check
Invalid requests: a syntax error, an unknown field, a variable of the wrong type, a missing required variable. Expected: a validation error with errors and without data, not 500.
Nullability: a non-null field must not return null without errors.
Introspection: a __schema query shows the whole schema. For public production it is often disabled so as not to hand out a map of the API, and on a test environment it is handy for checking the contract.
curl -s -X POST "$BASE/graphql" -H "Content-Type: application/json" \
-d '{"query":"{ __schema { types { name } } }"}'
Depth and complexity: recursive relations (account → transfers → account → …) allow a very deep query. The server must limit depth, complexity, result size or execution time.
Aliases and batching: one query can call the same field many times under different names. This bypasses a rate limit that counts HTTP requests, for example when guessing a PIN or codes.
N+1: a list query with nested fields can produce hundreds of database queries. It shows in response time as the number of items grows.
Mutation: the same idempotency and validation requirements as in REST; variables are typed, but the business rules are checked by the server.
Limits and alternatives
HTTP caching in GraphQL is harder: everything goes as POST to one URL, so CDN-level caching works worse. This is compensated by persisted queries and client caches.
Tools: Playwright request.post or any HTTP client works; Postman and Insomnia have built-in schema support and autocomplete. For contracts the schema itself serves as the specification, and it is compared between versions.
Alternatives for different needs: REST (caching, simplicity), gRPC (internal services, binary protocol). GraphQL is best where many different clients want different slices of data.
Subscriptions usually go over WebSocket, not a plain HTTP request, and are tested separately.
Common mistakes
Checking only the status. An error and partial data hide in the body.
Checking only data. If a field is null because of an error and the test does not look into errors, the bug goes unnoticed.
Authorizing only the top level. Nested fields open foreign objects.
Not testing depth limits and aliases. One query is enough to load the server or bypass a rate limit.
Relying on introspection in every environment: on production it may be absent.
Check yourself
A query returned 200, data.account.owner = null and errors has an entry with path: ["account","owner"]. What follows for the test?
Answer
This is a partial response: the owner field could not be obtained (for example, no permission) and the rest of the data is correct. The test must check errors, its path and the code in extensions, not just the status, and make sure foreign data did not land in other fields.
Why does a rate limit by the number of HTTP requests not protect GraphQL from code guessing?
Answer
One HTTP request can contain hundreds of calls to the same field under different aliases, and the server counts it as one. You need limits on complexity or the number of operations in a query, not only on the number of requests.
Why is it not enough in GraphQL to authorize the /graphql endpoint?
Answer
The client chooses the fields and nested relations itself, so one allowed query can reach data the user must not see (for example, account.owner of someone else's account). Permissions are checked in the resolvers of each field or relation.
Related lessons: “REST and alternatives”, “OWASP API Top 10: access and authentication”, “Excessive data, mass assignment, injections, rate limiting”, “Error format: Problem Details and stable codes”.
In an interview.Junior: GraphQL has one endpoint, and the client chooses the fields itself. I check not only the status but data and errors, because a response can be partial. Middle/Senior: Separately I check authorization at field and nested-relation level (BOLA), nullability, depth and complexity limits, and aliases as a rate-limit bypass. Introspection is usually disabled on production, and I look for N+1 by how response time grows with the number of items.
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 translatedexpect(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 existexpect(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
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.
Related lessons: “Error format and service response headers”, “401 vs 403, 400 vs 422, 500 vs 503”, “Excessive data, mass assignment, injections, rate limiting”, “GraphQL: basics and testing”.
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.
Long-running operations: 202, a status resource, webhooks and timeouts
A long operation is not held on one connection: the server answers 202 Accepted with a status link, and the client polls it until the state is final. A 202 status does not mean success, the job's error is carried by the status body. A test checks the state machine, the timeout of a hung job, a repeated start through Idempotency-Key, and for webhooks the signature and duplicates.
A report export takes 40 seconds. The client sends POST /exports and waits on the same connection, while a gateway in front of the service cuts it at 30 seconds: the client sees 504, repeats the request, and now the server has two exports instead of one, and the first may still finish. No "201 and the right JSON" test shows this. An operation that takes longer than a reasonable response time is designed differently: the server answers "accepted" quickly, and the client collects the result separately.
Mechanism. The contract has three parts.
202 Accepted at the start: the request is accepted for processing, but processing is not finished. The status says nothing about success; the response gives a link to a resource to follow (Location) and, if needed, Retry-After.
A status resource: an ordinary resource with a state field that the client reads with GET. The status request itself succeeded, so 200 comes even when the operation ended in an error: the error is described in the body. An unknown id gives 404, and after the retention period also 404 or 410, as the contract says.
A finite state machine, for example queued → running → succeeded | failed | cancelled. Final states do not change, and the state does not go backwards (running → queued).
The result is given either in a resultUrl field or by a 303 See Other redirect from the status resource to the finished resource: both exist, and the contract picks the shape.
Why it works this way. A connection must not live as long as the work lasts: gateways, load balancers and mobile networks drop it arbitrarily, and a drop does not cancel work already started on the server. By separating "accepted" from "finished", the service returns control at once, and the state becomes data that can be re-read, repeated and checked.
Example: a test that does not depend on time. A fixed pause (sleep(10)) is either too slow or too short; endless polling hangs the pipeline. Poll with an upper bound and a growing interval:
Separately check that the POST itself returns 202 fast (seconds, not the duration of the work) even when the worker is slow; otherwise it is a synchronous operation with a different status instead of an asynchronous one.
What to test.
Timeouts. The client's polling limit ends with a clear test error. The server's: a hung operation (simulated with a slowed worker or a small timeout in the configuration) is moved by the service to failed with a reason, not left in running forever. The same after a worker restart in the middle of the work: the job is neither lost nor stuck.
Repeats. A repeated POST with the same Idempotency-Key gives the same id and one operation (and with a different body under the same key the contract requires an error). A side effect (an email, a charge) happens once despite the worker's retries. Polling is a safe GET, repeating it changes nothing.
Final states. Each state moves only to the allowed ones and the others are forbidden; after succeeded or failed the state does not change; cancelling (DELETE or POST .../cancel) during running works, and for an already finished operation gives 409 or another value from the contract. A failed status carries the error in a stable shape, not a stack trace.
Access. Only the owner sees the status and result: someone else's id gives 404 or 403 by policy (BOLA), not the state of another person's operation.
Polling or a webhook. Polling is simple: the client sets the pace and the server knows nothing about it, but it spends requests and adds delay up to the interval. A webhook notifies at once, but needs a publicly reachable receiver and has its own defects: delivery at least once, so duplicates; order is not guaranteed, so a late running event can arrive after succeeded; the receiver is temporarily down, so retries with backoff are needed. So the receiver handles an event idempotently (by event id), verifies the signature and, when in doubt, re-reads the state from the status resource instead of trusting the order of events. On the test side check the signature (a forged event is rejected), redelivery after a receiver error, a duplicate event and an out-of-order event. For a UI a third option can help: SSE or WebSocket, but the status resource stays the source of truth.
Common mistakes.
Treating 202 as success and not waiting for the end: the test is green, while the export breaks after the response.
A pause instead of polling: the test is slow or unstable depending on the load of the environment.
Polling with no upper bound: a worker failure hangs the whole pipeline.
Not checking the terminal failed state: the test waits only for succeeded and fails on a timeout with no reason instead of showing the error from the status resource.
Not checking a repeated start: a double click or a retry after 504 creates a duplicate.
Check yourself
The status resource returns 200 and {"state":"failed"}. Is that an API defect or normal?
Answer
Normal if the contract says so: the status GET succeeded, and the error is carried by the operation's state. A defect would be a 5xx on the status request itself, or failed with no reason in the body.
The client got 504 on POST and repeated it. What must the server guarantee and what does the test check?
Answer
A repeat with the same Idempotency-Key does not create a second operation and returns the same one (the same id). The test sends the request twice and checks one id and one operation in the list.
Related lessons: "PUT vs PATCH and Idempotency-Key in fintech", "Which status to expect in typical scenarios", "Error format: Problem Details and stable codes".
In an interview.Junior: a long operation is not held on one request: the server answers 202 with a link to a status, and the client polls it until the state is final. Senior: I describe the state machine and check forbidden transitions, the server-side timeout of a hung operation, a repeated start through Idempotency-Key and the final states. Polling with a limit and a growing interval beats a pause. A webhook gives speed, but delivery is at least once and the order is arbitrary, so the receiver is idempotent, verifies the signature and re-reads the state.