- Home
- API Design
- How To Paginate Rest API Respo ...
What is pagination?
Pagination is an ordinal numbering of pages, which is usually located at the top or bottom of the site pages. It is used for main pages and partitions. Pagination is how you move between the pages when you don’t want to retrieve all the results at once.
Why use pagination?
- Better user experience
- Stateless on the server.
- Easy & simple to implement.
- Easier navigation
Pagination Methods
1. Offset Pagination
Offset pagination is one of the simplest to implement. It is implemented by two parameters, Limit and Offset. This is the simplest form of paging. Limit/Offset became popular with apps using SQL databases that already have LIMIT and OFFSET as part of the SQL SELECT Syntax. This query returns the 20 rows starting with the 100th row.
Example
- GET /items?limit=20&offset=40
SELECT * FROM Users ORDER BY Id LIMIT 20 OFFSET 40;
2. Keyset Pagination
Keyset pagination uses the filter values of the previous page to fetch the next set of items.
Those results will then be indexed.
Example
- GET /items?limit=20&created:lte:2021-01-20T00:00:00
SELECT * FROM Items WHERE created <= '2021-01-20T00:00:00' ORDER BY Id LIMIT 20
3. Seek Pagination
Seek Paging is an extension of Keyset paging. Adding the queries after_id and before_id, you can remove the constraints of filters and sort. Unique identifiers are more stable and static than lower cardinality fields such as state enums or category names.
Example
- GET /items?limit=20&after_id=20
SELECT * FROM Items WHERE Id > 20 LIMIT 20