Skip to main content
coding intermediate

Implement API Pagination System

Generate complete API pagination code with offset, cursor, or page-based approaches. Includes error handling and best practices.

Works with: chatgptclaudegemini

Prompt Template

I need to implement pagination for a REST API endpoint. Please provide a complete implementation with the following requirements: **API Details:** - Programming language/framework: [PROGRAMMING_LANGUAGE] - Database type: [DATABASE_TYPE] - Resource being paginated: [RESOURCE_TYPE] - Pagination method: [PAGINATION_METHOD] (offset-based, cursor-based, or page-based) **Requirements:** 1. Handle pagination parameters in query strings 2. Return paginated data with metadata (total count, current page, etc.) 3. Include proper error handling for invalid parameters 4. Implement database query optimization 5. Add response headers for pagination info 6. Include input validation and sanitization 7. Handle edge cases (empty results, out-of-range pages) **Additional Specifications:** - Default page size: [DEFAULT_PAGE_SIZE] - Maximum allowed page size: [MAX_PAGE_SIZE] - Include sorting capability: [SORTING_FIELDS] Please provide: 1. Complete API endpoint implementation 2. Database query logic with optimization 3. Response format with pagination metadata 4. Error handling code 5. Usage examples with sample requests/responses 6. Performance considerations and best practices Ensure the code follows RESTful conventions and includes comprehensive comments explaining the pagination logic.

Variables to Customize

[PROGRAMMING_LANGUAGE]

The programming language and framework to use

Example: Node.js with Express

[DATABASE_TYPE]

The database system being used

Example: PostgreSQL

[RESOURCE_TYPE]

The type of data being paginated

Example: user profiles

[PAGINATION_METHOD]

The pagination approach to implement

Example: offset-based

[DEFAULT_PAGE_SIZE]

Default number of items per page

Example: 20

[MAX_PAGE_SIZE]

Maximum allowed items per page

Example: 100

[SORTING_FIELDS]

Fields that can be used for sorting

Example: created_at, name, email

Example Output

```javascript const express = require('express'); const { Pool } = require('pg'); const router = express.Router(); const pool = new Pool(/* your config */); // GET /api/users - Paginated user profiles endpoint router.get('/users', async (req, res) => { try { // Parse and validate pagination parameters const page = Math.max(1, parseInt(req.query.page) || 1); const limit = Math.min(100, Math.max(1, parseInt(req.query.limit) || 20)); const offset = (page - 1) * limit; const sortBy = ['created_at', 'name', 'email'].includes(req.query.sort) ? req.query.sort : 'created_at'; const order = req.query.order === 'desc' ? 'DESC' : 'ASC'; // Get total count for metadata const countQuery = 'SELECT COUNT(*) FROM users WHERE active = true'; const countResult = await pool.query(countQuery); const totalItems = parseInt(countResult.rows[0].count); const totalPages = Math.ceil(totalItems / limit); // Validate page range if (page > totalPages && totalItems > 0) { return res.status(400).json({ error: 'Page number exceeds available pages', maxPage: totalPages }); } // Fetch paginated data const dataQuery = ` SELECT id, name, email, created_at FROM users WHERE active = true ORDER BY ${sortBy} ${order} LIMIT $1 OFFSET $2 `; const dataResult = await pool.query(dataQuery, [limit, offset]); // Build response with pagination metadata const response = { data: dataResult.rows, pagination: { currentPage: page, totalPages, totalItems, itemsPerPage: limit, hasNextPage: page < totalPages, hasPreviousPage: page > 1 } }; // Add pagination headers res.set({ 'X-Total-Count': totalItems.toString(), 'X-Total-Pages': totalPages.toString(), 'X-Current-Page': page.toString() }); res.json(response); } catch (error) { res.status(500).json({ error: 'Internal server error' }); } }); ```

Pro Tips for Best Results

  • Always validate and sanitize pagination parameters to prevent SQL injection and invalid queries
  • Include total count in responses but consider caching it for large datasets to improve performance
  • Set reasonable default and maximum page sizes to prevent resource exhaustion
  • Use database indexes on frequently sorted columns to optimize pagination queries
  • Consider cursor-based pagination for real-time data or very large datasets where offset becomes inefficient

Tags

Want 500+ Expert Prompts?

Get the Premium Prompt Pack — organized, tested, and ready to use.

Get it for $29

Related Prompts You Might Like