Pagination Overview
When an API returns large collections, sending all items at once is impractical. Pagination breaks responses into manageable chunks.
Why Paginate?
Without pagination:
- Performance: Large responses are slow to generate and transfer
- Memory: Server and client may run out of memory
- User Experience: Users don't need 10,000 items at once
- Cost: Bandwidth and processing costs increase
Pagination Parameters
Common Parameters
GET /api/users?page=2&limit=20
GET /api/users?offset=40&limit=20
GET /api/users?cursor=abc123&limit=20
| Parameter | Description |
|---|---|
page | Page number (1-indexed) |
limit / per_page | Items per page |
offset | Number of items to skip |
cursor | Pointer to position in dataset |
Pagination Response
Include Metadata
{
"data": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
],
"meta": {
"page": 2,
"perPage": 20,
"total": 150,
"totalPages": 8
},
"links": {
"first": "/api/users?page=1&limit=20",
"prev": "/api/users?page=1&limit=20",
"next": "/api/users?page=3&limit=20",
"last": "/api/users?page=8&limit=20"
}
}
Minimal Response
{
"data": [...],
"hasMore": true,
"nextCursor": "abc123"
}
Exercise: Implement Basic Pagination
Loading JavaScript Exercise...
Default Values
Set sensible defaults:
// Server defaults
const page = req.query.page || 1;
const limit = Math.min(req.query.limit || 20, 100); // Max 100
Best Practices
1. Set Maximum Page Size
GET /api/users?limit=10000 // Bad request!
HTTP/1.1 400 Bad Request
{ "error": "Maximum page size is 100" }
2. Handle Invalid Pages Gracefully
GET /api/users?page=999 // Page doesn't exist
// Option 1: Return empty data
{ "data": [], "meta": { "page": 999, "total": 50 } }
// Option 2: Return 404
HTTP/1.1 404 Not Found
{ "error": "Page 999 does not exist" }
3. Use 1-Indexed Pages
Pages starting at 1 are more intuitive for users:
GET /api/users?page=1 // First page (not page=0)
4. Include Navigation Links
HATEOAS-style links help clients navigate:
{
"links": {
"self": "/api/users?page=3",
"first": "/api/users?page=1",
"prev": "/api/users?page=2",
"next": "/api/users?page=4",
"last": "/api/users?page=10"
}
}
Summary
| Aspect | Recommendation |
|---|---|
| Default page size | 20-50 items |
| Maximum page size | 100 items |
| Page numbering | 1-indexed |
| Always include | total count, page info |
| Optional | navigation links |
Pagination is essential for any API returning collections. In the next lesson, we'll explore different pagination strategies in detail.
التالي · الدرس 20 من 37
Pagination Patterns
قراءة 4 دقيقة
أنهيت 19 من 37 درسًا

اسأل Byte عن هذا الدرس
محادثة خاصة حول هذا الدرس. قرأ Byte الدرس كاملًا، ويجيب خلال ثوانٍ، ويُظهر القسم الذي تأتي منه كل إجابة. يمكنك السؤال بأي لغة.
الأسئلة والأجوبة
أسئلة عامة حول هذا الدرس. يجيب AI Tutor فورًا بلغتك، ويراجع فريق FreeAcademy الإجابات، ويمكن لكل المتعلمين قراءتها.

