Handling pagination and sorting

Last updated: 3 months ago

The API returns search results in pages. Here's how to efficiently navigate through large result sets.

Basic pagination

POST /resources
{
  "query": "saints",
  "page": 1,
  "page_size": 20
}
Response:
{
  "total": 1523,
  "page": 1,
  "page_size": 20,
  "results": [ ... 20 items ... ]
}

The response tells you there are 1,523 total results, and you're viewing page 1 with 20 items.

Calculating total pages

const totalPages = Math.ceil(response.total / response.page_size);
// 1523 / 20 = 76.15 → 77 pages

Loading next page

// Simple next page
currentPage++;
// Or build pagination UI
for (let page = 1; page <= totalPages; page++) {
  // Create page button
}

Optimizing page size

Choose page size based on your use case:

Small pages (10-20 items):

  • Faster initial load

  • Good for user-facing search

  • More API requests needed

Large pages (50-100 items):

  • Fewer API requests

  • Good for batch processing

  • Slower individual requests

  • Maximum is 100 items

Sorting options

Popular (default):

{
  "order": "popular"
}

Returns most downloaded resources first. Best for showing high-quality, proven content.

Recent:

{
  "order": "recent"
}

Returns newest uploads first. Good for discovering fresh content.

Infinite scroll example

let currentPage = 1;
const pageSize = 20;
let isLoading = false;
let hasMore = true;
async function loadMore() {
  if (isLoading || !hasMore) return;
  
  isLoading = true;
  
  const response = await fetch('https://api.cathopic.com/resources', {
    method: 'POST',
    headers: {
      'x-api-key': apiKey,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      query: 'prayer',
      page: currentPage,
      page_size: pageSize,
      order: 'popular'
    })
  });
  
  const data = await response.json();
  
  // Add results to your UI
  appendResults(data.results);
  
  // Check if there are more pages
  const totalPages = Math.ceil(data.total / pageSize);
  hasMore = currentPage < totalPages;
  
  currentPage++;
  isLoading = false;
}
// Trigger on scroll
window.addEventListener('scroll', () => {
  if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500) {
    loadMore();
  }
});

Performance tips

  • Cache results locally to avoid redundant requests

  • Use appropriate page sizes for your use case

  • Implement loading states for better UX

  • Consider virtualization for very large lists

  • Don't fetch all pages at once - load on demand

For more details, see the full documentation at api.cathopic.com/docs.

Was this article helpful?