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

# Pagination

> Some Olostep endpoints return a list in pages. Learn how to get the next page with a cursor, and how to find the last page.

Some endpoints return a long list in pages. To get the next page, send the cursor from the last response.

## Endpoints with pages

| Endpoint | First request | Next page | Last page |
| - | - | - | - |
| [`GET /v1/batches/{batch_id}/items`](https://docs.olostep.com/api-reference/batches/items) | No `cursor` | Send `cursor` from the response | `cursor` is absent or `null` |
| [`GET /v1/crawls/{crawl_id}/pages`](https://docs.olostep.com/api-reference/crawls/pages) | `cursor=0` | Send `cursor` from the response | `cursor` is absent or `null` |
| [`GET /v1/files`](https://docs.olostep.com/api-reference/files/list) | No `cursor` | Send `next_cursor` as `cursor` | `has_more` is `false` |
| [`GET /v1/monitors/{monitor_id}/events`](https://docs.olostep.com/api-reference/monitors/events) | No `cursor` | Send `next_cursor` as `cursor` | `has_more` is `false` |

Maps also return a `cursor`. See [Create map](https://docs.olostep.com/api-reference/maps/create.md).

## Rules for all cursors

* Send the cursor back exactly as you got it. Batch and crawl cursors are numbers. File and monitor event cursors are strings.
* `0` is a valid cursor. Do not stop the loop on it.
* For batch items and crawl pages, stop when `cursor` is absent or `null`. For files and monitor events, stop when `has_more` is `false`. If more results remain without a next cursor, report an error.
* If a request fails, or a cursor repeats, stop the loop with an error. Do not skip to the next page.
* To get all the results of a batch or a crawl, wait until its `status` is `completed`. While the job is still running, a response can contain a `cursor` for results that are not ready yet.

Use Python 3.9 or later, or Node.js 18 or later. For Python, install Requests with `python -m pip install requests`. Set the `OLOSTEP_API_KEY` environment variable before you run the samples.

Each sample stops with an error after 1,000 pages without a last page. This is a limit in the sample, not in the API. For a very large list, increase `max_pages` in Python or `maxPages` in Node.js.

## Batch items

The batch items endpoint returns the results in `items`. Set `status` to `completed` or `failed` to filter them. Without `status`, the endpoint does not filter by status. These samples select `completed`. On the first request, leave out `cursor`.

```python list_batch_items.py theme={null}
import os

import requests

API_KEY = os.environ["OLOSTEP_API_KEY"]
API_URL = "https://api.olostep.com/v1"


def list_batch_items(batch_id, status="completed", max_pages=1000):
    """Get all items of a batch with this status. Follow the cursor to the last page."""
    items = []
    cursor = None  # The first request has no cursor
    seen = set()  # Cursors from the API, to stop if one repeats
    for _ in range(max_pages):
        response = requests.get(
            f"{API_URL}/batches/{batch_id}/items",
            headers={"Authorization": f"Bearer {API_KEY}"},
            params={"status": status, "cursor": cursor},
            timeout=30,
        )
        response.raise_for_status()  # Stop on an HTTP error, for example 401 or 429
        page = response.json()
        items.extend(page["items"])
        cursor = page.get("cursor")
        if cursor is None:  # No cursor: this was the last page
            return items
        if cursor in seen:
            raise RuntimeError(f"Pagination stopped: cursor {cursor} repeated")
        seen.add(cursor)
    raise RuntimeError(f"Pagination stopped after {max_pages} pages")


items = list_batch_items("YOUR_BATCH_ID")
print(len(items), "completed items")
```

```javascript listBatchItems.mjs theme={null}
const API_URL = 'https://api.olostep.com/v1'

async function listBatchItems(batchId, status = 'completed', maxPages = 1000) {
  // Get all items of a batch with this status. Follow the cursor to the last page.
  const items = []
  let cursor = null // The first request has no cursor
  const seen = new Set() // Cursors from the API, to stop if one repeats
  for (let pageNumber = 0; pageNumber < maxPages; pageNumber += 1) {
    const params = new URLSearchParams({ status })
    if (cursor !== null) params.set('cursor', String(cursor))
    const res = await fetch(`${API_URL}/batches/${batchId}/items?${params}`, {
      headers: { Authorization: `Bearer ${process.env.OLOSTEP_API_KEY}` },
      signal: AbortSignal.timeout(30_000),
    })
    // Stop on an HTTP error, for example 401 or 429
    if (!res.ok) throw new Error(`HTTP ${res.status} ${await res.text()}`)
    const page = await res.json()
    items.push(...page.items)
    cursor = page.cursor ?? null
    if (cursor === null) return items // No cursor: this was the last page
    if (seen.has(cursor)) throw new Error(`Pagination stopped: cursor ${cursor} repeated`)
    seen.add(cursor)
  }
  throw new Error(`Pagination stopped after ${maxPages} pages`)
}

const items = await listBatchItems('YOUR_BATCH_ID')
console.log(items.length, 'completed items')
```

To get the items that failed, call the function with the status `failed`.

## Crawl pages

The crawl pages endpoint returns the pages in `pages`. The first request sends `cursor=0`.

```python list_crawl_pages.py theme={null}
import os

import requests

API_KEY = os.environ["OLOSTEP_API_KEY"]
API_URL = "https://api.olostep.com/v1"


def list_crawl_pages(crawl_id, max_pages=1000):
    """Get all pages of a crawl. Follow the cursor to the last page."""
    pages = []
    cursor = 0  # The first request starts at cursor 0
    seen = set()  # Cursors from the API, to stop if one repeats
    for _ in range(max_pages):
        response = requests.get(
            f"{API_URL}/crawls/{crawl_id}/pages",
            headers={"Authorization": f"Bearer {API_KEY}"},
            params={"cursor": cursor},
            timeout=30,
        )
        response.raise_for_status()  # Stop on an HTTP error, for example 401 or 429
        page = response.json()
        pages.extend(page["pages"])
        cursor = page.get("cursor")
        if cursor is None:  # No cursor: this was the last page
            return pages
        if cursor in seen:
            raise RuntimeError(f"Pagination stopped: cursor {cursor} repeated")
        seen.add(cursor)
    raise RuntimeError(f"Pagination stopped after {max_pages} pages")


pages = list_crawl_pages("YOUR_CRAWL_ID")
print(len(pages), "pages")
```

```javascript listCrawlPages.mjs theme={null}
const API_URL = 'https://api.olostep.com/v1'

async function listCrawlPages(crawlId, maxPages = 1000) {
  // Get all pages of a crawl. Follow the cursor to the last page.
  const pages = []
  let cursor = 0 // The first request starts at cursor 0
  const seen = new Set() // Cursors from the API, to stop if one repeats
  for (let pageNumber = 0; pageNumber < maxPages; pageNumber += 1) {
    const params = new URLSearchParams({ cursor: String(cursor) })
    const res = await fetch(`${API_URL}/crawls/${crawlId}/pages?${params}`, {
      headers: { Authorization: `Bearer ${process.env.OLOSTEP_API_KEY}` },
      signal: AbortSignal.timeout(30_000),
    })
    // Stop on an HTTP error, for example 401 or 429
    if (!res.ok) throw new Error(`HTTP ${res.status} ${await res.text()}`)
    const page = await res.json()
    pages.push(...page.pages)
    cursor = page.cursor ?? null
    if (cursor === null) return pages // No cursor: this was the last page
    if (seen.has(cursor)) throw new Error(`Pagination stopped: cursor ${cursor} repeated`)
    seen.add(cursor)
  }
  throw new Error(`Pagination stopped after ${maxPages} pages`)
}

const pages = await listCrawlPages('YOUR_CRAWL_ID')
console.log(pages.length, 'pages')
```

## Files and monitor events

Files and monitor events use `has_more` and `next_cursor`. Send `next_cursor` as the `cursor` of the next request. Set `limit` from 1 to 100. Without `limit`, `GET /v1/files` returns all completed files for your team.

This sample lists your team's completed files, 100 at a time. For the events of a monitor, use `GET /v1/monitors/{monitor_id}/events` and read the events from `data` in the same way.

```python list_files.py theme={null}
import os

import requests

API_KEY = os.environ["OLOSTEP_API_KEY"]
API_URL = "https://api.olostep.com/v1"


def next_cursor(page):
    """Return the cursor of the next page, or None on the last page."""
    if not isinstance(page.get("has_more"), bool):
        raise ValueError("Pagination stopped: has_more is missing or not a boolean")
    if page["has_more"] is False:
        return None
    if page.get("next_cursor") is None:
        raise ValueError("Pagination stopped: has_more is true without next_cursor")
    return page["next_cursor"]


def list_files(limit=100, max_pages=1000):
    """Get your team's completed files. Follow next_cursor to the last page."""
    files = []
    cursor = None  # The first request has no cursor
    seen = set()  # Cursors from the API, to stop if one repeats
    for _ in range(max_pages):
        response = requests.get(
            f"{API_URL}/files",
            headers={"Authorization": f"Bearer {API_KEY}"},
            params={"limit": limit, "cursor": cursor},
            timeout=30,
        )
        response.raise_for_status()  # Stop on an HTTP error, for example 401 or 429
        page = response.json()
        files.extend(page["data"])
        cursor = next_cursor(page)
        if cursor is None:  # This was the last page
            return files
        if cursor in seen:
            raise RuntimeError(f"Pagination stopped: cursor {cursor} repeated")
        seen.add(cursor)
    raise RuntimeError(f"Pagination stopped after {max_pages} pages")


files = list_files()
print(len(files), "files")
```

```javascript listFiles.mjs theme={null}
const API_URL = 'https://api.olostep.com/v1'

function nextCursor(page) {
  // Return the cursor of the next page, or null on the last page.
  if (typeof page.has_more !== 'boolean') {
    throw new Error('Pagination stopped: has_more is missing or not a boolean')
  }
  if (page.has_more === false) return null
  if ((page.next_cursor ?? null) === null) {
    throw new Error('Pagination stopped: has_more is true without next_cursor')
  }
  return page.next_cursor
}

async function listFiles(limit = 100, maxPages = 1000) {
  // Get your team's completed files. Follow next_cursor to the last page.
  const files = []
  let cursor = null // The first request has no cursor
  const seen = new Set() // Cursors from the API, to stop if one repeats
  for (let pageNumber = 0; pageNumber < maxPages; pageNumber += 1) {
    const params = new URLSearchParams({ limit: String(limit) })
    if (cursor !== null) params.set('cursor', cursor)
    const res = await fetch(`${API_URL}/files?${params}`, {
      headers: { Authorization: `Bearer ${process.env.OLOSTEP_API_KEY}` },
      signal: AbortSignal.timeout(30_000),
    })
    // Stop on an HTTP error, for example 401 or 429
    if (!res.ok) throw new Error(`HTTP ${res.status} ${await res.text()}`)
    const page = await res.json()
    files.push(...page.data)
    cursor = nextCursor(page)
    if (cursor === null) return files // This was the last page
    if (seen.has(cursor)) throw new Error(`Pagination stopped: cursor ${cursor} repeated`)
    seen.add(cursor)
  }
  throw new Error(`Pagination stopped after ${maxPages} pages`)
}

const files = await listFiles()
console.log(files.length, 'files')
```

## Endpoints without pages

[`GET /v1/schedules`](https://docs.olostep.com/api-reference/schedules/list) and [`GET /v1/monitors`](https://docs.olostep.com/api-reference/monitors/list) return the full list in one response.

## Next steps

> [card] [Batches](https://docs.olostep.com/features/batches.md)
>
> Scrape a list of URLs in one job.

> [card] [Retrieve content](https://docs.olostep.com/api-reference/retrieve.md)
>
> Get the content of a result with its `retrieve_id`.


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