# Jobs and webhooks

How video, music and 3D jobs run: lifecycle, progress, polling, events, webhooks, retries and Idempotency-Key.

Video, music and 3D generations take seconds to minutes, so they run as **jobs**. You send a request, get a job back at once, and then follow it until it ends. This page is the whole story in one place; the [video](https://ewest.ai/docs/video), [audio](https://ewest.ai/docs/audio) and [3D](https://ewest.ai/docs/3d) pages cover what each model type accepts.

## Lifecycle

`POST /v1/videos/generations`, `/v1/audio/generations` or `/v1/3d/generations` answers `202` with a job: `{"id": "job_…", "object": "job", "type", "model", "status": "queued", "progress": 0, "eta_seconds", "created_at"}`. The job moves through these statuses:

| status | Meaning | Billed |
| --- | --- | --- |
| `queued` | Accepted, waiting to start. | No |
| `running` | The model is working. `progress` goes from 0 to 100 and `eta_seconds` estimates the time left (`null` when the job runs longer than usual). | Only if it succeeds |
| `succeeded` | Done. `output` holds the result (`url` on `cdn.ewest.ai`, `content_type`, and model-specific fields), `usage` what was used. | Yes |
| `failed` | Ended without a result. `error` holds a `code` and a fixed `message`; see [Errors](https://ewest.ai/docs/errors). | No |

`succeeded` and `failed` are final: the job never changes again. A job is visible only to the API key that created it; any other key gets `404`. Results stay on `cdn.ewest.ai` for 7 days, so download what you want to keep.

## Follow a job

There are three ways to find out how a job ended. They return the same job, so mix them as you like.

| Way | Use it when | How |
| --- | --- | --- |
| Poll | You have a script or a worker. | `GET /v1/jobs/{id}` every 3 to 5 seconds. |
| Event stream | You want live progress, for example in a UI. | `GET /v1/jobs/{id}/events`. |
| Webhook | You do not want to hold anything open. | `webhook_url` in the request; see [below](#webhooks). |

The event stream is Server-Sent Events: a `job` event with the full job on every change, a comment line every 10 seconds as a heartbeat, and the stream ends after the job's final status. Open it with `curl -N`, or with any SSE client that can send an `Authorization` header (the browser `EventSource` cannot, so call it from your server). If the stream drops, open it again: the first event is the current state. `GET /v1/jobs?limit=20` lists the key's recent jobs, newest first.

Polling faster than you need only uses up your [job-read limit](https://ewest.ai/docs/rate-limits#key-limits). If you are near it, use the stream or a webhook.

## Run a job to the end

The example submits with an `Idempotency-Key`, retries safely, polls until the job ends and raises on `failed`. It also shows how to cancel.

cURL:

```bash
# 1. Submit. The same Idempotency-Key on a retry returns this job instead of starting another.
curl https://api.ewest.ai/v1/videos/generations \
  -H "Authorization: Bearer $EWEST_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: my-boat-video-001" \
  -d '{"model": "ewest/veo-3.1-fast", "prompt": "A paper boat drifting down a rainy street"}'
# → 202 {"id": "job_…", "object": "job", "status": "queued", "progress": 0, …}

# 2. Poll (or follow GET /v1/jobs/job_…/events with curl -N).
curl https://api.ewest.ai/v1/jobs/job_… -H "Authorization: Bearer $EWEST_KEY"
# → {"status": "succeeded", "progress": 100, "output": {"url": "https://cdn.ewest.ai/vid/…"}, …}

# 3. Stop a job that has not started (409 job_running once it runs).
curl -X POST https://api.ewest.ai/v1/jobs/job_…/cancel -H "Authorization: Bearer $EWEST_KEY"
```

Python:

```python
import os, time, uuid, requests

BASE = "https://api.ewest.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['EWEST_KEY']}"}


def run_job(body):
    """Submit a job and wait for it. Returns the finished job; raises if it failed."""
    key = str(uuid.uuid4())  # one key per job you want; reuse it only to retry this submit
    for attempt in range(5):
        try:
            res = requests.post(f"{BASE}/videos/generations", headers={**HEADERS, "Idempotency-Key": key}, json=body, timeout=100)
        except requests.RequestException:
            time.sleep(2**attempt)  # lost response: the same key returns the same job
            continue
        if res.status_code in (409, 429, 500, 502, 503, 504):
            time.sleep(float(res.headers.get("retry-after", 2**attempt)))
            continue
        break
    else:
        raise RuntimeError("could not submit the job")
    if res.status_code != 202:
        raise RuntimeError(f"{res.status_code}: {res.text}")
    job = res.json()
    while job["status"] not in ("succeeded", "failed"):
        time.sleep(5)
        job = requests.get(f"{BASE}/jobs/{job['id']}", headers=HEADERS, timeout=30).json()
        print(job["status"], job["progress"])
    if job["status"] == "failed":
        raise RuntimeError(f"{job['error']['code']}: {job['error']['message']}")
    return job


job = run_job({"model": "ewest/veo-3.1-fast", "prompt": "A paper boat drifting down a rainy street"})
print(job["output"]["url"])
```

JavaScript:

```javascript
const BASE = "https://api.ewest.ai/v1";
const headers = { Authorization: `Bearer ${process.env.EWEST_KEY}` };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

// Submit a job and wait for it. Returns the finished job; throws if it failed.
async function runJob(body) {
  const key = crypto.randomUUID(); // one key per job you want; reuse it only to retry this submit
  let res;
  for (let attempt = 0; attempt < 5; attempt++) {
    try {
      res = await fetch(`${BASE}/videos/generations`, {
        method: "POST",
        headers: { ...headers, "Content-Type": "application/json", "Idempotency-Key": key },
        body: JSON.stringify(body),
        signal: AbortSignal.timeout(100_000),
      });
    } catch {
      await sleep(2 ** attempt * 1000); // lost response: the same key returns the same job
      continue;
    }
    if (![409, 429, 500, 502, 503, 504].includes(res.status)) break;
    await sleep(Number(res.headers.get("retry-after") ?? 2 ** attempt) * 1000);
  }
  if (!res || res.status !== 202) throw new Error(`${res?.status}: ${await res?.text()}`);
  let job = await res.json();
  while (!["succeeded", "failed"].includes(job.status)) {
    await sleep(5000);
    job = await (await fetch(`${BASE}/jobs/${job.id}`, { headers })).json();
    console.log(job.status, job.progress);
  }
  if (job.status === "failed") throw new Error(`${job.error.code}: ${job.error.message}`);
  return job;
}

const job = await runJob({ model: "ewest/veo-3.1-fast", prompt: "A paper boat drifting down a rainy street" });
console.log(job.output.url);
```

## Cancel a job

`POST /v1/jobs/{id}/cancel` stops a job that has not started. The answer is the job, now `failed` with code `cancelled`, and it is not charged. Once a job is running it cannot be stopped: the call answers `409` with code `job_running`, and the job finishes and is charged if it succeeds. A finished job answers `409` `job_finished`, and `409` `job_busy` means retry in a moment.

## Webhooks

Add `"webhook_url"` (a public `https://` address) to the request and we POST the finished job to it, with the same JSON as `GET /v1/jobs/{id}`. Every delivery is signed with your organization's secret by the [Standard Webhooks](https://www.standardwebhooks.com) rules.

- **Verify** each delivery before you trust it: check the `webhook-signature` over the raw body and refuse timestamps more than 5 minutes old. [Webhooks](https://ewest.ai/docs/webhooks#verify) has the rules and tested code for Node and Python.
- **Answer fast.** Reply `2xx` within 10 seconds and do slow work afterwards.
- **Retries.** Any other answer is retried 8 times in all over about 27.6 hours (5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 10 h). `410 Gone` stops them. See [retries](https://ewest.ai/docs/webhooks#retries).
- **Duplicates.** A delivery can arrive twice. Keep the `webhook-id` of what you handled and skip repeats ([duplicates](https://ewest.ai/docs/webhooks#duplicates)).
- **Redeliver.** `GET /v1/jobs/{id}/webhooks` shows the delivery log (kept 30 days); `POST /v1/jobs/{id}/webhooks/redeliver` sends the finished job again ([log and redelivery](https://ewest.ai/docs/webhooks#log)).
- **Rotate the secret** with `POST /v1/webhooks/secret`; for 24 hours deliveries carry both signatures ([your signing secret](https://ewest.ai/docs/webhooks#secret)).

A webhook can be missed (your server was down for longer than the retries). Treat it as a hint: if a job you expect has not arrived, read it with `GET /v1/jobs/{id}`.

## Idempotency-Key

If a connection drops after you sent a job request, you cannot tell whether it was accepted, and sending it again could start and bill a second job. Send an `Idempotency-Key` header (any unique string up to 255 characters, such as a UUID) and retry with the same key and the same body: within 24 hours you get the first job back, `202` with `Idempotent-Replayed: true`, and nothing new is started or charged.

- One key per job you want. Reuse it only to retry that request.
- The same key with a different body or on another endpoint is `409` `idempotency_key_reused`. While the first request is still being processed, a retry is `409` `idempotency_key_in_use` with `Retry-After`.
- Keys belong to the API key that sent them, and can be used again after 24 hours.
- A refused request (`400`, `402`) created no job, so retrying with the same key runs it again. A job that was created and then failed is returned as it is: submit a replacement with a new key.

More on telling a retry from a new job in [Rate limits and retries](https://ewest.ai/docs/rate-limits#async-jobs).

## When a job fails

A failed job is not an HTTP error: the request succeeded, and the job ended with `status: "failed"` and an `error` object. A failed job is never charged, so submitting a replacement is safe (with a new `Idempotency-Key`). The codes, for example `generation_failed`, `content_policy`, `timeout`, `storage_error` and `cancelled`, are in the [job errors](https://ewest.ai/docs/errors#jobs) section. Quote the job `id` and the `x-request-id` header when you [contact support](https://ewest.ai/docs/troubleshooting).

Source: https://ewest.ai/docs/jobs
