LearnFrenzy
Sign in Take a free test

Requests, Responses and Data · Lesson 9 of 30

Pagination, Filtering and Sorting in REST APIs

6 min read Updated Nov 8, 2026 Saurabh Samir

A collection endpoint that returns everything works in development and falls over in production, when the table has a million rows. Every list endpoint needs pagination from day one, plus predictable filtering and sorting. There are two pagination styles, and knowing when to use which is a mark of an experienced API designer.

In this lesson

  • Filtering and sorting with query parameters
  • Offset pagination – simple, with known limits
  • Cursor pagination – stable and fast
  • Link headers and page-size limits

Filtering, sorting and offset pagination

// server.js
import express from 'express';

const app = express();

const levels = ['beginner', 'intermediate', 'advanced'];
const courses = Array.from({ length: 23 }, (_, i) => ({
  id: i + 1,
  title: `Course ${String(i + 1).padStart(2, '0')}`,
  level: levels[i % 3],
  rating: Number((3 + ((i * 7) % 20) / 10).toFixed(1)),
}));

const SORTABLE = new Set(['title', 'rating']);
const MAX_LIMIT = 50;

app.get('/api/courses', (req, res) => {
  // filter: ?level=beginner&minRating=4
  let rows = courses;
  if (req.query.level) rows = rows.filter((c) => c.level === req.query.level);
  if (req.query.minRating) rows = rows.filter((c) => c.rating >= Number(req.query.minRating));

  // sort: ?sort=-rating,title  (a minus sign means descending)
  const sortKeys = String(req.query.sort ?? 'title').split(',');
  for (const key of sortKeys) {
    if (!SORTABLE.has(key.replace(/^-/, ''))) return res.status(400).json({ error: `Cannot sort by '${key}'` });
  }
  rows = [...rows].sort((a, b) => {
    for (const key of sortKeys) {
      const field = key.replace(/^-/, '');
      const dir = key.startsWith('-') ? -1 : 1;
      if (a[field] < b[field]) return -dir;
      if (a[field] > b[field]) return dir;
    }
    return 0;
  });

  // paginate: ?limit=5&offset=0, with a hard maximum
  const limit = Math.min(Number(req.query.limit ?? 10), MAX_LIMIT);
  const offset = Number(req.query.offset ?? 0);
  const page = rows.slice(offset, offset + limit);

  res.set('X-Total-Count', String(rows.length));
  res.json({
    data: page,
    page: { limit, offset, total: rows.length, hasMore: offset + limit < rows.length },
  });
});

app.listen(process.env.PORT ?? 3000);

Real responses

$ curl 'http://localhost:3000/api/courses?level=advanced&sort=-rating,title&limit=3'
HTTP/1.1 200 OK
X-Total-Count: 7
Content-Type: application/json; charset=utf-8

{
  "data": [
    {
      "id": 18,
      "title": "Course 18",
      "level": "advanced",
      "rating": 4.9
    },
    {
      "id": 15,
      "title": "Course 15",
      "level": "advanced",
      "rating": 4.8
    },
    {
      "id": 12,
      "title": "Course 12",
      "level": "advanced",
      "rating": 4.7
    }
  ],
  "page": {
    "limit": 3,
    "offset": 0,
    "total": 7,
    "hasMore": true
  }
}

$ curl 'http://localhost:3000/api/courses?level=advanced&sort=-rating,title&limit=3&offset=3'
HTTP/1.1 200 OK
X-Total-Count: 7
Content-Type: application/json; charset=utf-8

{
  "data": [
    {
      "id": 9,
      "title": "Course 09",
      "level": "advanced",
      "rating": 4.6
    },
    {
      "id": 6,
      "title": "Course 06",
      "level": "advanced",
      "rating": 4.5
    },
    {
      "id": 3,
      "title": "Course 03",
      "level": "advanced",
      "rating": 4.4
    }
  ],
  "page": {
    "limit": 3,
    "offset": 3,
    "total": 7,
    "hasMore": true
  }
}

$ curl 'http://localhost:3000/api/courses?sort=price'
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8

{
  "error": "Cannot sort by 'price'"
}
  • Allow-list the fields clients can filter and sort by – arbitrary sorting on unindexed columns can bring a database down.
  • Always cap limit. The default should be modest (10–50).
  • Sort by a unique tie-breaker (here title, in a database usually id) so pages are deterministic.

Why offset pagination breaks

