Skip to content

Pagination

List endpoints in the Cashfin Business API support pagination to efficiently handle large datasets.

Query Parameters

ParameterTypeDefaultDescription
pageinteger1Page number (1-indexed)
limitinteger10Items per page (max: 100)

Example Request

bash
GET /business/product/list?page=2&limit=20

Paginated Response

json
{
  "success": true,
  "data": [
    {
      "_id": "507f1f77bcf86cd799439011",
      "title": "Product 21",
      "price": 999.99
    },
    {
      "_id": "507f191e810c19729de860ea",
      "title": "Product 22",
      "price": 1299.99
    }
    // ... more items
  ],
  "meta": {
    "total": 150,
    "page": 2,
    "limit": 20,
    "pages": 8
  }
}

Pagination Metadata

FieldDescription
totalTotal number of records matching the query
pageCurrent page number
limitNumber of records per page
pagesTotal number of pages

Implementation Examples

JavaScript - Fetching All Pages

javascript
async function fetchAllProducts() {
  const allProducts = [];
  let page = 1;
  let hasMore = true;

  while (hasMore) {
    const response = await fetch(
      `https://api.cashfin.africa/business/product/list?page=${page}&limit=100`,
      { headers: { Authorization: API_KEY } }
    );

    const result = await response.json();

    if (result.success) {
      allProducts.push(...result.data);
      hasMore = page < result.meta.pages;
      page++;
    } else {
      break;
    }
  }

  return allProducts;
}

JavaScript - Pagination Component

javascript
async function getProductPage(page = 1, limit = 10) {
  const response = await fetch(
    `https://api.cashfin.africa/business/product/list?page=${page}&limit=${limit}`,
    { headers: { Authorization: API_KEY } }
  );

  const result = await response.json();

  return {
    products: result.data,
    pagination: {
      currentPage: result.meta.page,
      totalPages: result.meta.pages,
      totalItems: result.meta.total,
      hasNext: result.meta.page < result.meta.pages,
      hasPrev: result.meta.page > 1,
    },
  };
}

// Usage
const { products, pagination } = await getProductPage(1, 20);
console.log(
  `Showing page ${pagination.currentPage} of ${pagination.totalPages}`
);

PHP - Pagination Helper

php
<?php
function getProductPage(int $page = 1, int $limit = 10): array
{
    $apiKey = getenv('CASHFIN_API_KEY');

    $url = "https://api.cashfin.africa/business/product/list?" .
           http_build_query(['page' => $page, 'limit' => $limit]);

    $response = file_get_contents($url, false, stream_context_create([
        'http' => ['header' => "Authorization: {$apiKey}"]
    ]));

    $result = json_decode($response, true);

    return [
        'products' => $result['data'],
        'meta' => $result['meta'],
        'hasNext' => $result['meta']['page'] < $result['meta']['pages'],
        'hasPrev' => $result['meta']['page'] > 1
    ];
}

Python - Async Pagination

python
import asyncio
import aiohttp

async def fetch_all_products():
    all_products = []
    page = 1

    async with aiohttp.ClientSession() as session:
        while True:
            async with session.get(
                f'https://api.cashfin.africa/business/product/list?page={page}&limit=100',
                headers={'Authorization': API_KEY}
            ) as response:
                result = await response.json()

                if not result['success']:
                    break

                all_products.extend(result['data'])

                if page >= result['meta']['pages']:
                    break
                page += 1

    return all_products

Best Practices

1. Use Appropriate Page Sizes

javascript
// For list views with quick loading
const quickList = await getProducts({ page: 1, limit: 10 });

// For data exports or sync operations
const fullExport = await getProducts({ page: 1, limit: 100 });

2. Cache Page Results

javascript
const pageCache = new Map();

async function getCachedPage(page, limit = 10) {
  const cacheKey = `products-${page}-${limit}`;

  if (pageCache.has(cacheKey)) {
    return pageCache.get(cacheKey);
  }

  const result = await getProductPage(page, limit);
  pageCache.set(cacheKey, result);

  return result;
}

3. Handle Empty Pages Gracefully

javascript
async function getProducts(page = 1) {
  const result = await getProductPage(page);

  if (result.products.length === 0 && page > 1) {
    // Requested page beyond available data
    return getProductPage(1); // Return to first page
  }

  return result;
}

4. Implement Infinite Scroll

javascript
let currentPage = 1;
let isLoading = false;
let hasMoreData = true;

async function loadMore() {
  if (isLoading || !hasMoreData) return;

  isLoading = true;

  const { products, pagination } = await getProductPage(currentPage);

  appendProducts(products);

  hasMoreData = pagination.hasNext;
  currentPage++;
  isLoading = false;
}

// Trigger on scroll
window.addEventListener("scroll", () => {
  if (
    window.innerHeight + window.scrollY >=
    document.body.offsetHeight - 1000
  ) {
    loadMore();
  }
});

Limits

ConstraintValue
Maximum limit100
Default limit10
Minimum page1

WARNING

Requesting a limit greater than 100 will automatically be capped at 100.

Filtering with Pagination

Pagination works alongside filtering:

bash
GET /business/product/list?status=published&page=1&limit=20

The meta.total reflects the total matching the filter, not the total in the database.

Cashfin Business API Documentation