Skip to content
IRC-CodingIRC-Coding
PaginationFilteringSortingOffset PaginationCursor PaginationKeyset PaginationQuery Parameter

API Pagination, Filtering & Sorting Best Practices

Master API pagination, filtering and sorting: offset, cursor, keyset pagination, query design and best practices for efficient APIs.

S

schutzgeist

5 min read
API Pagination, Filtering & Sorting Best Practices

API Pagination, Filtering, and Sorting

Pagination, filtering, and sorting enable APIs to deliver large datasets efficiently, consistently, and in a user-friendly manner.

Overview

Pagination limits the number of records an API returns in a single request, preventing bloated responses that slow down both servers and clients. Filters let you narrow results by specific criteria without requiring separate endpoints. Sorting controls the order of results. Together, these three mechanisms form the foundation of flexible API queries. The most common pagination approaches are offset pagination, cursor pagination, and keyset pagination—each with distinct trade-offs around simplicity, consistency, and performance. Filters and sorting typically use query parameters, with clear naming conventions and documentation being essential. A well-designed API documents its pagination and filtering options clearly and includes helpful metadata in responses such as navigation links, total counts, or cursors.

Key Components

Offset Pagination

Offset pagination uses parameters like page or offset and limit to fetch a slice of results. For example: ?page=2&limit=20. It’s straightforward to implement and understand, but performance degrades with large offset values, and inconsistencies emerge when data changes between page requests.

Cursor Pagination

Cursor pagination uses an opaque cursor based on a sorted value—for example, ?cursor=abc123&limit=20. It outperforms offset pagination on large datasets and handles consistency better. The trade-off is that jumping to arbitrary pages becomes harder, and it depends on a stable, unique sort order.

Keyset Pagination

Keyset pagination resembles cursor pagination but uses explicit values like ?createdAfter=2026-07-01T00:00:00Z&limit=20. It’s highly performant and stable, though less flexible when multiple sort fields are involved. It works particularly well for time-ordered data streams.

Page and Limit

page and limit are the classic offset pagination parameters. page specifies which page to retrieve, while limit sets how many items per page. Typical defaults are page=1 and limit=20. APIs should enforce a maximum limit to prevent abuse.

Responses should include metadata that aids navigation: total, page, limit, next, prev, first, and last. HATEOAS links help clients navigate pages without manually constructing URLs.

Filter Parameters

Filters typically use query parameters. Examples include ?status=active, ?category=books, or ?minPrice=10&maxPrice=50. Filter names should be meaningful, well-documented, and validated. Boolean combinations can be expressed through separate parameters or a dedicated filter query syntax.

Sorting

Sorting is often controlled by parameters like sort or orderBy. Examples are ?sort=name or ?sort=-createdAt, where a leading minus denotes descending order. Clear conventions and documentation ensure clients use the API correctly.

Search Parameters

Full-text search typically uses a parameter like q or search, for instance ?q=python. More complex searches can leverage dedicated services like Elasticsearch or OpenSearch, exposed through a dedicated search API.

Combining Filters, Sorting, and Pagination

In practice, all three are often used together. For example: ?status=active&sort=-createdAt&page=1&limit=25. The API must combine, validate, and document these parameters sensibly, keeping the order of operations consistent.

Limits and Defaults

A reasonable default limit reduces data volume and response time, while a maximum limit prevents overly large requests. Clients should be able to choose a limit within permitted bounds.

Consistency with Growing Data

When data changes during pagination, records can appear twice or be skipped entirely. Cursor and keyset pagination are more stable than offset pagination in this regard. With offset pagination, clients should expect inconsistencies, or the API should use snapshots.

Practical Example

Consider an API for products that supports offset pagination, filtering, and sorting.

Request:

GET /api/v1/products?category=electronics&minPrice=100&sort=-rating&page=2&limit=10

Response:

