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

# Video Generation API

> Complete API reference for OpenRouter's dedicated asynchronous Video Generation API. Submit jobs, poll status, stream video content, discover models, and configure webhooks.

OpenRouter provides a dedicated asynchronous API for generating videos from text prompts, start and end frame images, and multimodal references. Because video generation takes significantly longer than text or image generation (typically 30 seconds to several minutes), requests follow an asynchronous submit-poll-download lifecycle.

## Endpoints

The Video Generation API consists of four endpoints:

| Method | Endpoint | Description | Response |
| - | - | - | - |
| `POST` | `/api/v1/videos` | Submits a video generation job | `202 Accepted` with job ID and polling URL |
| `GET` | `/api/v1/videos/{jobId}` | Polls job status, progress, and download URLs | `200 OK` with status and video URLs |
| `GET` | `/api/v1/videos/{jobId}/content` | Streams video binary bytes from the provider | `200 video/mp4` binary stream |
| `GET` | `/api/v1/videos/models` | Lists video generation models and capabilities | `200 OK` with model parameter metadata |

## End-to-end workflow

Video generation follows three sequential steps:

1. **Submit**: Send a generation request with a video model and prompt to `POST /api/v1/videos`. Receive a job ID (`id`) and relative polling URL (`polling_url`).
2. **Poll**: Query `GET /api/v1/videos/{jobId}` at regular intervals (recommended: every 10–30 seconds) until `status` reaches a terminal value: `completed`, `failed`, `cancelled` or `expired`. Alternatively, supply a `callback_url` to receive a webhook notification upon completion.
3. **Download**: Once completed, retrieve the generated video using either the signed storage URL (`urls[0]`) or the authenticated content proxy endpoint (`unsigned_urls[0]`).

In a multi-user app, one API key can poll, download, and continue every job the app created. Record which end user owns each job ID, and check that ownership before you act on a job ID supplied by a client.

### cURL example

```bash theme={null}
# Step 1: Submit a video generation job (Veo 3.1 supports durations: 4, 6, 8)
SUBMIT_RESPONSE=$(curl -fsS -X POST "https://openrouter.ai/api/v1/videos" \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "google/veo-3.1",
    "prompt": "A drone shot flying through a mist-shrouded redwood forest at sunrise, cinematic lighting, 4k",
    "duration": 6,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }')

JOB_ID=$(echo "$SUBMIT_RESPONSE" | bun -e 'const j = await Bun.stdin.json(); console.log(j.id ?? "");')
if [ -z "$JOB_ID" ] || [ "$JOB_ID" = "null" ]; then
  echo "Submission failed: $SUBMIT_RESPONSE" >&2
  exit 1
fi
echo "Submitted job: $JOB_ID"

# Step 2: Poll until completion (capped at 40 iterations = 10 minutes)
POLL_COUNT=0
while [ "$POLL_COUNT" -lt 40 ]; do
  sleep 15
  POLL_COUNT=$((POLL_COUNT + 1))
  STATUS_RESPONSE=$(curl -fsS "https://openrouter.ai/api/v1/videos/$JOB_ID" \
    -H "Authorization: Bearer $OPENROUTER_API_KEY") || {
      echo "Polling request failed (HTTP error)" >&2
      exit 1
    }

  STATUS=$(echo "$STATUS_RESPONSE" | bun -e 'const j = await Bun.stdin.json(); console.log(j.status ?? "");')
  echo "Current status: $STATUS"

  if [ "$STATUS" = "completed" ]; then
    break
  elif [ "$STATUS" = "failed" ] || [ "$STATUS" = "cancelled" ] || [ "$STATUS" = "expired" ]; then
    echo "Job terminated with status $STATUS" >&2
    exit 1
  fi
done

if [ "$STATUS" != "completed" ]; then
  echo "Timed out waiting for video generation" >&2
  exit 1
fi

# Step 3: Download video using the authenticated content endpoint
curl -fsS "https://openrouter.ai/api/v1/videos/$JOB_ID/content" \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -o output.mp4

echo "Saved video to output.mp4"
```

### TypeScript example

