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

How to Return Total Count in Pagination for REST APIs

To return the total count in pagination, include a total_count field in your API response alongside the paginated data. This field shows the total number of items available, helping clients understand how many pages exist.
๐Ÿ“

Syntax

A typical paginated API response includes:

  • data: the current page items
  • page: current page number
  • page_size: number of items per page
  • total_count: total number of items available

This helps clients calculate total pages as total_count / page_size.

json
{
  "data": [/* items for current page */],
  "page": 1,
  "page_size": 10,
  "total_count": 57
}
๐Ÿ’ป

Example

This example shows a simple REST API endpoint in Python using Flask that returns paginated data with a total count.

python
from flask import Flask, request, jsonify

app = Flask(__name__)

# Sample data list
items = [f"item_{i}" for i in range(1, 101)]  # 100 items

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

if __name__ == '__main__':
    app.run(debug=True)
โš ๏ธ

Common Pitfalls

Common mistakes when returning total count in pagination include:

  • Not including total_count, leaving clients unaware of total pages.
  • Calculating total_count inefficiently, causing slow responses on large datasets.
  • Returning inconsistent total_count when data changes between requests.

Always ensure total_count matches the full dataset size and optimize queries for performance.

json
## Wrong: Missing total_count
{
  "data": ["item_1", "item_2"],
  "page": 1,
  "page_size": 2
}

## Right: Include total_count
{
  "data": ["item_1", "item_2"],
  "page": 1,
  "page_size": 2,
  "total_count": 100
}
๐Ÿ“Š

Quick Reference

Tips for returning total count in pagination:

  • Always include total_count in your paginated response.
  • Use efficient database queries like COUNT(*) to get total count.
  • Keep pagination parameters consistent: page, page_size, and total_count.
  • Document your API response format clearly for clients.
โœ…

Key Takeaways

Include a total_count field in your paginated API response to show total items.
Calculate total_count efficiently to avoid slow API responses.
Use total_count with page_size to help clients calculate total pages.
Avoid omitting total_count to prevent client confusion about data size.