JAVASCRIPT
Implementing Server-Side Pagination for API Data (Offset-Limit)
Efficiently fetch and display large datasets from APIs using server-side pagination with offset and limit parameters in Node.js or similar environments.
// Example using Node.js with 'node-fetch'
const fetch = require('node-fetch'); // or use native fetch in newer Node.js
const BASE_API_URL = 'https://api.example.com/items'; // Replace with your actual API endpoint
const PAGE_SIZE = 10; // Number of items per page
/**
* Fetches a paginated list of items from an API.
* @param {number} pageNumber - The 0-indexed page number to fetch.
* @param {number} pageSize - The number of items per page.
* @returns {Promise<Array<Object>>} A promise that resolves to an array of items.
*/
async function fetchPaginatedData(pageNumber, pageSize = PAGE_SIZE) {
const offset = pageNumber * pageSize;
const url = new URL(BASE_API_URL);
url.searchParams.append('limit', pageSize);
url.searchParams.append('offset', offset);
// Add any other necessary query parameters, e.g., filters, sort_by
// url.searchParams.append('filter', 'active');
try {
const response = await fetch(url.toString());
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`API pagination failed: ${response.status} - ${JSON.stringify(errorData)}`);
}
const data = await response.json();
// Assuming the API returns an array directly, or an object with a 'data' key
return data.items || data;
} catch (error) {
console.error(`Error fetching page ${pageNumber}:`, error.message);
throw error;
}
}
// Example usage:
// (async () => {
// try {
// console.log('Fetching page 0...');
// const page0Data = await fetchPaginatedData(0);
// console.log('Page 0 data (first 3 items):', page0Data.slice(0, 3)); // Display first 3 for brevity
// console.log('
Fetching page 1...');
// const page1Data = await fetchPaginatedData(1);
// console.log('Page 1 data (first 3 items):', page1Data.slice(0, 3)); // Display first 3 for brevity
// // For a real API, you'd check total items and available pages
// // const totalItems = response.headers.get('X-Total-Count'); // If API provides this header
// // const totalPages = Math.ceil(totalItems / PAGE_SIZE);
// } catch (e) {
// console.error('Pagination operation failed:', e);
// }
// })();
How it works: This snippet demonstrates how to implement server-side pagination for API integrations using the `offset` and `limit` (or `pageSize`) parameters. Instead of fetching all data at once, which can be inefficient and slow for large datasets, this approach requests only a specific 'page' of data. The `fetchPaginatedData` function constructs the API URL with the appropriate `limit` (how many items to return) and `offset` (how many items to skip) query parameters, ensuring efficient data retrieval and reducing server load.