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

# Asynchrone Jobs

> Batches und Crawls laufen im Hintergrund. Erfahre, wie du auf einen Job mit Zeitlimit warten kannst und wie du später die Ergebnisse mit der Job-ID erhältst.

Scrapes, Suchen, Antworten und Karten liefern das Ergebnis in der Antwort. Batches und Crawls sind anders. Sie laufen im Hintergrund und die Erstellungsanfrage gibt sofort eine Job-`id` zurück.

## Wie ein asynchroner Job funktioniert

1. **Erstelle den Job** mit `POST /v1/batches` oder `POST /v1/crawls`. Speichere die `id` aus der Antwort.
2. **Warte auf den Job.** Überprüfe `GET /v1/batches/{batch_id}` oder `GET /v1/crawls/{crawl_id}`, bis der `status` `completed` ist.
3. **Hole die Ergebnisse ab.** Liste die Elemente des Batches oder die Seiten des Crawls auf. Dann hole den Inhalt jedes Ergebnisses mit seiner `retrieve_id`.

Schritte 2 und 3 verwenden die gespeicherte Job-ID. Wenn dein Programm stoppt, verwende diese ID, um den Status zu überprüfen und die Ergebnisse abzurufen. Eine neue Erstellungsanfrage kann die Arbeit wiederholen und mehr Credits verwenden.

## Was `completed` bedeutet

Wenn der `status` `completed` ist, höre auf, den Jobstatus zu überprüfen, und liste die Ergebnisse auf. Der Batch-Inhalt kann mehr Zeit benötigen, um lesbar zu werden. Wenn die API `failed` zurückgibt, höre auf zu warten und behalte die Job-ID für den Support.

`completed` bedeutet nicht, dass jede URL funktioniert hat:

* **Batch:** Ein abgeschlossener Batch kann fehlgeschlagene URLs enthalten. Liste sie mit `GET /v1/batches/{batch_id}/items?status=failed` auf.
* **Crawl:** Ein Crawl kann mit 0 Seiten abgeschlossen werden. Überprüfe `pages_count`. Die Seitenantwort listet die URLs auf, die in `metadata.failed_urls` fehlgeschlagen sind.
* **Inhalt:** In der `GET /v1/retrieve` Antwort, wenn `size_exceeded` `true` ist, hole das Markdown von `markdown_hosted_url`. Wenn `markdown_content` und `markdown_hosted_url` beide leer sind, direkt nachdem der Batch abgeschlossen ist, versuche später erneut dieselbe `retrieve_id`.

## Warten mit einem Zeitlimit

Der folgende Helfer wartet 10 Sekunden zwischen den Überprüfungen. Er startet keine neue Überprüfung nach 30 Minuten. Er stoppt auch bei einem HTTP-Fehler, zum Beispiel `401` oder `429`. Das Stoppen bricht den Job nicht ab: Du kannst ihn später erneut mit seiner ID überprüfen.

Verwende Python 3.9 oder neuer, oder Node.js 18 oder neuer. Für Python installiere Requests mit `python -m pip install requests`. Setze die Umgebungsvariable `OLOSTEP_API_KEY`, bevor du die Beispiele ausführst.

```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`)
}
```

Gib dem Helfer den Pfad des Jobs: `batches/<batch_id>` oder `crawls/<crawl_id>`.

Um den Status einmalig von einem Terminal aus zu überprüfen:

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

## Die Ergebnisse später mit der Job-ID abrufen

Dieses Beispiel verwendet eine gespeicherte Batch-ID. Es wartet, bis der Batch abgeschlossen ist. Dann listet es die abgeschlossenen und fehlgeschlagenen Elemente auf. Jede Liste stoppt mit einem Fehler nach 1.000 Seiten ohne eine letzte Seite. Dies ist eine Begrenzung im Beispiel, nicht in der API.

Speichere die Python-Blöcke als `wait_for_job.py` und `get_results.py` im selben Ordner. Für Node.js verwende `waitForJob.mjs` und `getResults.mjs`. Ersetze `YOUR_BATCH_ID` durch deine gespeicherte 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)
```

Um die Beispiele auszuführen, verwende `python get_results.py` oder `node getResults.mjs`. Um den Inhalt jedes Ergebnisses zu erhalten, sende seine `retrieve_id` an [`GET /v1/retrieve`](https://docs.olostep.com/api-reference/retrieve). Für einen Crawl siehe [Crawls](https://docs.olostep.com/features/crawls.md).

Anstatt zu pollen, kannst du auch einen `webhook` setzen, wenn du den Job erstellst. Siehe [Webhooks](https://docs.olostep.com/api-reference/common/webhooks.md).

## Nächste Schritte

> [card] [Batches](https://docs.olostep.com/features/batches.md)
>
> Eine Liste von URLs in einem Job scrapen.

> [card] [Crawls](https://docs.olostep.com/features/crawls.md)
>
> Die Seiten einer ganzen Website abrufen.

> [card] [Inhalt abrufen](https://docs.olostep.com/api-reference/retrieve.md)
>
> Den Inhalt eines Ergebnisses mit seiner `retrieve_id` abrufen.

> [card] [Webhooks](https://docs.olostep.com/api-reference/common/webhooks.md)
>
> Eine Anfrage erhalten, wenn ein Job abgeschlossen ist.


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