> ## Documentation Index
> Fetch the complete documentation index at: https://usefoil.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Pagination

> Paginate Foil API list endpoints with cursor-based pagination, including limit and cursor parameters, filters, and SDK auto-pagination helpers.

Foil uses **cursor-based pagination** on the list endpoints for sessions, fingerprints, and API keys. Cursors are opaque - don't parse them, construct them, or rely on their format. They're stable across process restarts and safe to persist in your own database if you want to resume a long iteration.

Two list endpoints don't paginate. `GET /v1/organizations/{organizationId}/webhooks/endpoints` takes no query parameters and returns every endpoint. `GET /v1/organizations/{organizationId}/events` accepts `limit`, `type`, and `endpoint_id`, but it has no `cursor`, so it returns at most one page and always reports `has_more` as `false`. See [Request parameters](#request-parameters).

## Response envelope

Every list response has the same shape:

```json theme={"dark"}
{
  "data": [
    { "object": "session", "id": "sid_...", "...": "..." },
    { "object": "session", "id": "sid_...", "...": "..." }
  ],
  "pagination": {
    "limit": 50,
    "has_more": true,
    "next_cursor": "eyJ2IjoxLCJzY29yZWRBdCI6IjIwMjYtMDMtMTdUMDA6MDA6MDMuMDAwWiIsInJvd0lkIjoiMTg0MiJ9"
  },
  "meta": {
    "request_id": "req_..."
  }
}
```

