0
0
Rest-apiHow-ToBeginner ยท 4 min read

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 null if none.
  • previous: URL to the previous page, or null if 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_items or total_pages, which makes it hard for clients to know how many pages exist.
  • Using inconsistent or missing next and previous URLs, 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

FieldDescriptionExample
itemsList of data for the current page[{"id":1, "name":"A"}, {...}]
pageCurrent page number2
page_sizeNumber of items per page10
total_itemsTotal number of items available95
total_pagesTotal number of pages10
nextURL to next page or null"https://api.example.com/data?page=3"
previousURL 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.