```typescript theme={null}
const apiKey = process.env.OPENROUTER_API_KEY;
if (!apiKey) {
  throw new Error('OPENROUTER_API_KEY environment variable is required');
}

const headers = {
  Authorization: `Bearer ${apiKey}`,
  'Content-Type': 'application/json',
};

type VideoJobStatus = 'pending' | 'in_progress' | 'completed' | 'failed' | 'cancelled' | 'expired';

interface VideoJobResponse {
  id: string;
  generation_id?: string;
  status: VideoJobStatus;
  polling_url: string;
  urls?: string[];
  expires_at?: number;
  unsigned_urls?: string[];
  error?: string;
  usage?: {
    cost: number | null;
    is_byok?: boolean;
  };
}

// Step 1: Submit job (Veo 3.1 supports durations: 4, 6, 8)
const submitRes = await fetch('https://openrouter.ai/api/v1/videos', {
  method: 'POST',
  headers,
  body: JSON.stringify({
    model: 'google/veo-3.1',
    prompt: 'A gentle ocean wave washing over golden sand in slow motion',
    duration: 6,
    resolution: '720p',
    aspect_ratio: '16:9',
  }),
});

if (!submitRes.ok) {
  const errorText = await submitRes.text();
  throw new Error(`Video submission failed (${submitRes.status}): ${errorText}`);
}

const job = (await submitRes.json()) as VideoJobResponse;
console.log(`Job submitted: ${job.id}`);

// Step 2: Poll status with a 10-minute deadline
const deadline = Date.now() + 10 * 60_000;
let completedJob: VideoJobResponse | null = null;

while (!completedJob) {
  if (Date.now() > deadline) {
    throw new Error(`Timed out waiting for video job ${job.id} to complete`);
  }

  await new Promise((resolve) => setTimeout(resolve, 15000));
  const pollRes = await fetch(`https://openrouter.ai/api/v1/videos/${job.id}`, { headers });
  if (!pollRes.ok) {
    const errorText = await pollRes.text();
    throw new Error(`Polling failed with HTTP ${pollRes.status}: ${errorText}`);
  }

  const statusData = (await pollRes.json()) as VideoJobResponse;
  console.log(`Status: ${statusData.status}`);

  if (statusData.status === 'completed') {
    completedJob = statusData;
  } else if (['failed', 'cancelled', 'expired'].includes(statusData.status)) {
    throw new Error(`Job ended with status ${statusData.status}: ${statusData.error ?? 'Unknown error'}`);
  }
}

// Step 3: Stream video bytes to file or downstream response
const videoRes = await fetch(`https://openrouter.ai/api/v1/videos/${job.id}/content`, {
  headers: { Authorization: `Bearer ${apiKey}` },
});

if (!videoRes.ok) {
  throw new Error(`Video download failed (${videoRes.status})`);
}

const videoBytes = await videoRes.arrayBuffer();
console.log(`Downloaded video (${videoBytes.byteLength} bytes)`);
```

### Python example

```python theme={null}
import os
import time
import requests

api_key = os.getenv("OPENROUTER_API_KEY")
if not api_key:
    raise ValueError("OPENROUTER_API_KEY environment variable is required")

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}

# Step 1: Submit video job (Veo 3.1 supports durations: 4, 6, 8)
submit_res = requests.post(
    "https://openrouter.ai/api/v1/videos",
    headers=headers,
    json={
        "model": "google/veo-3.1",
        "prompt": "An architect sketching a modern house on parchment, pencil strokes forming 3D walls",
        "duration": 6,
        "resolution": "720p",
        "aspect_ratio": "16:9",
    },
)
submit_res.raise_for_status()
job = submit_res.json()
job_id = job["id"]
print(f"Submitted video job: {job_id}")

# Step 2: Poll until finished (capped at 40 iterations = 10 minutes)
max_polls = 40
polls = 0
while polls < max_polls:
    time.sleep(15)
    polls += 1
    poll_res = requests.get(f"https://openrouter.ai/api/v1/videos/{job_id}", headers=headers)
    poll_res.raise_for_status()
    poll_data = poll_res.json()
    status = poll_data["status"]
    print(f"Job status: {status}")

    if status == "completed":
        break
    if status in ("failed", "cancelled", "expired"):
        raise RuntimeError(f"Video job failed with status {status}: {poll_data.get('error')}")
