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

How to Use Page and Limit in API for Pagination

Use page to specify which page of results you want and limit to set how many items appear per page in your API request. These parameters help divide large data into smaller, manageable parts called pages.
๐Ÿ“

Syntax

The typical syntax for using page and limit in an API request URL looks like this:

https://api.example.com/items?page=2&limit=10

Here, page is the page number you want to retrieve, and limit is the number of items per page.

http
GET /items?page=2&limit=10 HTTP/1.1
Host: api.example.com
๐Ÿ’ป

Example

This example shows a simple API endpoint in Node.js using Express that supports page and limit query parameters to paginate a list of items.

javascript
const express = require('express');
const app = express();

const items = Array.from({ length: 50 }, (_, i) => `Item ${i + 1}`);

app.get('/items', (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;

  const startIndex = (page - 1) * limit;
  const endIndex = page * limit;

  const paginatedItems = items.slice(startIndex, endIndex);

  res.json({
    page,
    limit,
    totalItems: items.length,
    items: paginatedItems
  });
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
โš ๏ธ

Common Pitfalls

  • Not validating inputs: Forgetting to check if page and limit are positive integers can cause errors or unexpected results.
  • Off-by-one errors: Using zero-based page numbers instead of one-based can confuse users.
  • Ignoring total count: Not returning total items or total pages makes it hard for clients to know when to stop requesting.
  • Large limits: Allowing very large limit values can overload the server or slow down responses.

Example of wrong and right usage:

javascript
// Wrong: No validation, zero-based page
const page = parseInt(req.query.page) || 0; // zero-based
const limit = parseInt(req.query.limit) || 1000; // too large

// Right: Validate and set defaults
const page = Math.max(parseInt(req.query.page) || 1, 1);
const limit = Math.min(Math.max(parseInt(req.query.limit) || 10, 1), 100); // limit max 100
๐Ÿ“Š

Quick Reference

ParameterDescriptionExample Value
pageThe page number to retrieve (1-based)2
limitNumber of items per page10
startIndexCalculated start index for slicing data(page - 1) * limit
endIndexCalculated end index for slicing datapage * limit
โœ…

Key Takeaways

Use page and limit query parameters to paginate API results efficiently.
Always validate page and limit to avoid errors and server overload.
Return total item count to help clients understand pagination limits.
Use one-based page numbering to match common user expectations.
Limit the maximum limit value to protect server performance.