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
pageandlimitare 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
limitvalues 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
| Parameter | Description | Example Value |
|---|---|---|
| page | The page number to retrieve (1-based) | 2 |
| limit | Number of items per page | 10 |
| startIndex | Calculated start index for slicing data | (page - 1) * limit |
| endIndex | Calculated end index for slicing data | page * 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.