0
0
Rest APIprogramming~5 mins

Pagination metadata in response in Rest API

Choose your learning style9 modes available
Introduction

Pagination metadata helps you split large lists into smaller parts and tells you about the current page and total pages.

When you have many items and want to show them page by page.
When you want to let users navigate through a list without loading everything at once.
When your app needs to load data faster by fetching small chunks.
When you want to show how many pages or items are left to browse.
Syntax
Rest API
{
  "data": [ ...items... ],
  "pagination": {
    "current_page": 1,
    "per_page": 10,
    "total_items": 100,
    "total_pages": 10
  }
}

The data field holds the current page items.

The pagination object gives info about pages and items.

Examples
This shows page 1 with 2 items per page out of 5 total items.
Rest API
{
  "data": ["apple", "banana"],
  "pagination": {
    "current_page": 1,
    "per_page": 2,
    "total_items": 5,
    "total_pages": 3
  }
}
This shows page 3 with no items (maybe last page is empty).
Rest API
{
  "data": [],
  "pagination": {
    "current_page": 3,
    "per_page": 10,
    "total_items": 25,
    "total_pages": 3
  }
}
Sample Program

This simple API returns items in pages with pagination info.

Try changing page and per_page in the URL to see different results.

Rest API
from flask import Flask, request, jsonify

app = Flask(__name__)

items = [f"item{i}" for i in range(1, 26)]  # 25 items

@app.route('/items')
def get_items():
    page = int(request.args.get('page', 1))
    per_page = int(request.args.get('per_page', 10))
    total_items = len(items)
    total_pages = (total_items + per_page - 1) // per_page
    start = (page - 1) * per_page
    end = start + per_page
    data = items[start:end]
    response = {
        "data": data,
        "pagination": {
            "current_page": page,
            "per_page": per_page,
            "total_items": total_items,
            "total_pages": total_pages
        }
    }
    return jsonify(response)

# To test, run this app and visit /items?page=2&per_page=10
OutputSuccess
Important Notes

Always include total items and total pages so clients know how much data exists.

Use current_page and per_page to control which items to send.

Empty data array means no items on that page, maybe page number is too high.

Summary

Pagination metadata helps break big lists into smaller pages.

It tells clients which page they are on and how many pages exist.

This makes data easier and faster to load and use.