> ## 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.

# Async jobs

> Batches and crawls run in the background. Learn how to wait for a job with a time limit, and how to get the results later with the job ID.

Scrapes, searches, answers, and maps return the result in the response. Batches and crawls are different. They run in the background, and the create request returns a job `id` right away.

## How an async job works

1. **Create the job** with `POST /v1/batches` or `POST /v1/crawls`. Save the `id` from the response.
2. **Wait for the job.** Check `GET /v1/batches/{batch_id}` or `GET /v1/crawls/{crawl_id}` until `status` is `completed`.
3. **Get the results.** List the items of the batch or the pages of the crawl. Then get the content of each result with its `retrieve_id`.

Steps 2 and 3 use the saved job ID. If your program stops, use that ID to check the status and get the results. A new create request can repeat work and use more credits.

## What `completed` means

When `status` is `completed`, stop checking the job status and list the results. Batch content can take more time to become readable. If the API returns `failed`, stop waiting and keep the job ID for support.

`completed` does not mean that every URL worked:

* **Batch:** a completed batch can include failed URLs. List them with `GET /v1/batches/{batch_id}/items?status=failed`.
* **Crawl:** a crawl can complete with 0 pages. Check `pages_count`. The pages response lists the URLs that failed in `metadata.failed_urls`.
* **Content:** in the `GET /v1/retrieve` response, if `size_exceeded` is `true`, get the Markdown from `markdown_hosted_url`. If `markdown_content` and `markdown_hosted_url` are both empty just after the batch completes, try the same `retrieve_id` again later.

## Wait with a time limit

The helper below waits 10 seconds between checks. It starts no new check after 30 minutes. It also stops on an HTTP error, for example `401` or `429`. Stopping does not cancel the job: you can check it again later with its ID.

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.

```python wait_for_job.py theme={null}
import os
import time

import requests

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


def wait_for_job(path, timeout_s=1800, interval_s=10):
    """Check GET /v1/<path> until the job is completed or failed.

    Wait interval_s seconds between checks. Start no new check after
    timeout_s seconds. Stopping does not cancel the job.
    """
    deadline = time.monotonic() + timeout_s
    while time.monotonic() < deadline:
        response = requests.get(
            f"{API_URL}/{path}",
            headers={"Authorization": f"Bearer {API_KEY}"},
            timeout=30,
        )
        response.raise_for_status()  # Stop on an HTTP error, for example 401 or 429
        job = response.json()
        if not isinstance(job.get("status"), str):
            raise ValueError(f"{path}: no status in the response")
        print("Status:", job["status"])
        if job["status"] == "completed":
            return job
        if job["status"] == "failed":
            raise RuntimeError(f"{path} failed")
        time.sleep(interval_s)
    raise TimeoutError(f"{path} is not complete after {timeout_s} seconds")
```

```javascript waitForJob.mjs theme={null}
import { setTimeout as sleep } from 'node:timers/promises'

const API_URL = 'https://api.olostep.com/v1'

export async function waitForJob(path, timeoutMs = 30 * 60 * 1000, intervalMs = 10_000) {
  // Check GET /v1/<path> until the job is completed or failed.
  // Wait intervalMs between checks. Start no new check after timeoutMs.
  // Stopping does not cancel the job.
  const deadline = performance.now() + timeoutMs
  while (performance.now() < deadline) {
    const res = await fetch(`${API_URL}/${path}`, {
      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(`${path}: HTTP ${res.status} ${await res.text()}`)
    const job = await res.json()
    if (typeof job.status !== 'string') throw new Error(`${path}: no status in the response`)
    console.log('Status:', job.status)
    if (job.status === 'completed') return job
    if (job.status === 'failed') throw new Error(`${path} failed`)
    await sleep(intervalMs)
  }
  throw new Error(`${path} is not complete after ${timeoutMs / 1000} seconds`)
}
```

Give the helper the path of the job: `batches/<batch_id>` or `crawls/<crawl_id>`.

To check the status one time from a terminal:

```bash theme={null}
curl --max-time 30 "https://api.olostep.com/v1/batches/YOUR_BATCH_ID" \
  -H "Authorization: Bearer $OLOSTEP_API_KEY"
```

## Get the results later with the job ID

This example uses a saved batch ID. It waits for the batch to complete. Then it lists the completed and failed items. Each list stops with an error after 1,000 pages without a last page. This is a limit in the sample, not in the API.

Save the Python blocks as `wait_for_job.py` and `get_results.py` in the same folder. For Node.js, use `waitForJob.mjs` and `getResults.mjs`. Replace `YOUR_BATCH_ID` with your saved batch ID.

```python get_results.py theme={null}
import requests

from wait_for_job import API_KEY, API_URL, wait_for_job

BATCH_ID = "YOUR_BATCH_ID"  # Saved when you created the batch


def list_items(batch_id, status, max_pages=1000):
    """Get all items with this status. Follow the cursor until 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")


wait_for_job(f"batches/{BATCH_ID}")
completed = list_items(BATCH_ID, "completed")
failed = list_items(BATCH_ID, "failed")
print(f"{len(completed)} completed, {len(failed)} failed")
for item in completed:
    print(item["url"], item["retrieve_id"])
for item in failed:
    print("Failed:", item["url"])
```

```javascript getResults.mjs theme={null}
import { waitForJob } from './waitForJob.mjs'

const API_URL = 'https://api.olostep.com/v1'
const batchId = 'YOUR_BATCH_ID' // Saved when you created the batch

async function listItems(batchId, status, maxPages = 1000) {
  // Get all items with this status. Follow the cursor until 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`)
}

await waitForJob(`batches/${batchId}`)
const completed = await listItems(batchId, 'completed')
const failed = await listItems(batchId, 'failed')
console.log(`${completed.length} completed, ${failed.length} failed`)
for (const item of completed) console.log(item.url, item.retrieve_id)
for (const item of failed) console.log('Failed:', item.url)
```

To run the samples, use `python get_results.py` or `node getResults.mjs`. To get the content of each result, send its `retrieve_id` to [`GET /v1/retrieve`](https://docs.olostep.com/api-reference/retrieve). For a crawl, see [Crawls](https://docs.olostep.com/features/crawls.md).

Instead of polling, you can also set a `webhook` when you create the job. See [Webhooks](https://docs.olostep.com/api-reference/common/webhooks.md).

## Next steps

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

> [card] [Crawls](https://docs.olostep.com/features/crawls.md)
>
> Get the pages of a whole site.

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

> [card] [Webhooks](https://docs.olostep.com/api-reference/common/webhooks.md)
>
> Get a request when a job completes.


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