else:
    raise TimeoutError(f"Video job {job_id} did not finish within 10 minutes")

# Step 3: Download video binary
download_res = requests.get(
    f"https://openrouter.ai/api/v1/videos/{job_id}/content",
    headers={"Authorization": f"Bearer {api_key}"},
)
download_res.raise_for_status()

with open("output.mp4", "wb") as f:
    f.write(download_res.content)
print("Saved output.mp4")
```

## Job lifecycle and statuses

The `status` field on `GET /api/v1/videos/{jobId}` reflects the current state of generation:

| Status | Type | Meaning | Next action |
| - | - | - | - |
| `pending` | In-flight | The request was admitted and queued for processing | Continue polling |
| `in_progress` | In-flight | The provider is actively rendering the video frames | Continue polling |
| `completed` | Terminal | Video rendering succeeded and output assets are ready | Retrieve output using `urls` or `unsigned_urls` |
| `failed` | Terminal | The provider or validation failed; `error` explains the reason | Inspect `error` message and do not retry without parameter changes |
| `cancelled` | Terminal | The job was cancelled before rendering completed | Terminal state |
| `expired` | Terminal | The job exceeded maximum allowed time-to-live before settlement | Terminal state |

While a job is in flight, the response can also carry `status_detail`, the step within `status`, and `progress`:

| `status` | `status_detail` | Meaning |
| - | - | - |
| `pending` | `submitting` | OpenRouter is submitting the job to the provider |
| `pending` | `queued_at_provider` | The provider accepted the job and reports it as queued |
| `in_progress` | `generating` | The provider reports the job as generating |
| `in_progress` | `finalizing` | The provider finished, and OpenRouter is storing the video |

A job becomes pollable once the provider accepts it, so most polls start at `queued_at_provider`. `status_detail` only moves forward when present, and a fast job can skip steps between polls. It is absent once the job is finished and can be absent mid-job when the step is unknown, so use `status` to tell whether the job is finished.

`progress` is the percent complete, from 0 to 100, while `status_detail` is `generating`. Only providers that report a percent send it.

### Polling and retrieval

* Call `GET /api/v1/videos/{jobId}/content` only after a poll returns `status: "completed"`. Before then the content endpoint returns `404` with `Job <id> is not completed (status: <status>)`, and the request does not move the job forward.
* Poll every 10–30 seconds and back off on `429`. For long jobs or many concurrent jobs, set `callback_url` and wait for the [webhook](#webhooks-and-signature-verification) instead of polling. Keep a timeout and a fallback poll anyway: if webhook delivery exhausts its retries, the job can complete and be billed without your application hearing about it.
* A `completed` job can briefly report `in_progress` while its result is still being stored. Keep polling until `status` is terminal.
* Generated videos are not kept forever. `expires_at` is when OpenRouter's stored copy and signed `urls` expire. After that, the content endpoint may still serve the video from the provider until the provider deletes it, which returns `410` or, for some providers, a `5xx`. Download or copy the video to your own storage soon after the job completes.

## Downloading outputs: `urls` vs `unsigned_urls`

When a job reaches `status: "completed"`, the response payload provides two distinct ways to access the generated video:

```json theme={null}
{
  "id": "gen-vid-1789480874-Ab3dEf9hIjKlMnOpQrSt",
  "generation_id": "gen-vid-1789480874-Ab3dEf9hIjKlMnOpQrSt",
  "status": "completed",
  "polling_url": "/api/v1/videos/gen-vid-1789480874-Ab3dEf9hIjKlMnOpQrSt",
  "urls": [
    "https://storage.openrouter.ai/generated-media/video-sample.mp4?token=..."
  ],
  "expires_at": 1789567274,
  "unsigned_urls": [
    "/api/v1/videos/gen-vid-1789480874-Ab3dEf9hIjKlMnOpQrSt/content?index=0"
  ],
  "usage": {
    "cost": 0.5,
    "is_byok": false
  }
}
```

### 1. Pre-signed storage URLs (`urls`)

* **Authentication**: No `Authorization` header required.
* **Validity**: Temporary, valid until the Unix timestamp in `expires_at`.
* **Use case**: Safe for direct client browser playback (`<video src={urls[0]}>`) or direct download links without exposing your OpenRouter API key.
* **Availability**: Present when OpenRouter's edge media storage has cached the output. Because these URLs grant direct read access while valid, treat them as bearer secrets.
* **Multi-user apps**: Your API key can read every job your app created, so before returning `urls` to an end user, check that the requested job belongs to that user. Otherwise one user can play another user's video by passing its job ID.

### 2. Authenticated content endpoint (`unsigned_urls`)

* **Authentication**: Requires `Authorization: Bearer <OPENROUTER_API_KEY>`.
* **Validity**: Permanent for as long as the generation record is retained.
* **Use case**: Server-side processing, archival pipelines, or backend streaming proxies when `urls` is absent or expired.
* **Streaming in web apps**: Because browser `<video>` tags cannot attach custom `Authorization` headers, never send `unsigned_urls` directly to the client browser with client-side API keys. Instead, implement a thin server-side proxy route in your web framework (e.g., Next.js `app/api/videos/[id]/route.ts`) that verifies the user session, checks that the requested job belongs to that user (your API key can read every job your app created), fetches `GET /api/v1/videos/{jobId}/content` using your server's `OPENROUTER_API_KEY`, and pipes the `video/mp4` response back to the client.

## Request parameters

`POST /api/v1/videos` accepts the following parameters:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `model` | string | Yes | Model slug (e.g. `google/veo-3.1`, `bytedance-seed/seedance-2`, `minimax/hailuo-3`). |
| `prompt` | string | Conditional | Description of the scene and motion. Required unless the selected model supports video generation from image inputs alone. |
| `duration` | integer | No | Length of the generated video in seconds (e.g., `4`, `6`, `8`). Must be one of the model's `supported_durations`. |
| `resolution` | string | No | Resolution tier (e.g., `480p`, `720p`, `1080p`, `1K`, `2K`, `4K`). Must match the model's `supported_resolutions`. |
| `aspect_ratio` | string | No | Aspect ratio (e.g., `16:9`, `9:16`, `1:1`, `4:3`, `3:4`, `21:9`). Must match the model's `supported_aspect_ratios`. |
| `size` | string | No | Exact pixel dimensions in `WIDTHxHEIGHT` format (e.g., `1280x720`). Interchangeable with `resolution` + `aspect_ratio`. |
| `frame_images` | array | No | First and last frame images for image-to-video generation. Each item specifies `frame_type: "first_frame"` or `"last_frame"`. |
| `input_references` | array | No | Reference images, audio, or video for reference-to-video style guidance. |
| `generate_audio` | boolean | No | Whether to generate synchronized audio alongside the video. Defaults to `true` for models that support audio output. |
| `previous_job_id` | string | No | Job ID of a completed video generation to continue or extend using the same model and provider endpoint. Your API key can continue every job your app created, so verify that the referenced job belongs to the requesting end user before forwarding a client-supplied ID; otherwise one user can extend another user's video and receive the combined clip. |
| `seed` | integer | No | Integer seed for deterministic generation (supported by select providers). |
| `callback_url` | string | No | HTTPS URL to receive a webhook notification when generation completes. Overrides the workspace-level default webhook. |
| `provider` | object | No | [Video provider routing](https://openrouter.ai/docs/guides/overview/multimodal/video-generation.md#provider-routing) preferences (`order`, `only`, `ignore`), data policy (`data_collection`, `zdr`), and provider-specific options. Sorting and automatic provider fallbacks are not supported. |
| `session_id` | string | No | Identifier for grouping related requests in observability tools and Broadcast. |
| `user` | string | No | End-user identifier for rate limiting and audit logging. |

### Image-to-video (`frame_images`)

To animate an existing image into a video, supply one or two frame images in `frame_images`. Supported frame types are `first_frame` (starts the clip from this image) and `last_frame` (ends the clip at this image):

```json theme={null}
{
  "model": "google/veo-3.1",
  "prompt": "The camera pans around the statue as dust motes float through sunbeams",
  "frame_images": [
    {
      "type": "image_url",
      "image_url": {
        "url": "https://example.com/character-start.png"
      },
      "frame_type": "first_frame"
    }
  ],
  "duration": 6,
  "resolution": "720p",
  "aspect_ratio": "16:9"
}
```

### Reference-to-video (`input_references`)

Reference-to-video guides character consistency, aesthetic style, or scene composition without locking the video to an exact starting pixel frame:

```json theme={null}
{
  "model": "google/veo-3.1",
  "prompt": "A cinematic shot of the character walking through a neon-lit cyberpunk alley in the rain",
  "input_references": [
    {
      "type": "image_url",
      "image_url": {
        "url": "https://example.com/character-sheet.png"
      }
    }
  ],
  "duration": 6,
  "resolution": "1080p",
  "aspect_ratio": "16:9"
}
```

## Model discovery

Query the dedicated Video Models endpoint to retrieve supported parameters, resolutions, durations, and pricing SKUs for every video model currently deployed:

```bash theme={null}
curl -fsS "https://openrouter.ai/api/v1/videos/models"
```

```typescript title="TypeScript" lines theme={null}
const response = await fetch('https://openrouter.ai/api/v1/videos/models');
const models = await response.json();
```

```python title="Python" lines theme={null}
response = requests.get("https://openrouter.ai/api/v1/videos/models")
response.raise_for_status()
models = response.json()
```

```go title="Go" lines theme={null}
resp, err := http.Get("https://openrouter.ai/api/v1/videos/models")
if err != nil {
	log.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
	log.Fatal(err)
}
fmt.Println(string(body))
```

Each model entry includes capability matrices and pricing units:

```json theme={null}
{
  "data": [
    {
      "id": "google/veo-3.1",
      "canonical_slug": "google/veo-3.1-20260320",
      "name": "Google: Veo 3.1",
      "description": "Google state-of-the-art video generation model supporting 720p, 1080p, and 4K outputs.",
      "created": 1774277148,
      "supported_durations": [4, 6, 8],
      "supported_resolutions": ["720p", "1080p", "4K"],
      "supported_aspect_ratios": ["16:9", "9:16"],
      "supported_frame_images": ["first_frame", "last_frame"],
      "generate_audio": true,
      "pricing_skus": {
        "duration_seconds_with_audio": "0.40",
        "duration_seconds_with_audio_4k": "0.60",
        "duration_seconds_without_audio": "0.20",
        "duration_seconds_without_audio_4k": "0.40"
      },
      "allowed_passthrough_parameters": [
        "personGeneration",
        "aspectRatio",
        "negativePrompt",
        "conditioningScale",
        "enhancePrompt"
      ]
    }
  ]
}
```

### Parameter support by model

Use the model's entry in `GET /api/v1/videos/models` to choose parameter values before you submit. Each entry describes one endpoint for the model, so treat the lists as discovery hints rather than a guarantee for every provider: if you pin a different provider with `provider`, it can reject a listed value or accept an unlisted one. Unsupported values are usually rejected with `400`, either by OpenRouter before the job is sent or by the provider. Some providers instead ignore a setting they can't apply, for example an `aspect_ratio` on image-to-video that follows the first frame's geometry, so a successful job doesn't guarantee every parameter was used.

| Request parameter | Model field | Rule |
| - | - | - |
| `duration` | `supported_durations` | Must be one of the listed values. |
| `resolution` | `supported_resolutions` | Must be one of the listed values. |
| `aspect_ratio` | `supported_aspect_ratios` | Must be one of the listed values. |
| `size` | `supported_sizes` | Must be one of the listed `WIDTHxHEIGHT` values. |
| `frame_images[].frame_type` | `supported_frame_images` | Each frame type must be listed. Omit `frame_images` when the field is `null`. |
| `generate_audio` | `generate_audio` | Set to `true` only when the field is `true`. |
| `seed` | `seed` | Send only when the field is `true`. |
| `provider.options.<provider>` | `allowed_passthrough_parameters` | Only listed keys are forwarded. See [provider-specific video options](https://openrouter.ai/docs/cookbook/video-generation/provider-specific-video-options.md). |

A `null` field means the model does not advertise a list, so OpenRouter does not restrict that parameter, and the provider can still reject unsupported values. `upscale_factor` and `creativity` are stricter: sending either returns `400` unless an eligible endpoint advertises support. Another exception is `duration: -1` (automatic duration): it needs explicit endpoint support and can return `400` even when `supported_durations` is `null`. `previous_job_id` works only on models whose provider supports continuing a job, and the referenced job must be a completed job from your account.

To list what every model supports:

```bash theme={null}
curl -fsS "https://openrouter.ai/api/v1/videos/models" \
  | jq '.data[] | {id, supported_durations, supported_resolutions, supported_aspect_ratios, supported_sizes, supported_frame_images, generate_audio, seed}'
