# Pagination

Source: https://developers.newjune.co/pagination

> Every list uses the same envelope and an opaque cursor. Here is a complete loop in each language.

Every `GET /v1/<collection>` returns a page:

```json
{
  "object": "list",
  "data": [{ "object": "round", "id": "6f1c2b8e-3d4a-4f5b-9c6d-7e8f9a0b1c2d" }],
  "has_more": true,
  "next_cursor": "eyJ2IjoxLCJrIjpbIjIwMjYtMDYtMDdUMTY6NDA6MDMuMDAwMDAwWiIsIjBiNWQ3YzFlLTJmM2EtNGI2Yy04ZDllLTFhMmIzYzRkNWU2ZiJdfQ"
}
```

| Field | Meaning |
| --- | --- |
| `data` | The items on this page, in the list's order. |
| `has_more` | True when more items come after this page. |
| `next_cursor` | Pass it as `cursor` to get the next page. Null on the last page. |

| Parameter | Meaning |
| --- | --- |
| `limit` | Items per page, 1 to 100. Default 25. |
| `cursor` | The `next_cursor` from the previous page. Leave it out for the first page. |

## How cursors work

Each list has a fixed order that ends with `id`, for example rounds by `started_at` then `id`, newest first. A cursor marks the position after the last item on a page, so:

- **Pages never overlap or skip**, even when new rounds arrive while you page.
- **Items added before the cursor's position do not appear** in later pages. Start a new walk to pick them up.
- **Keep the same filters and order** for every page of a walk. Change a filter and you start a new walk.
- **Cursors are opaque.** Do not parse or build them. A cursor that has been changed is `400 invalid_cursor`.

Every list's order is in its reference page and in the OpenAPI description of the list operation.

## A complete loop

Each sample fetches every round, 100 at a time, and prints how many it found.

curl:

```bash
#!/usr/bin/env bash
# Needs curl and jq.
set -euo pipefail

cursor=""
count=0
while :; do
  url="https://data.newjune.co/v1/rounds?limit=100"
  if [ -n "$cursor" ]; then url="$url&cursor=$cursor"; fi

  page=$(curl -sf "$url" -H "Authorization: Bearer $NEW_JUNE_API_KEY")
  count=$((count + $(echo "$page" | jq '.data | length')))

  if [ "$(echo "$page" | jq -r '.has_more')" != "true" ]; then break; fi
  cursor=$(echo "$page" | jq -r '.next_cursor')
done

echo "Found $count rounds"
```

TypeScript:

```ts
// Node 20+. Run with: npx tsx list-all-rounds.mts
interface ListPage<T> {
  object: 'list';
  data: T[];
  has_more: boolean;
  next_cursor: string | null;
}

async function* listAll<T>(path: string, params: Record<string, string> = {}) {
  let cursor: string | null = null;
  do {
    const url = new URL(`https://data.newjune.co/v1/${path}`);
    url.searchParams.set('limit', '100');
    for (const [name, value] of Object.entries(params)) url.searchParams.set(name, value);
    if (cursor) url.searchParams.set('cursor', cursor);

    const response = await fetch(url, {
      headers: { Authorization: `Bearer ${process.env.NEW_JUNE_API_KEY}` },
    });
    if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);

    const page = (await response.json()) as ListPage<T>;
    yield* page.data;
    cursor = page.has_more ? page.next_cursor : null;
  } while (cursor);
}

let count = 0;
for await (const _round of listAll('rounds')) count += 1;
console.log(`Found ${count} rounds`);
```

Python:

```python
import os
import requests

API = "https://data.newjune.co/v1"
session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ['NEW_JUNE_API_KEY']}"

def list_all(path, **params):
    params = {"limit": 100, **params}
    while True:
        response = session.get(f"{API}/{path}", params=params, timeout=30)
        response.raise_for_status()
        page = response.json()
        yield from page["data"]
        if not page["has_more"]:
            return
        params["cursor"] = page["next_cursor"]

count = sum(1 for _ in list_all("rounds"))
print(f"Found {count} rounds")
```

The `listAll` and `list_all` helpers work for every collection. Pass filters as the second argument, for example `listAll('hole_scores', { round_id })` or `list_all("shots", round_id=round_id)`. The [guides](https://developers.newjune.co/guides/export-rounds-to-csv) reuse them.

> **Large walks and rate limits.** At 100 items per page, 1,000 rounds take 10 requests. A full export with every round's hole scores and shots makes more requests than that: see [Rate limits](https://developers.newjune.co/rate-limits) for how to pace a long walk.
