Pagination
The TakeTheme API uses page-based pagination to efficiently navigate through large collections. This approach provides simple and predictable navigation through result sets.
How It Works
When you request a list endpoint, the API returns:
- A batch of results (default: 25 items)
- Pagination metadata with page information
Response Format
{
"success": true,
"data": [
{ "id": "507f1f77bcf86cd799439011", "name": "Category 1" },
{ "id": "507f191e810c19729de860ea", "name": "Category 2" },
{ "id": "507f1f77bcf86cd799439012", "name": "Category 3" }
],
"pagination": {
"results": [],
"totalResults": 150,
"currentPage": 1,
"page": 1,
"limit": 25,
"lastPage": 6
}
}
Pagination Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
page | integer | 1 | Page number to retrieve |
limit | integer | 25 | Number of items per page |
sortBy | string | varies | Field to sort by (e.g., createdAt) |
sortDirection | string | desc | Sort direction: asc or desc |
Fetching Pages
First Page
To get the first page, make a request without specifying a page:
curl -X GET "https://api.taketheme.com/api/v1/category?limit=25" \
-H "tt-api-key: YOUR_API_KEY"
Specific Page
Use the page parameter to get a specific page:
curl -X GET "https://api.taketheme.com/api/v1/category?page=2&limit=25" \
-H "tt-api-key: YOUR_API_KEY"
Last Page
Calculate the last page from the lastPage field in the pagination response:
curl -X GET "https://api.taketheme.com/api/v1/category?page=6&limit=25" \
-H "tt-api-key: YOUR_API_KEY"
Code Examples
cURL
# Get first page
curl -X GET "https://api.taketheme.com/api/v1/category?limit=10" \
-H "tt-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json"
# Get page 2
curl -X GET "https://api.taketheme.com/api/v1/category?page=2&limit=10" \
-H "tt-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json"
# With sorting
curl -X GET "https://api.taketheme.com/api/v1/category?page=1&limit=10&sortBy=name&sortDirection=asc" \
-H "tt-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json"
JavaScript (axios)
import axios from "axios";
const apiClient = axios.create({
baseURL: "https://api.taketheme.com/api/v1",
headers: {
tt-api-key: ` ${process.env.TAKETHEME_API_KEY}`,
"Content-Type": "application/json",
},
});
async function getAllCategories() {
const categories = [];
let currentPage = 1;
let lastPage = 1;
do {
const response = await apiClient.get("/category", {
params: {
page: currentPage,
limit: 100,
},
});
categories.push(...response.data.data);
lastPage = response.data.pagination.lastPage;
currentPage++;
} while (currentPage <= lastPage);
return categories;
}
// Usage
getAllCategories().then((categories) => {
console.log(`Retrieved ${categories.length} total categories`);
});
JavaScript (fetch)
const API_KEY = process.env.TAKETHEME_API_KEY;
const BASE_URL = "https://api.taketheme.com/api/v1";
async function getAllCategories() {
const categories = [];
let currentPage = 1;
let lastPage = 1;
do {
const url = new URL(`${BASE_URL}/category`);
url.searchParams.set("page", currentPage);
url.searchParams.set("limit", "100");
const response = await fetch(url, {
headers: {
tt-api-key: ` ${API_KEY}`,
"Content-Type": "application/json",
},
});
const result = await response.json();
categories.push(...result.data);
lastPage = result.pagination.lastPage;
currentPage++;
} while (currentPage <= lastPage);
return categories;
}
Python
import requests
import os
API_KEY = os.environ['TAKETHEME_API_KEY']
BASE_URL = 'https://api.taketheme.com/api/v1'
def get_all_categories():
categories = []
current_page = 1
last_page = 1
while current_page <= last_page:
response = requests.get(
f'{BASE_URL}/category',
headers={'tt-api-key': f'{API_KEY}'},
params={
'page': current_page,
'limit': 100
}
)
result = response.json()
categories.extend(result['data'])
last_page = result['pagination']['lastPage']
current_page += 1
return categories
# Usage
categories = get_all_categories()
print(f'Retrieved {len(categories)} total categories')
PHP
<?php
$apiKey = getenv('TAKETHEME_API_KEY');
$baseUrl = 'https://api.taketheme.com/api/v1';
function getAllCategories($apiKey, $baseUrl) {
$categories = [];
$currentPage = 1;
$lastPage = 1;
do {
$url = $baseUrl . '/category?' . http_build_query([
'page' => $currentPage,
'limit' => 100
]);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'tt-api-key: ' . $apiKey,
'Content-Type: application/json'
]
]);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
$categories = array_merge($categories, $result['data']);
$lastPage = $result['pagination']['lastPage'];
$currentPage++;
} while ($currentPage <= $lastPage);
return $categories;
}
$categories = getAllCategories($apiKey, $baseUrl);
echo "Retrieved " . count($categories) . " total categories\n";
.NET (C#)
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
public class TakeThemeClient
{
private readonly HttpClient _httpClient;
private const string BaseUrl = "https://api.taketheme.com/api/v1";
public TakeThemeClient(string apiKey)
{
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", apiKey);
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<List<JObject>> GetAllCategoriesAsync()
{
var categories = new List<JObject>();
int currentPage = 1;
int lastPage = 1;
do
{
var url = $"{BaseUrl}/category?page={currentPage}&limit=100";
var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(content);
var data = result["data"] as JArray;
foreach (var item in data)
{
categories.Add(item as JObject);
}
lastPage = result["pagination"]["lastPage"].Value<int>();
currentPage++;
} while (currentPage <= lastPage);
return categories;
}
}
// Usage
var apiKey = Environment.GetEnvironmentVariable("TAKETHEME_API_KEY");
var client = new TakeThemeClient(apiKey);
var categories = await client.GetAllCategoriesAsync();
Console.WriteLine($"Retrieved {categories.Count} total categories");
Best Practices
Use Appropriate Page Sizes
// ✓ Good: Reasonable page size for UI
const uiResponse = await fetch("/api/v1/category?limit=25");
// ✓ Good: Larger batches for background processing
const syncResponse = await fetch("/api/v1/category?limit=100");
// ✗ Avoid: Very small pages (too many requests)
const response = await fetch("/api/v1/category?limit=5");
Handle Empty Results
const result = await fetchCategories(page);
if (result.data.length === 0) {
console.log("No more categories to process");
return;
}
// Process categories...
Implement Rate Limit Handling
async function fetchWithRetry(url, options, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
const response = await fetch(url, options);
if (response.status === 429) {
const retryAfter = response.headers.get("Retry-After") || 1;
await sleep(retryAfter * 1000);
continue;
}
return response;
}
throw new Error("Max retries exceeded");
}
Track Progress for Long Operations
async function syncAllCategories() {
let currentPage = 1;
let lastPage = 1;
let totalProcessed = 0;
do {
const result = await fetchCategories(currentPage);
// Process batch
await processBatch(result.data);
totalProcessed += result.data.length;
console.log(
`Processed page ${currentPage}/${result.pagination.lastPage} ` +
`(${totalProcessed}/${result.pagination.totalResults} items)`
);
lastPage = result.pagination.lastPage;
currentPage++;
} while (currentPage <= lastPage);
console.log(`Sync complete! Processed ${totalProcessed} categories`);
}
Sorting & Filtering
Pagination works with sorting and filtering:
# Paginate through filtered results
curl -X GET "https://api.taketheme.com/api/v1/category?q=electronics&page=1&limit=25" \
-H "tt-api-key: YOUR_API_KEY"
# Paginate with custom sort order
curl -X GET "https://api.taketheme.com/api/v1/category?sortBy=name&sortDirection=asc&page=1&limit=25" \
-H "tt-api-key: YOUR_API_KEY"
Pagination Metadata
| Field | Type | Description |
|---|---|---|
totalResults | integer | Total number of items available |
currentPage | integer | Current page number |
page | integer | Current page number (duplicate) |
limit | integer | Items per page |
lastPage | integer | Last page number |
Related
- Rate Limits — Understand request limits
- Error Handling — Handle errors gracefully
- API Reference — Browse all endpoints