Pagination and filtering
Page through lists with cursors, sort them and filter them.
2 min read Updated
Lists answer one page at a time. Each page says whether more follow and gives a cursor for the next one: pass it back to read on, until there's no more.
Pages and cursors
Every list takes the same two parameters for its pages:
limit- How many items a page holds: 1 to 100, 25 unless you say.
cursor- Where the page starts: the
nextCursorof the page before, exactly as it was given. Leave it out for the first page.
Beside the items in data, a page has a pagination object:
{
"limit": 25,
"hasMore": false,
"nextCursor": null
} | Field | Type and description |
|---|---|
limit | integer The page size that was used. |
hasMore | boolean Whether another page follows this one. |
nextCursor | string or null Pass it as |
When another page follows, a Link header gives its whole address too, with rel="next". No total count is given: read on until
nextCursor is null.
Link: <https://api.rabbitflare.com/v1/sites?limit=100&cursor=…>; rel="next" Read every page
The same loop in three languages, here over your sites, 100 at a time: the fewest requests for a long list. The SDK follows the cursors by itself.
// Every item of a list, one page of 100 at a time.
async function listAll(path, filters = {}) {
const items = [];
let cursor = null;
do {
const url = new URL(`https://api.rabbitflare.com/v1${path}`);
for (const [name, value] of Object.entries({ ...filters, limit: 100 })) url.searchParams.set(name, value);
if (cursor) url.searchParams.set("cursor", cursor);
const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.RABBITFLARE_TOKEN}` } });
if (!res.ok) throw new Error(`Rabbitflare API error ${res.status}: ${await res.text()}`);
const { data, pagination } = await res.json();
items.push(...data);
cursor = pagination.nextCursor;
} while (cursor);
return items;
}
const sites = await listAll("/sites");
console.log(`${sites.length} sites`); // Every item of a list, one page of 100 at a time.
import { Rabbitflare } from "@rabbitflare/api";
const rf = new Rabbitflare({ token: process.env.RABBITFLARE_TOKEN });
const sites = [];
// The SDK follows nextCursor, with the same filters, until the last page.
for await (const site of rf.sites.list({ limit: 100 })) sites.push(site);
console.log(`${sites.length} sites`); <?php
// Every item of a list, one page of 100 at a time.
function listAll(string $path, array $filters = []): array
{
$items = [];
$cursor = null;
do {
$query = $filters + ['limit' => 100] + ($cursor !== null ? ['cursor' => $cursor] : []);
$ch = curl_init('https://api.rabbitflare.com/v1' . $path . '?' . http_build_query($query));
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('RABBITFLARE_TOKEN')],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
throw new RuntimeException("Rabbitflare API error $status: $body");
}
$page = json_decode($body, true);
array_push($items, ...$page['data']);
$cursor = $page['pagination']['nextCursor'];
} while ($cursor !== null);
return $items;
}
$sites = listAll('/sites');
echo count($sites), ' sites', PHP_EOL; import os
import requests
def list_all(path, **filters):
"""Every item of a list, one page of 100 at a time."""
items, cursor = [], None
while True:
params = {**filters, "limit": 100}
if cursor:
params["cursor"] = cursor
response = requests.get(
"https://api.rabbitflare.com/v1" + path,
headers={"Authorization": "Bearer " + os.environ["RABBITFLARE_TOKEN"]},
params=params,
timeout=120,
)
response.raise_for_status()
page = response.json()
items.extend(page["data"])
cursor = page["pagination"]["nextCursor"]
if cursor is None:
return items
sites = list_all("/sites")
print(len(sites), "sites")
With cURL, read the first page, then send the same request again with cursor set to its nextCursor. Paging is stable: an item
added or removed while you read never makes another one repeat or go missing.
Sorting and filters
sort names the field to sort by, and order is asc (smallest or oldest first) or desc. Items that sort the
same are in the order of their ids. A list's filters are query parameters of its own, matched exactly unless its page says otherwise, like
?status=active. Every list, with what it can be sorted by and filtered on:
| List | Sort by | Unless you say | Filters |
|---|---|---|---|
| List clouds | name | name asc | None |
| List a cloud's regions | name, city, country, continent | name asc | None |
| List a cloud's plans | priceMonthlyCents, name, vcpus, memoryGb, diskGb | priceMonthlyCents asc | region |
| List servers | createdAt, name | createdAt desc | status, cloud, region |
| List a server's sites | createdAt, name | createdAt desc | status |
| List a server's snapshots and backups | createdAt, name | createdAt desc | kind, takenBy |
| List sites | createdAt, name | createdAt desc | serverId, status |
| List a site's domains | createdAt, hostname | createdAt asc | None |
| List the domains of every site | createdAt, hostname | createdAt desc | siteId, status |
| List the requests a site's firewall stopped | occurredAt | occurredAt desc | blocked |
| List requests Cloudflare stopped on a site | occurredAt | occurredAt desc | None |
| List a server's allowed and blocked addresses | addedAt, key | addedAt desc | kind, automatic |
| List a site's malware threats | foundAt | foundAt desc | status, severity, kind |
| List a site's cron jobs | createdAt, name | createdAt asc | type, enabled |
| List a cron job's runs | startedAt | startedAt desc | status, trigger |
| List a site's backups | startedAt | startedAt desc | status, trigger |
| List your backup storage | createdAt, name | createdAt desc | kind, status |
| List support tickets | lastMessageAt, createdAt | lastMessageAt desc | status |
| List events | createdAt | createdAt desc | type, serverId, siteId, level, since, until |
| List event types | type, category | type asc | category |
| List webhook endpoints | createdAt, url | createdAt desc | status |
| List an endpoint's deliveries | createdAt | createdAt desc | state, eventType |
What a cursor isn't
- Not a page number, and not something to build or read: pass it back exactly as it came.
-
Not for other filters or another sort. A cursor belongs to the request it came from: with a different
sort,orderor filter it answers400invalid_cursor. Start again from the first page instead. - Not for keeping: read the pages one after another, and start again from the first page next time.
Still have a question?
Our team answers support tickets about the API, and other developers answer in the community.