Pagination, Filtering and Sorting
BookNook's catalogue has 180,000 books. A client calling GET /v1/books must not get all of them at once: the response would be huge, slow and useless on a phone. Callers need to ask for a slice, narrowed to what they care about, in the order they want.
The rule
Filter to narrow, sort to order, page to slice — always in that order.
All three live in the query string, because they change the view, not the resource.
Filtering narrows the collection with field conditions:
GET /v1/books?author=tolkien&available=true
GET /v1/books?published_after=2000-01-01
GET /v1/books?q=dragonSimple equality uses the field name. Ranges need a clear convention such as _after / _before or min_ / max_. A free-text search usually gets its own parameter, commonly q.
Sorting picks the order. A common style lists fields, with - for descending:
GET /v1/books?sort=-published,titleThat means newest first, then by title for ties. Always have a default order, and include a unique field such as id as a final tie-breaker, or pages can shuffle.
Pagination slices the result. Two main styles:
- Offset/limit:
?limit=20&offset=40gives items 41 to 60. Simple, and allows "jump to page 50". But if a book is added while someone is paging, items shift and they may see one twice or miss one. Large offsets also get slow, since the database must count past every skipped row. - Cursor: the response includes an opaque marker for "where you stopped", and the client sends it back:
?limit=20&cursor=eyJpZCI6NDB9. Stable while data changes and fast at any depth, but you cannot jump to an arbitrary page.
{
"data": [ { "id": 41, "title": "..." } ],
"next_cursor": "eyJpZCI6NjB9",
"has_more": true
}Always cap limit (say, at 100) so nobody can ask for everything at once.
The shortcut
Build the query left to right in the same order the server applies it: which books → in what order → which slice.
Which books? (filter)
genre=fantasy&available=true.
The trap is paginating before filtering or sorting in your own code. Page 2 of an unsorted list, sorted afterwards, is not page 2 of the sorted list.
Drills
Answer fast — trust the rule.
With ?limit=10&offset=30, which items come back?
A popular feed gets new books every second. Which pagination style avoids repeated or skipped items?
What does sort=-published,title mean?
Why should the server cap limit, say at 100?
Remember
- Filter to narrow, sort to order, page to slice — in that order.
- Shortcut: which items → what order → which slice.
- Trap: offsets on fast-changing data, sorting without a tie-breaker, and no cap on
limit.
