Filtering, sorting, searching and field selection

Difficulty: Beginner

Question

How would you design filtering, sorting, searching and sparse field selection on a list endpoint?

Answer

Once an endpoint returns a list, clients immediately want to narrow it: only paid orders, only from last week, cheapest first, and just the fields needed for a table. The design goal is to give expressive power without inventing a query language that becomes impossible to secure and document. Think of a restaurant menu with sections: you offer sensible filters, not a way for guests to write SQL.

Filtering is usually done with query parameters that map to fields: GET /orders?status=paid&customer_id=42. For multiple values, pick one convention: status=paid,shipped or repeated status=paid&status=shipped. For ranges, use suffixes or brackets: created_at[gte]=2026-09-01&created_at[lt]=2026-10-01, or created_after and created_before. Stripe uses bracket operators; many teams prefer simple named params for readability. Whatever you pick, document it and use it everywhere.

Sorting: use a sort parameter with a leading minus for descending, and commas for multiple keys: sort=-created_at,total. Whitelist sortable fields, and make sure they are backed by indexes; allowing sort on arbitrary columns is an easy way to create slow queries. Always include a tiebreaker, such as id, so ordering is deterministic and pagination remains stable.

Searching is different from filtering. Filtering is exact or range matching on structured fields; search is relevance-ranked text matching. Use q=biryani for free text, and route it to a proper index such as Postgres full text search, Elasticsearch or OpenSearch rather than LIKE '%term%' on a big table. Keep the response shape the same.

Field selection, sometimes called sparse fieldsets: fields=id,status,total lets mobile clients trim payloads. Related to that is expansion or embedding: expand=customer,items inlines related resources so that the client avoids extra round trips, as in Stripe's expand parameter. These two features are how REST APIs address over-fetching and under-fetching without going to GraphQL. Watch out for expansion depth, which can cause heavy joins and N+1 queries, so cap it.

Validation and safety: treat all of these parameters as untrusted input. Whitelist filter fields and operators, validate types, return 400 or 422 with a clear error for unknown params rather than silently ignoring them, since silent ignoring gives clients a false impression that the filter worked. Never concatenate values into SQL; use parameterised queries or an ORM. Enforce maximum page size and maximum filter complexity.

Also consider consistency with caching: query strings form part of the cache key, so normalise parameter order when possible. And decide whether filters combine with AND (the usual default) and how to express OR, which most APIs handle with multiple-value params on one field rather than arbitrary boolean logic.

If requirements become very complex, with arbitrary nested filters and dynamic projections, that is a signal to consider GraphQL or a dedicated search endpoint, rather than pushing REST query strings further.

Code examples

Filter, sort, fields and expand in one request

GET /v1/orders?status=paid,shipped&created_at[gte]=2026-09-01&sort=-created_at,id&fields=id,status,total&expand=customer&limit=20 HTTP/1.1
Host: api.example.com

Multi-value filter, range operator, multi-key sort with tiebreaker, sparse fields, and expansion of the customer relation.

Whitelisting sort fields

const SORTABLE = new Set(['created_at', 'total', 'id']);
function parseSort(param = '-created_at') {
  return param.split(',').map((s) => {
    const desc = s.startsWith('-');
    const field = desc ? s.slice(1) : s;
    if (!SORTABLE.has(field)) throw Object.assign(new Error('Unknown sort field: ' + field), { status: 400 });
    return { field, dir: desc ? 'DESC' : 'ASC' };
  });
}

Only indexed, allowed columns can be sorted, and unknown ones produce a clear 400.

Key points

Common follow-up questions

Interview tips

Concepts covered

filtering, sorting, field selection, query parameters

More API Design questions