{
  "data": [
    { "id": 15, "name": "Laptop", "price": 999, "rating": 4.8 },
    { "id": 22, "name": "Monitor", "price": 299, "rating": 4.7 }
  ],
  "pagination": {
    "page": 2,
    "limit": 10,
    "total": 145,
    "pages": 15,
    "next": "/api/v1/products?category=electronics&minPrice=100&sort=-rating&page=3&limit=10",
    "prev": "/api/v1/products?category=electronics&minPrice=100&sort=-rating&page=1&limit=10"
  }
}

The client can navigate using the provided links without reconstructing filters and sorting.

FAQ: Pagination, Filtering, and Sorting

1. What is pagination in APIs?

Pagination limits the number of records an API returns per request. It prevents large, slow responses and reduces load on both servers and clients.

2. What is offset pagination?

Offset pagination uses parameters like page and limit to fetch a slice of results. It’s simple to implement but performs poorly with large offsets and suffers from consistency issues when data changes between requests.

3. What is cursor pagination?

Cursor pagination uses an opaque cursor to load the next page. It performs better and is more stable than offset pagination on large datasets, but it’s less flexible for jumping to arbitrary pages.

4. What is keyset pagination?

Keyset pagination uses explicit values like createdAfter or lastId to load the next page. It’s highly performant and particularly suited to time-ordered data streams.

5. What is a default limit?

A default limit is the standard number of items per page when the client doesn’t specify one. Typical values are 20 or 50.

6. What are HATEOAS links in pagination?

HATEOAS links in pagination provide URLs for the next, previous, first, and last pages. They allow clients to navigate without manually constructing URLs.

7. What is a filter parameter?

A filter parameter is a query parameter that narrows results by a specific criterion, such as ?status=active or ?category=books.

8. What is a sort parameter?

A sort parameter controls the order of results, like ?sort=name or ?sort=-createdAt for descending order. Clear conventions are essential.

9. What is a search parameter?

A search parameter like q or search enables full-text search via the API. Complex searches are often handled through dedicated search APIs using Elasticsearch or OpenSearch.

10. Why is pagination important for performance?

Pagination reduces data per request, lowering latency and memory use while easing the load on databases and networks. Without it, large queries can overwhelm both servers and clients.

11. What is a maximum limit?

A maximum limit is the upper bound on items per page. It prevents clients from requesting excessively large responses and protects the API from overload.

12. What is inconsistency in pagination?

Inconsistency occurs when data changes between page requests, causing records to appear twice or be skipped. Cursor pagination is less prone to this than offset pagination.

13. What is total count in paginated responses?

Total count is the total number of records matching the filter criteria. It helps clients determine the total number of pages and the scope of results.

14. How should you document filters and sorting?

Filters and sorting should be clearly documented in OpenAPI or your API documentation, including allowed parameters, data types, defaults, valid values, and examples.

15. What are best practices for pagination, filtering, and sorting?

Best practices include choosing the appropriate pagination strategy, setting sensible default and maximum limits, using descriptive parameter names, maintaining stable sort criteria, providing helpful navigation links, documenting clearly, and validating all parameters thoroughly.

References

  1. https://www.rfc-editor.org/rfc/rfc8288
  2. https://www.martinfowler.com/articles/patterns-of-distributed-systems/pagination.html
  3. https://use-the-index-luke.com/no-offset

Further Reading on API Design

If you’d like to deepen your knowledge of API design, data querying, and software architecture, here are some books worth exploring:

API Development

Books about API design, REST, GraphQL, OpenAPI and API architecture

Designing Data-Intensive Applications von Martin Kleppmann

Designing Data-Intensive Applications von Martin Kleppmann

Bei Amazon ansehen

Affiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.

API Design Patterns von JJ Geewax

API Design Patterns von JJ Geewax

Bei Amazon ansehen

Affiliate-Link: Bei einem Kauf erhalten wir möglicherweise eine Provision.

Back to Blog
Share:

Related Posts