| Field | Type | Meaning |
| - | - | - |
| `data` | array | Up to `limit` items for this page. |
| `pagination.limit` | number | The effective page size the server used. For the webhook endpoint list, this is the number of endpoints returned. |
| `pagination.has_more` | boolean | `true` if more pages exist beyond this one. |
| `pagination.next_cursor` | string, optional | Present when `has_more` is `true`. Pass it as `cursor` on the next request. |
| `meta.request_id` | string | Per-request ID - see [Errors → Using `request_id`](https://usefoil.com/docs/api-reference/errors#using-request_id). |

Endpoints that return one resource wrap it in a `data` envelope instead: `{ "data": { ... }, "meta": { "request_id": "req_..." } }`.

## Request parameters

The sessions, fingerprints, and API keys list endpoints accept these two query parameters:

| Parameter | Type | Default | Max | Notes |
| - | - | - | - | - |
| `limit` | integer | `50` | `200` | Items per page. The value must be an integer from `1` to `200`. Any other value returns `422` with `request.validation_failed`. Smaller pages keep responses fast; larger pages reduce round trips for bulk iteration. |
| `cursor` | string | - | - | The `pagination.next_cursor` from a prior page. Omit on the first request. An invalid cursor returns `422`. |

The list endpoints don't support `offset`. A request that includes it returns `422`; use `cursor` instead. Foil ignores other query parameters that an endpoint doesn't define.

| Endpoint | Parameters |
| - | - |
| `GET /v1/sessions` | `limit`, `cursor`, `verdict`, `search` |
| `GET /v1/fingerprints` | `limit`, `cursor`, `search`, `sort` |
| `GET /v1/organizations/{organizationId}/api-keys` | `limit`, `cursor` |
| `GET /v1/organizations/{organizationId}/events` | `limit` (1-200, default 50), `type`, `endpoint_id`. No `cursor`. |
| `GET /v1/organizations/{organizationId}/webhooks/endpoints` | None. |

See the per-resource filter sections below for the filter parameters.

## Iterating

The canonical pattern: call the endpoint, process `data`, and loop while `has_more` is true, passing `next_cursor` forward.

```javascript Node.js theme={"dark"}
const { Foil } = require("@abxy/foil-server");
const client = new Foil({ secretKey: process.env.FOIL_SECRET_KEY });

async function iterateSessions() {
  let cursor = undefined;
  do {
    const page = await client.sessions.list({ limit: 100, cursor });
    for (const session of page.items) {
      await processSession(session);
    }
    cursor = page.has_more ? page.next_cursor : undefined;
  } while (cursor);
}
```

```python Python theme={"dark"}
from foil_server import Foil
import os

client = Foil(secret_key=os.environ["FOIL_SECRET_KEY"])

def iterate_sessions():
    cursor = None
    while True:
        page = client.sessions.list(limit=100, cursor=cursor)
        for session in page.items:
            process_session(session)
        if not page.has_more:
            break
        cursor = page.next_cursor
```

```go Go theme={"dark"}
import foil "github.com/abxy-labs/foil-server-go"

func iterateSessions(ctx context.Context, client *foil.Client) error {
    var cursor string
    for {
        page, err := client.Sessions.List(ctx, foil.SessionListParams{
            Limit:  100,
            Cursor: cursor,
        })
        if err != nil {
            return err
        }
        for _, s := range page.Items {
            processSession(s)
        }
        if !page.HasMore {
            return nil
        }
        cursor = page.NextCursor
    }
}
```

```ruby Ruby theme={"dark"}
require "foil/server"

client = Foil::Server::Client.new(secret_key: ENV["FOIL_SECRET_KEY"])

cursor = nil
loop do
  page = client.sessions.list(limit: 100, cursor: cursor)
  page.items.each { |s| process_session(s) }
  break unless page.has_more
  cursor = page.next_cursor
end
```

```php PHP theme={"dark"}
$client = new \Foil\Server\Client(
    secretKey: getenv("FOIL_SECRET_KEY") ?: null,
);

$cursor = null;
do {
    $page = $client->sessions()->list(limit: 100, cursor: $cursor);
    foreach ($page->items as $session) {
        processSession($session);
    }
    $cursor = $page->has_more ? $page->next_cursor : null;
} while ($cursor !== null);
```

```bash cURL theme={"dark"}
# First page
curl "https://api.usefoil.com/v1/sessions?limit=100" \
  -H "Authorization: Bearer sk_live_..."

# Subsequent page - pass the next_cursor from the previous response
curl "https://api.usefoil.com/v1/sessions?limit=100&cursor=eyJ2IjoxLC..." \
  -H "Authorization: Bearer sk_live_..."
```

## Auto-pagination in the SDKs

Every server SDK has an iterator for sessions and fingerprints that runs the cursor loop for you. Use it when you want to walk the entire result set without managing state.

```javascript Node.js theme={"dark"}
for await (const session of client.sessions.iter({ limit: 100 })) {
  await processSession(session);
}
```

```python Python theme={"dark"}
for session in client.sessions.iter(limit=100):
    process_session(session)
```

```go Go theme={"dark"}
err := client.Sessions.Iter(ctx, foil.SessionListParams{Limit: 100}, func(session foil.SessionSummary) error {
    return processSession(session)
})
if err != nil {
    return err
}
```

```ruby Ruby theme={"dark"}
client.sessions.iter(limit: 100).each do |session|
  process_session(session)
end
```

```php PHP theme={"dark"}
foreach ($client->sessions()->iterate(limit: 100) as $session) {
    processSession($session);
}
```

The iterators request one page at a time and yield items as they go, so they're safe to use on result sets that wouldn't fit in memory. They make the same number of requests as manual iteration and count against the same [rate limits](https://usefoil.com/docs/api-reference/rate-limits.md). They don't retry: if a page request fails, the iterator raises the error, and it doesn't expose the cursor it reached. For long iterations that must resume after a failure, page manually and persist `next_cursor`. The Go iterator stops at the first error that your callback returns.

## Filters and sorting

Filter parameters layer on top of the standard pagination params. They narrow the result set but don't change the envelope shape.

### Sessions

`GET /v1/sessions` returns one row per session, ordered by the time of its latest decision, newest first.

| Parameter | Type | Notes |
| - | - | - |
| `verdict` | `"bot" \| "human" \| "inconclusive"` | Filter to sessions whose latest decision has this verdict. Any other value returns `422`. |
| `search` | string | Match sessions by ID or request metadata. See the matching rules below. |
| `client_user_id` | string | Filter to sessions whose `client_user_id` is exactly this value, case-sensitive. An empty value or one longer than 256 characters returns `422`. |
| `client_application_id` | string | Filter to sessions whose `client_application_id` is exactly this value, case-sensitive. An empty value or one longer than 256 characters returns `422`. |

A `search` value that starts with `sid_`, `evt_`, or `vid_` matches a session ID, event ID, or visitor ID exactly, ignoring case. A 32-character hexadecimal value matches a legacy session ID or event ID exactly. Any other value is a case-insensitive substring match against the session ID, event ID, visitor ID, `client_user_id`, `client_application_id`, page URL, user agent, and IP address. Each request searches a fixed slice of your sessions. A page can hold fewer results than `limit`, or none. An empty page isn't the end while `has_more` is `true`, so keep paging until it's `false`. A `search` value longer than 256 characters returns `422`, and a substring search that can't finish within a second returns `503`.

### Fingerprints

`GET /v1/fingerprints` returns one row per visitor fingerprint. The default order is most recently seen first.

| Parameter | Type | Notes |
| - | - | - |
| `search` | string | Match fingerprints by ID, user agent, or IP address. A value that starts with `vid_`, or a 32-character hexadecimal value, matches a visitor ID exactly. Any other value is a case-insensitive substring match against the visitor ID and the latest user agent and IP address. |
| `sort` | `"seen_count" \| "first_seen"` | Orders results from the highest value to the lowest: `seen_count` puts the most frequently seen visitors first, and `first_seen` puts the most recently first-seen visitors first. Any other value returns `422`. |

A fingerprint cursor is tied to the `sort` value of the request that returned it. Pass the same `sort` with every request in an iteration. A cursor used with a different `sort` returns `422`.

### API keys

| Parameter | Type | Notes |
| - | - | - |
| `limit`, `cursor` | - | Pagination only. No additional filters today. Keys are ordered newest first and include revoked keys. |

### Events

| Parameter | Type | Notes |
| - | - | - |
| `limit` | integer | `1` to `200`, default `50`. |
| `type` | string | Only return events of this type. An unknown type returns `422`. |
| `endpoint_id` | string | Only return events that produced a delivery for this endpoint. |

Events are ordered newest first. The endpoint returns a single page.

Combining filters and pagination is supported: pass the filters once, and carry the cursor forward as normal. The server applies filters before paginating, so `limit` controls page size of the filtered result set.

## Caveats

* **Don't construct cursors.** They're opaque tokens - the server may change their encoding. To find a specific session or visitor, use the `search` parameter instead.
* **Cursor lifetimes.** Cursors remain valid as long as the underlying result set does - a cursor minted today is valid until the records it points into expire. Stored sessions and visitor fingerprints are not currently expired on a fixed window.
* **Result stability under concurrent writes.** Sessions, and fingerprints in the default order, are ordered newest first, so records created or updated after you start iterating land ahead of your cursor and don't appear in later pages. A session that receives a new decision during an iteration moves to the front of the ordering. The list endpoints have no time filters. To audit a fixed window, iterate from the newest record and stop when `latest_decision.evaluated_at` falls before the start of the window.
* **Ordering.** Each list endpoint documents its default sort in [Filters and sorting](#filters-and-sorting). Don't assume an order that isn't explicitly documented.

## What's next

> [card] [Authentication](https://usefoil.com/docs/api-reference/authentication.md)
>
> Key types and scopes.

> [card] [Errors](https://usefoil.com/docs/api-reference/errors.md)
>
> Envelope shape, status codes, retry semantics.

> [card] [Sessions](https://usefoil.com/docs/api-reference/sessions.md)
>
> The most common list endpoint.

> [card] [Fingerprints](https://usefoil.com/docs/api-reference/fingerprints.md)
>
> Visitor fingerprint lookup.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.