```

To filter models by the job you want to run, follow [Choose a video model](https://openrouter.ai/docs/cookbook/video-generation/choose-video-model.md).

## Errors

Errors returned by an endpoint use the standard OpenRouter error body, `{"error": {"code": <HTTP status>, "message": "...", "metadata": {...}}}`. The `message` text describes the specific cause; the tables below list the causes by status. See [Errors and debugging](https://openrouter.ai/docs/api_reference/errors-and-debugging.md) for the shared format.

### Errors from `POST /api/v1/videos`

These errors are returned before the job is created, so no job ID is issued and you are not charged.

| Status | Cause | How to fix |
| - | - | - |
| `400` | A parameter value isn't supported by the model, for example a `duration` outside `supported_durations`. The message names the parameter and lists the supported values. | Use a value from the model's entry in `GET /api/v1/videos/models`. See [Parameter support by model](#parameter-support-by-model). |
| `400` | The request is malformed: a missing `prompt` on a model that needs one, an invalid reference URL, or an input type (image, audio, video) the model doesn't accept. | Fix the field named in the message. |
| `400` | `previous_job_id` isn't supported by the model, or the referenced job can't be continued. | Continue only completed jobs on a model that supports continuation. |
| `400` | The model slug doesn't exist. | Check the slug against `GET /api/v1/videos/models`. |
| `400` | Your account or key enforces [ZDR](#zero-data-retention-zdr-policy). Account-level enforcement can instead return `404` when it filters out every endpoint. | Turn off ZDR enforcement for video requests. |
| `401` | The API key is missing or invalid. | Send `Authorization: Bearer <OPENROUTER_API_KEY>`. |
| `402` | Your balance or key limit doesn't cover the estimated cost of the job. Holds for your other running jobs count toward this. | If the response has `Retry-After`, pending jobs are using the budget: wait and retry. Otherwise add credits or raise the key's limit. |
| `403` | Your workspace is HIPAA-enabled. The Videos API isn't available to HIPAA workspaces. | Use a workspace without HIPAA enabled. Changing the prompt or provider doesn't help. |
| `403` | A key or guardrail spending limit is reached, counting billed usage and holds for running jobs, even when the account has enough credits. | Raise the limit or wait for running jobs to settle. |
| `403` | The model requires moderation on the selected provider and your prompt was flagged. The message lists the flagged categories and says no credits were charged. | Rewrite the prompt, or choose a model or provider that doesn't require moderation. |
| `404` | The model exists but no endpoint is available for it (including when your data policies, such as ZDR, filter out every endpoint), or the `previous_job_id` job wasn't found. For a continuation, the original job's endpoint or BYOK credential may no longer be available. | Check your data policy and provider settings. For a continuation, restore access to the original endpoint and credential, or start a new job. |
| `409` | The `previous_job_id` job hasn't finished yet, or it failed, was cancelled, or expired. | If the previous job is still running, wait for it to complete and retry. If it failed, was cancelled, or expired, it can never be continued: start a new job or continue a different completed job. |
| `413` | The text in the request exceeds the moderation budget for the endpoint. | Shorten the prompt. |
| `429` | You hit a rate limit. | Honor `Retry-After` when present. Otherwise wait until `X-RateLimit-Reset` or retry with exponential backoff. |
| `503` | Moderation is temporarily unavailable, or a spending hold was lost before dispatch. A provider `503` after dispatch can also leave the outcome unknown. | Retry when the message says moderation or the spending hold failed. For other `503`s, the job may have started: don't blindly resubmit, because a retry can create a second paid job. |

### Errors from `GET /api/v1/videos/{jobId}` and `/content`

| Status | Cause | How to fix |
| - | - | - |
| `403` | The request hostname isn't allowed by your workspace's data-region policy. This is checked before the job is looked up. | Use the URL returned for the job, or a hostname your workspace allows. |
| `404` | The job ID doesn't exist, belongs to another account, or was submitted from a workspace your API key isn't authorized for. | Check the ID returned by `POST /api/v1/videos`, and use a key for the workspace that submitted the job. |
| `404` | `/content` was called before the job reached `completed`, or the job is `failed`, `cancelled`, or `expired`. | Poll `GET /api/v1/videos/{jobId}` until `status` is `completed`. Stop polling on `failed`, `cancelled`, or `expired`, which never reach `completed`, and read `error`. |
| `400` | The `index` query parameter on `/content` is out of range for the job's outputs. | Use an index below the number of entries in `unsigned_urls`. `urls` can be omitted even when the video is downloadable. |
| `409` | `/content` is served from the provider and the provider reports the video isn't ready yet, even though the job is `completed`. | Wait a few seconds and retry. |
| `410` | The provider has deleted the generated video after its retention window. | Download videos soon after completion. Submit a new job to regenerate. |
| `5xx` | OpenRouter or the provider failed to serve the result. After `expires_at`, this can also mean the original provider endpoint is no longer available. | Retry with backoff. A `5xx` doesn't prove the video is gone, because an outage can block retrieval while the provider still holds it. Only a `410` confirms the provider deleted it. |

### Failed jobs

A job that the provider accepted but couldn't finish ends with `status: "failed"`, `"cancelled"`, or `"expired"`, and the poll response and webhook carry an `error` string. For example, a video that the provider's output moderation blocked fails with `Generated video rejected by content moderation.` Change the prompt or inputs before you retry; resubmitting the same request usually fails the same way.

## Billing

* Requests rejected by `POST /api/v1/videos` with a `4xx` are not billed. A `5xx` from submit can leave the outcome unknown: the job may still have started and can complete and bill. Don't blindly resubmit after a `5xx`, because a retry can create a second paid job.
* When a job is accepted, OpenRouter places a hold for its estimated cost against your balance and key limit. The hold counts toward your spend while the job runs.
* A job is billed when it completes with a usable video. The final cost is in `usage.cost` on the poll response.
* If the job fails, is cancelled, expires, or completes without a retrievable video, the hold is usually released and you are not charged. Two exceptions: a job can fail and still be charged when the provider reports billable usage for output it blocked in moderation, and a completed job can be billed when OpenRouter can't confirm whether its output is available. The poll response includes `usage` only for completed jobs, so a `failed` job without `usage.cost` may still have been charged. Check your [activity](https://openrouter.ai/activity) before you assume a retry won't add a charge.

## Webhooks and signature verification

When `callback_url` is configured on the request (or set as the workspace default in [Workspace Settings](https://openrouter.ai/docs/guides/features/workspaces.md)), OpenRouter sends an HTTPS `POST` payload upon job completion, failure, expiration, or cancellation.

### Webhook payload example

```json theme={null}
{
  "type": "video.generation.completed",
  "created_at": "2026-11-10T22:30:00.000Z",
  "data": {
    "id": "gen-vid-1789480874-Ab3dEf9hIjKlMnOpQrSt",
    "generation_id": "gen-vid-1789480874-Ab3dEf9hIjKlMnOpQrSt",
    "model": "google/veo-3.1",
    "status": "completed",
    "urls": [
      "https://storage.openrouter.ai/generated-media/video-sample.mp4?token=..."
    ],
    "expires_at": 1789567274,
    "unsigned_urls": [
      "/api/v1/videos/gen-vid-1789480874-Ab3dEf9hIjKlMnOpQrSt/content?index=0"
    ],
    "usage": {
      "cost": 0.5,
      "is_byok": false
    }
  }
}
```

### Verifying signatures

Setting a `callback_url` doesn't create a signing secret. To get one, open your workspace settings and select **Generate signing secret** under **Webhook signing secret**; video and batch deliveries share it. With a secret configured, OpenRouter includes an `X-OpenRouter-Signature` header on every delivery containing a timestamp (`t`) and HMAC-SHA256 hash (`v1`). Without one, deliveries are unsigned and can't be told apart from a forged request, so reject any delivery whose signature header is missing or invalid with a non-`2xx` response:

```lines theme={null}
X-OpenRouter-Signature: t=1789480874,v1=9f83c18b76...
```

Verify signatures using the raw, unparsed request body:

```typescript theme={null}
import crypto from 'node:crypto';

