Pagination

Learn how to implement pagination in mock APIs with moclojer. Offset/Limit, Cursor-based, Page-based and Link headers (RFC 5988).

Pagination is essential in APIs that return large lists of data. This guide shows how to implement different pagination strategies with moclojer.

Why Paginate?

βœ… Performance: Don't load 10,000 items at once βœ… UX: Better user experience βœ… Bandwidth: Less data transferred βœ… Cost: Less server processing

Without pagination:

GET /users β†’ [10,000 users] 😱

With pagination:

GET /users?page=1&limit=20 β†’ [20 users] βœ…

Pagination Strategies

1. Offset/Limit (Most Common)

Concept: Skip X items, return Y items.

Parameters:

  • limit (or per_page): Quantity per page

  • offset (or skip): How many to skip

Math:

Example:

Usage:


2. Page/Limit (More Intuitive)

Concept: Page number + items per page.

Parameters:

  • page: Page number (starts at 1)

  • limit (or per_page): Items per page

Example:

Usage:


3. Cursor-Based (For Dynamic Feeds)

Concept: Uses a cursor (ID, timestamp) to mark position.

Advantages:

  • Consistent even with new items

  • Perfect for infinite scroll

  • Doesn't allow skipping pages (more secure)

Example:

Usage:


Pagination Metadata

Complete Structure

Pagination Headers


Practical Examples

1. E-commerce API (Products)

Usage:

2. Blog API (Posts with Cursor)

Usage:

3. Comments API (Nested Pagination)

Usage:

4. API with Default Values

Usage:


Standard for pagination navigation via headers:

Format:

Relations:

  • first: First page

  • prev: Previous page

  • next: Next page

  • last: Last page

  • self: Current page

GitHub API Example:


Sorting + Pagination

Usage:


Filters + Pagination

Usage:


Search + Pagination

Usage:


Best Practices

βœ… Do

  1. Always return metadata

  2. Use headers for totals

  3. Provide navigation links

  4. Maximum item limit

  5. Consistency in names

❌ Avoid

  1. Pagination without total

  2. Very high limits

  3. Offset without limit

  4. Broken links


Troubleshooting

Problem: Client doesn't know total pages

Solution: Return totalPages or X-Total-Pages header

Solution: Use template vars correctly

Problem: Pagination + Lost filters

Solution: Preserve all query params in links


Strategy Comparison

Strategy
Pros
Cons
When to Use

Offset/Limit

Simple, allows jumping pages

Inconsistent with changes

Traditional APIs

Page/Limit

Intuitive, easy to understand

Same offset problems

UIs with pagination

Cursor

Consistent, perfect for feeds

Can't jump, more complex

Infinite scroll, feeds


Next Steps

See Also

Last updated

Was this helpful?