Skip to the workspace
Pebellslearn by building
Robust Endpoints  ›  Lesson

Pagination, Filtering and Sorting

Pagination 15 minLarge collections are narrowed with filter parameters, ordered with a sort parameter and sliced into pages with offsets or cursors, all in the query string.

api design / Pagination, Filtering and Sorting

Explore each scene at your own pace.

01 · The rule

The rule

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=dragon

Simple 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,title

That 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=40 gives 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.