function verifyWebhook(rawBody: string, signatureHeader: string, secret: string): boolean {
  // An empty secret produces an HMAC anyone can compute, so treat it as misconfiguration.
  if (!secret) {
    return false;
  }

  const parts = signatureHeader.split(',');
  const timestamp = parts.find((p) => p.startsWith('t='))?.slice(2);
  const hash = parts.find((p) => p.startsWith('v1='))?.slice(3);

  if (!timestamp || !hash) {
    return false;
  }

  const tsSeconds = Number(timestamp);
  if (!Number.isFinite(tsSeconds)) {
    return false;
  }

  // Reject replay attempts older than 5 minutes
  if (Math.abs(Math.floor(Date.now() / 1000) - tsSeconds) > 300) {
    return false;
  }

  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(`${timestamp},${rawBody}`)
    .digest('hex');

  const expectedBuf = Buffer.from(expectedSignature, 'utf8');
  const receivedBuf = Buffer.from(hash, 'utf8');

  if (expectedBuf.length !== receivedBuf.length) {
    return false;
  }

  return crypto.timingSafeEqual(expectedBuf, receivedBuf);
}
```

```python title="Python" lines theme={null}
import hashlib
import hmac
import math
import time


def verify_webhook(raw_body: str, signature_header: str, secret: str) -> bool:
    # An empty secret produces an HMAC anyone can compute, so treat it as misconfiguration.
    if not secret:
        return False

    parts = signature_header.split(",")
    timestamp = next((p[2:] for p in parts if p.startswith("t=")), None)
    received = next((p[3:] for p in parts if p.startswith("v1=")), None)

    if not timestamp or not received:
        return False

    try:
        ts_seconds = float(timestamp)
    except ValueError:
        return False
    if not math.isfinite(ts_seconds):
        return False

    # Reject replay attempts older than 5 minutes
    if abs(int(time.time()) - ts_seconds) > 300:
        return False

    expected = hmac.new(
        secret.encode(), f"{timestamp},{raw_body}".encode(), hashlib.sha256
    ).hexdigest()

    return hmac.compare_digest(expected.encode(), received.encode())

