# Video webhooks

Have the end of a video job posted to your server, instead of asking for it.

1. [Put up a receiver](#1-put-up-a-receiver) on a public HTTPS address.
2. [Send the job with that address](#2-send-the-job-with-that-address) in `callback_url`.
3. [Read the post](#3-read-the-post).
4. [Fetch the clip](#4-fetch-the-clip).

## 1. Put up a receiver

When a job ends, OpenDunes sends a `POST` with a JSON body to the address you gave. The receiver below answers `200` at once, drops a post it has already seen, and prints the job's end. It listens on port 8080: put it behind your app's HTTPS address.

```python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer

PORT = 8080
seen = set()


class Receiver(BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers["Content-Length"])
        event = json.loads(self.rfile.read(length))
        key = self.headers["X-OpenDunes-Idempotency-Key"]

        self.send_response(200)
        self.end_headers()

        if key in seen:
            return
        seen.add(key)

        job = event["data"]
        if event["type"] == "video.generation.completed":
            print(job["id"], "completed", job["usage"]["cost"], "DA")
        else:
            print(job["id"], job["status"], job.get("error"))


HTTPServer(("", PORT), Receiver).serve_forever()
```

```javascript
import { createServer } from "node:http";

const PORT = 8080;
const seen = new Set();

createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) body += chunk;
  res.writeHead(200).end();

  const key = req.headers["x-opendunes-idempotency-key"];
  if (req.method !== "POST" || seen.has(key)) return;
  seen.add(key);

  const event = JSON.parse(body);
  const job = event.data;
  if (event.type === "video.generation.completed") {
    console.log(job.id, "completed", job.usage.cost, "DA");
  } else {
    console.log(job.id, job.status, job.error);
  }
}).listen(PORT);
```

```go
package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"sync"
)

const port = ":8080"

var (
	mu   sync.Mutex
	seen = map[string]bool{}
)

type event struct {
	Type string `json:"type"`
	Data struct {
		ID     string `json:"id"`
		Status string `json:"status"`
		Error  any    `json:"error"`
		Usage  *struct {
			Cost float64 `json:"cost"`
		} `json:"usage"`
	} `json:"data"`
}

func receive(w http.ResponseWriter, r *http.Request) {
	var e event
	err := json.NewDecoder(r.Body).Decode(&e)
	w.WriteHeader(http.StatusOK)
	if err != nil || r.Method != http.MethodPost {
		return
	}

	key := r.Header.Get("X-OpenDunes-Idempotency-Key")
	mu.Lock()
	repeat := seen[key]
	seen[key] = true
	mu.Unlock()
	if repeat {
		return
	}

	job := e.Data
	if e.Type == "video.generation.completed" && job.Usage != nil {
		fmt.Println(job.ID, "completed", job.Usage.Cost, "DA")
	} else {
		fmt.Println(job.ID, job.Status, job.Error)
	}
}

func main() {
	http.HandleFunc("/", receive)
	if err := http.ListenAndServe(port, nil); err != nil {
		panic(err)
	}
}
```

<div class="dont">
<p>Do slow work before you answer. A post that gets no 2xx is sent again, and your work runs twice.</p>
</div>
<div class="do">
<p>Answer 2xx first, then work. Drop a post whose <code>X-OpenDunes-Idempotency-Key</code> you have already handled.</p>
</div>

The receiver keeps the keys it has seen in memory, lost at each restart. In your app, keep them where your jobs are kept.

## 2. Send the job with that address

Add `callback_url` to the job: your receiver's public HTTPS address. The samples read it from the environment variable `VIDEO_CALLBACK_URL`, for example `https://your-app.dz/hooks/video`. The rest of the job is as in [Text to video](/docs/cookbook/text-to-video).

```python
import json
import os
import urllib.request

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/videos"
MODEL = "alibaba/wan-3.0"
PROMPT = "Fishing boats leave the port of Béjaïa at dawn, wide shot"
CALLBACK_URL = os.environ["VIDEO_CALLBACK_URL"]

request = urllib.request.Request(
    ADDRESS,
    data=json.dumps(
        {
            "model": MODEL,
            "prompt": PROMPT,
            "duration": 5,
            "resolution": "480p",
            "aspect_ratio": "16:9",
            "callback_url": CALLBACK_URL,
        }
    ).encode(),
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json",
    },
)
with urllib.request.urlopen(request) as response:
    job = json.load(response)

print(job["id"], job["status"])
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/videos";
const MODEL = "alibaba/wan-3.0";
const PROMPT = "Fishing boats leave the port of Béjaïa at dawn, wide shot";
const CALLBACK_URL = process.env.VIDEO_CALLBACK_URL;

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: MODEL,
    prompt: PROMPT,
    duration: 5,
    resolution: "480p",
    aspect_ratio: "16:9",
    callback_url: CALLBACK_URL,
  }),
});
const job = await response.json();

console.log(job.id, job.status);
```

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

const (
	address = "https://opendunes.com/v1/videos"
	model   = "alibaba/wan-3.0"
	prompt  = "Fishing boats leave the port of Béjaïa at dawn, wide shot"
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")
	callbackURL := os.Getenv("VIDEO_CALLBACK_URL")

	body, err := json.Marshal(map[string]any{
		"model":        model,
		"prompt":       prompt,
		"duration":     5,
		"resolution":   "480p",
		"aspect_ratio": "16:9",
		"callback_url": callbackURL,
	})
	if err != nil {
		panic(err)
	}

	req, err := http.NewRequest("POST", address, bytes.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var job struct {
		ID     string `json:"id"`
		Status string `json:"status"`
	}
	if err := json.NewDecoder(res.Body).Decode(&job); err != nil {
		panic(err)
	}
	fmt.Println(job.ID, job.Status)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/videos"
MODEL="alibaba/wan-3.0"
PROMPT="Fishing boats leave the port of Béjaïa at dawn, wide shot"

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "prompt": "'"$PROMPT"'",
    "duration": 5,
    "resolution": "480p",
    "aspect_ratio": "16:9",
    "callback_url": "'"$VIDEO_CALLBACK_URL"'"
  }'
```

The answer is `202`, with the job's `id` and `status` `pending`: keep the `id`. An address that is not HTTPS on the public internet gets a 400, and no job is made. Every field: [Clips](/docs/reference/videos).

<div class="good-to-know">
<p>Asking still works beside a <code>callback_url</code>. If your receiver was down when the job ended, <a href="/docs/reference/videos-id"><code>GET /v1/videos/{id}</code></a> still answers how it ended, free.</p>
</div>

## 3. Read the post

One post per job, when it ends. The `type` names the end.

| `type` | The job |
|---|---|
| `video.generation.completed` | made the clip |
| `video.generation.failed` | failed; `data.error` holds the provider's reason |
| `video.generation.cancelled` | was cancelled |
| `video.generation.expired` | lapsed before a clip was made |

| Field | Holds |
|---|---|
| `type` | the end, from the table above |
| `created_at` | when the post was sent |
| `data` | the job as the last ask would answer it, with its `model` |

A completed post, illustrative:

```json
{
  "type": "video.generation.completed",
  "created_at": "2026-09-29T09:20:11Z",
  "data": {
    "id": "3f2b8c1e-6a4d-4e9b-9c7a-2d5e8f1a0b64",
    "status": "completed",
    "model": "alibaba/wan-3.0",
    "unsigned_urls": [
      "https://opendunes.com/v1/videos/3f2b8c1e-…/content?index=0"
    ],
    "usage": {
      "cost": 42.5,
      "is_byok": false
    }
  }
}
```

Each post carries `X-OpenDunes-Idempotency-Key`: the job `id` and the status, joined by `-`, the same on every repeat of one post.

<div class="watch-out">
<p>A post can arrive twice. Answer any 2xx; a post that gets none is sent again, up to six times in all. Handle a key once.</p>
</div>

## 4. Fetch the clip

On `video.generation.completed`, fetch the clip with the job `id` and your API key: [`GET /v1/videos/{id}/content?index=0`](/docs/reference/videos-content). The answer is the MP4's bytes, free to fetch as often as you like. Text to video saves one in its last lines.

The charge was taken once, at `completed`, and `data.usage.cost` carries it in DA. A job that ends any other way charges nothing.
