How to Implement Pagination in REST API: Simple Guide
To implement pagination in a
REST API, use query parameters like page and limit to control which subset of data is returned. The server responds with only the requested page of results, improving performance and usability.Syntax
Pagination in REST APIs typically uses query parameters to specify the page number and the number of items per page.
page: The current page number (starting from 1).limit: The number of items to return per page.
Example URL: /items?page=2&limit=10 returns the second page with 10 items.
http
GET /items?page=2&limit=10 HTTP/1.1 Host: api.example.com
Example
This example shows a simple REST API endpoint in Node.js using Express that implements pagination with page and limit query parameters.
javascript
const express = require('express'); const app = express(); // Sample data array const items = Array.from({ length: 50 }, (_, i) => ({ id: i + 1, name: `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, totalPages: Math.ceil(items.length / limit), data: paginatedItems }); }); app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Common Pitfalls
Common mistakes when implementing pagination include:
- Not validating
pageandlimitvalues, which can cause errors or unexpected results. - Returning all data without limiting, which defeats pagination's purpose.
- Using zero-based page numbers without clear documentation, confusing clients.
- Not including total count or total pages in the response, making it hard for clients to know when to stop.
Always validate inputs and provide helpful metadata in the response.
javascript
/* Wrong way: No validation and returns all items */ app.get('/items', (req, res) => { const page = req.query.page; // no parseInt or default const limit = req.query.limit; // no parseInt or default // Returns all items ignoring pagination res.json({ data: items }); }); /* Right way: Validate and paginate */ app.get('/items', (req, res) => { const page = Math.max(1, parseInt(req.query.page) || 1); const limit = Math.min(100, Math.max(1, 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, totalPages: Math.ceil(items.length / limit), data: paginatedItems }); });
Quick Reference
- Use
pageandlimitquery parameters for pagination. - Validate and sanitize input values to avoid errors.
- Return metadata like
totalItemsandtotalPagesto help clients. - Use slicing or database queries with
OFFSETandLIMITfor efficient data retrieval.
Key Takeaways
Use query parameters like
page and limit to control pagination in REST APIs.Always validate and sanitize pagination inputs to prevent errors and abuse.
Include helpful metadata such as total items and total pages in the API response.
Implement pagination logic using array slicing or database queries with OFFSET and LIMIT.
Clear documentation on pagination behavior helps API users avoid confusion.