```

```go title="Go" lines theme={null}
func verifyWebhook(rawBody, signatureHeader, secret string) bool {
	// An empty secret produces an HMAC anyone can compute, so treat it as misconfiguration.
	if secret == "" {
		return false
	}

	var timestamp, hash string
	for _, p := range strings.Split(signatureHeader, ",") {
		if timestamp == "" && strings.HasPrefix(p, "t=") {
			timestamp = p[2:]
		} else if hash == "" && strings.HasPrefix(p, "v1=") {
			hash = p[3:]
		}
	}

	if timestamp == "" || hash == "" {
		return false
	}

	tsSeconds, err := strconv.ParseFloat(timestamp, 64)
	if err != nil || math.IsInf(tsSeconds, 0) || math.IsNaN(tsSeconds) {
		return false
	}

	// Reject replay attempts older than 5 minutes
	if math.Abs(float64(time.Now().Unix())-tsSeconds) > 300 {
		return false
	}

	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(timestamp + "," + rawBody))
	expectedSignature := hex.EncodeToString(mac.Sum(nil))

	return hmac.Equal([]byte(expectedSignature), []byte(hash))
}
```

Each delivery also carries an `X-OpenRouter-Idempotency-Key` header of the form `<jobId>-<status>`. Failed deliveries are retried, so use the key to deduplicate them. Record it in the same transaction that applies the event, return a non-`2xx` response if processing fails so the retry can recover, and acknowledge a key you've already recorded without acting on it again.

## Zero Data Retention (ZDR) policy

Video generation is **not eligible** for [Zero Data Retention (ZDR)](https://openrouter.ai/docs/guides/features/zdr.md). Because video generation is asynchronous, provider endpoints must temporarily retain the generated media artifact so your application can retrieve it via the polling or content download endpoints. If your account or API key enforces ZDR mode, video generation requests will be rejected with an HTTP `400` error.
