How to Design Pagination Response in REST API
Design a pagination response by including
items for the current page data, page and page_size to show current position, and total_pages or total_items for navigation. Use next and previous URLs for easy client navigation between pages.Syntax
A typical pagination response includes these parts:
- items: The list of data for the current page.
- page: The current page number.
- page_size: How many items per page.
- total_items: Total number of items available.
- total_pages: Total number of pages.
- next: URL to the next page, or
nullif none. - previous: URL to the previous page, or
nullif none.
json
{
"items": [ ... ],
"page": 1,
"page_size": 10,
"total_items": 95,
"total_pages": 10,
"next": "https://api.example.com/data?page=2",
"previous": null
}Example
This example shows a simple REST API response for page 2 with 3 items per page out of 7 total items.
json
{
"items": [
{"id": 4, "name": "Item 4"},
{"id": 5, "name": "Item 5"},
{"id": 6, "name": "Item 6"}
],
"page": 2,
"page_size": 3,
"total_items": 7,
"total_pages": 3,
"next": "https://api.example.com/items?page=3",
"previous": "https://api.example.com/items?page=1"
}Common Pitfalls
Common mistakes when designing pagination responses include:
- Not including
total_itemsortotal_pages, which makes it hard for clients to know how many pages exist. - Using inconsistent or missing
nextandpreviousURLs, confusing navigation. - Returning all items without limiting page size, causing slow responses.
- Not validating page numbers, leading to errors or empty results.
json
Wrong example:
{
"items": [ ... ],
"page": 5
// Missing total_pages and next/previous URLs
}
Right example:
{
"items": [ ... ],
"page": 5,
"page_size": 10,
"total_items": 50,
"total_pages": 5,
"next": null,
"previous": "https://api.example.com/data?page=4"
}Quick Reference
| Field | Description | Example |
|---|---|---|
| items | List of data for the current page | [{"id":1, "name":"A"}, {...}] |
| page | Current page number | 2 |
| page_size | Number of items per page | 10 |
| total_items | Total number of items available | 95 |
| total_pages | Total number of pages | 10 |
| next | URL to next page or null | "https://api.example.com/data?page=3" |
| previous | URL to previous page or null | "https://api.example.com/data?page=1" |
Key Takeaways
Always include current page, page size, and total items or pages in the response.
Provide next and previous URLs for easy client navigation.
Limit the number of items per page to keep responses fast.
Validate page parameters to avoid errors or empty results.
Keep the response structure consistent and clear for clients.