# Pagination

Every `/api/v1/*` endpoint that lists one kind of record (`data` is an array) uses cursor pagination, except three small, bounded lists that return every row at once, with no `pagination` object: the risk categories, the templates, and a workspace's members (`GET /api/v1/members`, narrowed with `search` rather than pages). A read that gathers several capped lists into one object (`/me/work`, and a register's `review-queue`, `treatment-plan` and `changes`) doesn't page: it sets a `truncated` flag when a list was cut short. Cursors are opaque; you forward what the server gives you, you never construct one. Pages are stable across inserts: a record created while you page doesn't shift the others. Lists run newest first, so a record created after you fetch the first page isn't returned at all; start a new drain to see it.

## Wire shape

Response envelope:

```json
{
  "data": [
    { "id": "...", "title": "Risk A", "createdAt": "2026-05-28T12:00:00.000Z" },
    { "id": "...", "title": "Risk B", "createdAt": "2026-05-28T11:59:00.000Z" }
  ],
  "pagination": {
    "next_cursor": "eyJ0cyI6IjIwMjYtMDUtMjhUMTE6NTk6MDAuMDAwWiIsImlkIjoiYWJjZGVmIn0",
    "has_more": true
  },
  "requestId": "..."
}
```

The two pagination fields are snake_case; every other field in a response is camelCase.

- `next_cursor` - opaque base64url string. Pass it back on the next request to fetch the next page. `null` on the final page.
- `has_more` - canonical boolean. Source of truth for "is there more?" Don't infer from `next_cursor` alone; if both are present they always agree, but consumers should branch on `has_more`.

## Query parameters

```
GET /api/v1/registers?limit=50&cursor=<base64url>
```

| Param | Type | Default | Max | Notes |
| --- | --- | --- | --- | --- |
| `limit` | integer | 50 | 100 | Larger values are silently clamped to 100 (no error). Must be digits only and at least 1: `?limit=10abc` and `?limit=0` return 400. |
| `cursor` | base64url | - | - | Omit on the first request. Pass `next_cursor` from the prior page on subsequent requests. Malformed cursors return 400. |

## Ordering

By default every list endpoint returns the newest record first: by creation time, then by `id` to break ties (the audit log orders by each entry's `timestamp`). The tiebreak means records created in the same millisecond, as a bulk save makes them, are never skipped or repeated at a page boundary. The risk list has two exceptions. A search (`search=`) returns the best match first, and its cursor continues that order. An explicit `sort=` can't be combined with `cursor`, so a sorted list is one page of up to `limit` rows.

## Stability

Cursors don't expire. A cursor minted on a Monday morning still works on Friday afternoon. You can paginate at your own pace.

Cursors are not portable across endpoints. A cursor from `/api/v1/risks` is meaningless on `/api/v1/controls`.

Cursors are opaque. What a cursor holds is an implementation detail and may change, so never decode one in application logic.

## Pagination + filters

Filters are not stored in the cursor: the cursor holds only the position. Send the same filters on every page. Changing them part-way through a drain gives undefined results.

```bash
# Page 1
curl 'https://riskregister.com/api/v1/registers/REG-0001/risks?status=open&score_band=critical&limit=50' \
  -H "Authorization: Bearer rr_pat_live_..."

# Page 2: send the same filters, forward the cursor
curl 'https://riskregister.com/api/v1/registers/REG-0001/risks?status=open&score_band=critical&limit=50&cursor=<next_cursor>' \
  -H "Authorization: Bearer rr_pat_live_..."
```

## Drain pattern

Cap how many pages a drain fetches, so one call can't accidentally pull a 50,000-row register. The list tools of the [MCP endpoint](https://riskregister.com/docs/mcp.md) (the endpoint AI assistants connect to, over the Model Context Protocol) return one page per call instead, with the cursor to pass back.

A drain with a page cap, which stops on an error instead of reading a body that has no `pagination`:

```ts
interface Risk {
  id: string;
  title: string;
}

const MAX_PAGES = 50; // 50 pages of 100 = at most 5,000 risks
const pat = process.env.RR_PAT;

/** One page. On a 429, waits as long as the server asks, then asks again. */
async function getPage(url: URL): Promise<Response> {
  for (;;) {
    const res = await fetch(url, { headers: { Authorization: `Bearer ${pat}` } });
    if (res.status !== 429) return res;
    const seconds = Number(res.headers.get('Retry-After') ?? '1');
    await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
  }
}

const all: Risk[] = [];
let cursor: string | undefined;
let hasMore = true;

for (let page = 0; hasMore && page < MAX_PAGES; page += 1) {
  const url = new URL('https://riskregister.com/api/v1/registers/REG-0001/risks');
  url.searchParams.set('limit', '100');
  if (cursor) url.searchParams.set('cursor', cursor);

  const res = await getPage(url);
  if (!res.ok) throw new Error(`List failed: ${res.status} ${await res.text()}`);

  const body = await res.json();
  all.push(...body.data);

  hasMore = body.pagination.has_more;
  cursor = hasMore ? body.pagination.next_cursor : undefined;
}

if (hasMore) {
  // The cap was reached with more to read. Keep `cursor` to carry on later: it doesn't expire.
}
```

## Failure modes

| HTTP | Cause |
| --- | --- |
| `400 VALIDATION_ERROR` | The cursor is malformed: not one the server issued, or altered since. |
| `400 VALIDATION_ERROR` | `limit` is not a positive whole number. |
| `400 VALIDATION_ERROR` | `since` > `until` on the audit-log endpoint (the only filter that supports a range today). |

Don't pattern-match on the error message: the `code` field is stable.

## See also

- [Errors](https://riskregister.com/docs/errors.md) - error envelope.
- [Getting started](https://riskregister.com/docs/getting-started.md) - first paginated call.
