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: 2or a version in the media type inAccept. Cleaner URLs, but a client forgets the header more easily, and caches must take it into account throughVary. - 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.
HTTP/1.1 200 OK
Deprecation: @1798761600
Sunset: Thu, 01 Jul 2027 00:00:00 GMT
Link: <https://docs.bank.test/migrate-v2>; rel="deprecation"
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
200and 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=COMPLETEDandcompletedgive the same result or 400, but not a different one silently. - A repeated parameter:
status=a&status=bmeans “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
toinclusive 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 correctly
if (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
@deprecatedand 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.
Deprecation and Sunset signals and through traffic.