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

# Lavori asincroni

> Batch e crawl vengono eseguiti in background. Scopri come attendere un lavoro con un limite di tempo e come ottenere i risultati successivamente con l’ID del lavoro.

Scrapes, ricerche, risposte e mappe restituiscono il risultato nella risposta. I batch e i crawl sono diversi. Vengono eseguiti in background e la richiesta di creazione restituisce subito un `id` del lavoro.

## Come funziona un lavoro asincrono

1. **Crea il lavoro** con `POST /v1/batches` o `POST /v1/crawls`. Salva l’`id` dalla risposta.
2. **Attendi il lavoro.** Controlla `GET /v1/batches/{batch_id}` o `GET /v1/crawls/{crawl_id}` finché lo `status` non è `completed`.
3. **Ottieni i risultati.** Elenca gli elementi del batch o le pagine del crawl. Poi ottieni il contenuto di ciascun risultato con il suo `retrieve_id`.

I passaggi 2 e 3 utilizzano l’ID del lavoro salvato. Se il tuo programma si interrompe, utilizza quell’ID per controllare lo stato e ottenere i risultati. Una nuova richiesta di creazione può ripetere il lavoro e utilizzare più crediti.

## Cosa significa `completed`

Quando lo `status` è `completed`, smetti di controllare lo stato del lavoro ed elenca i risultati. Il contenuto del batch può richiedere più tempo per diventare leggibile. Se l’API restituisce `failed`, smetti di attendere e conserva l’ID del lavoro per il supporto.

`completed` non significa che ogni URL ha funzionato:

* **Batch:** un batch completato può includere URL falliti. Elencali con `GET /v1/batches/{batch_id}/items?status=failed`.
* **Crawl:** un crawl può completarsi con 0 pagine. Controlla `pages_count`. La risposta delle pagine elenca gli URL che hanno fallito in `metadata.failed_urls`.
* **Contenuto:** nella risposta di `GET /v1/retrieve`, se `size_exceeded` è `true`, ottieni il Markdown da `markdown_hosted_url`. Se `markdown_content` e `markdown_hosted_url` sono entrambi vuoti subito dopo il completamento del batch, prova di nuovo lo stesso `retrieve_id` più tardi.

## Attendere con un limite di tempo

L’helper qui sotto attende 10 secondi tra i controlli. Non avvia nuovi controlli dopo 30 minuti. Si interrompe anche in caso di errore HTTP, ad esempio `401` o `429`. L'interruzione non annulla il lavoro: puoi controllarlo di nuovo più tardi con il suo ID.

Usa Python 3.9 o successivo, o Node.js 18 o successivo. Per Python, installa Requests con `python -m pip install requests`. Imposta la variabile d’ambiente `OLOSTEP_API_KEY` prima di eseguire gli esempi.

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

Fornisci all’helper il percorso del lavoro: `batches/<batch_id>` o `crawls/<crawl_id>`.

Per controllare lo stato una volta da un terminale:

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

## Ottieni i risultati successivamente con l’ID del lavoro

Questo esempio utilizza un ID batch salvato. Attende che il batch sia completato. Poi elenca gli elementi completati e quelli falliti. Ogni elenco si interrompe con un errore dopo 1.000 pagine senza una pagina finale. Questo è un limite nell’esempio, non nell’API.

Salva i blocchi Python come `wait_for_job.py` e `get_results.py` nella stessa cartella. Per Node.js, usa `waitForJob.mjs` e `getResults.mjs`. Sostituisci `YOUR_BATCH_ID` con il tuo ID batch salvato.

```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"  # Salvato quando hai creato il 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' // Salvato quando hai creato il 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)
```

Per eseguire gli esempi, usa `python get_results.py` o `node getResults.mjs`. Per ottenere il contenuto di ciascun risultato, invia il suo `retrieve_id` a [`GET /v1/retrieve`](https://docs.olostep.com/api-reference/retrieve). Per un crawl, vedi [Crawls](https://docs.olostep.com/features/crawls.md).

Invece di fare polling, puoi anche impostare un `webhook` quando crei il lavoro. Vedi [Webhooks](https://docs.olostep.com/api-reference/common/webhooks.md).

## Prossimi passi

> [card] [Batch](https://docs.olostep.com/features/batches.md)
>
> Scrape un elenco di URL in un unico lavoro.

> [card] [Crawl](https://docs.olostep.com/features/crawls.md)
>
> Ottieni le pagine di un intero sito.

> [card] [Recupera contenuto](https://docs.olostep.com/api-reference/retrieve.md)
>
> Ottieni il contenuto di un risultato con il suo `retrieve_id`.

> [card] [Webhooks](https://docs.olostep.com/api-reference/common/webhooks.md)
>
> Ricevi una richiesta quando un lavoro è completato.


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