The moving-window problem

  1. Page 1client reads rows 1–10, newest first
  2. Meanwhiletwo new rows are inserted at the top
  3. Page 2 (offset=10)now starts at old row 9 – rows 9 and 10 appear twice
  4. And it's slowOFFSET 100000 makes the database read and skip 100,000 rows

Cursor pagination

Instead of "skip N", the client says "continue after this item". The cursor is an opaque token, typically the sort key of the last item, encoded so clients don't depend on its format:

// server.js
import express from 'express';

const app = express();
const events = Array.from({ length: 12 }, (_, i) => ({ id: 100 + i, type: i % 2 ? 'login' : 'purchase' }));

const encode = (id) => Buffer.from(JSON.stringify({ id })).toString('base64url');
const decode = (cursor) => JSON.parse(Buffer.from(cursor, 'base64url').toString()).id;

app.get('/api/events', (req, res) => {
  const limit = Math.min(Number(req.query.limit ?? 5), 100);
  const afterId = req.query.cursor ? decode(String(req.query.cursor)) : 0;
  const rows = events.filter((e) => e.id > afterId).slice(0, limit + 1);   // fetch one extra to know if there's more
  const hasMore = rows.length > limit;
  const data = rows.slice(0, limit);
  const nextCursor = hasMore ? encode(data.at(-1).id) : null;
  if (nextCursor) res.links({ next: `/api/events?limit=${limit}&cursor=${nextCursor}` });
  res.json({ data, nextCursor });
});

app.listen(process.env.PORT ?? 3000);

Real responses

$ curl 'http://localhost:3000/api/events?limit=5'
HTTP/1.1 200 OK
Link: </api/events?limit=5&cursor=eyJpZCI6MTA0fQ>; rel="next"
Content-Type: application/json; charset=utf-8

{
  "data": [
    {
      "id": 100,
      "type": "purchase"
    },
    {
      "id": 101,
      "type": "login"
    },
    {
      "id": 102,
      "type": "purchase"
    },
    {
      "id": 103,
      "type": "login"
    },
    {
      "id": 104,
      "type": "purchase"
    }
  ],
  "nextCursor": "eyJpZCI6MTA0fQ"
}

$ curl 'http://localhost:3000/api/events?limit=5&cursor=eyJpZCI6MTA0fQ'
HTTP/1.1 200 OK
Link: </api/events?limit=5&cursor=eyJpZCI6MTA5fQ>; rel="next"
Content-Type: application/json; charset=utf-8

{
  "data": [
    {
      "id": 105,
      "type": "login"
    },
    {
      "id": 106,
      "type": "purchase"
    },
    {
      "id": 107,
      "type": "login"
    },
    {
      "id": 108,
      "type": "purchase"
    },
    {
      "id": 109,
      "type": "login"
    }
  ],
  "nextCursor": "eyJpZCI6MTA5fQ"
}

$ curl 'http://localhost:3000/api/events?limit=5&cursor=eyJpZCI6MTA5fQ'
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{
  "data": [
    {
      "id": 110,
      "type": "purchase"
    },
    {
      "id": 111,
      "type": "login"
    }
  ],
  "nextCursor": null
}

In SQL this becomes WHERE id > :afterId ORDER BY id LIMIT :limit + 1 – an index seek that's equally fast on page 1 and page 10,000, and inserts never shift pages. The Link header gives the next URL in a standard way.

OffsetCursor
Jump to page 37✔ easy✗ only next/previous
Total counteasy (but expensive on huge tables)usually omitted
Stable while data changes✗ duplicates or gaps✔
Performance on deep pages✗ gets slower✔ constant
Good foradmin tables, small datasetsfeeds, infinite scroll, sync, large tables, public APIs (Stripe, Slack)

Practice

Try it yourself

  1. A client calls ?limit=10000. What should happen, and why?

    Show answer

    Clamp it to your maximum (for example 100) and report the real limit in the response, or reject it with 400 and a clear message. Unbounded page sizes let a single request exhaust memory and database time.

Quick check

Why fetch limit + 1 rows in cursor pagination?

To know whether another page exists without a COUNT query.

Why should cursors be opaque?

So you can change how they're built without breaking clients.

Which style suits an infinite-scroll feed?

Cursor pagination.

Summary

  • Filter and sort with allow-listed query parameters; sort with a unique tie-breaker.
  • Offset pagination is simple but unstable and slow on deep pages; cursor pagination fixes both.
  • Cap page sizes, and expose next links in the body and/or a Link header.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links