# Webhooks

Get a finished transcript posted to your server, signed so you know it came from us.

> **Needs batch transcription.** Webhooks deliver the transcripts of files, so they work once batch is open on your workspace ([Batch transcription](https://platform.vatis.tech/docs/batch)).

A webhook is an address on your server. When a file's transcript is done, the API posts it there, so you need no polling. Webhooks belong to the workspace: an Admin key creates and changes them, and any key's jobs can send their results to one by its id.

## 1. Create the webhook once

Give it the address of your receiver. The API must be able to reach it from the internet ([Create a webhook](https://platform.vatis.tech/docs/batch/webhooks#create-a-webhook) has the rules). Owners and admins of the workspace can also add one on the console's [Webhooks](https://platform.vatis.tech/webhooks) page.

A webhook gets both events, or only the one you choose with `events`: say the failures to an alerting tool and the transcripts to a CRM, each with a webhook of its own. The console's Webhooks page sets this too.

```bash
curl -sS -H "Authorization: Bearer $VATIS_KEY" -H "Content-Type: application/json" \
  -d '{"url": "https://crm.example.com/vatis", "name": "crm"}' https://api.eu.vatis.tech/v1/webhooks
```

```javascript
// node create_webhook.mjs, with an Admin key in VATIS_KEY
const response = await fetch("https://api.eu.vatis.tech/v1/webhooks", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.VATIS_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({ url: "https://crm.example.com/vatis", name: "crm" }),
});
const webhook = await response.json();
if (!response.ok) throw new Error(`${response.status} ${webhook.error.code}: ${webhook.error.message}`);
console.log(webhook.id, webhook.secret); // the secret is shown only now: keep it with your receiver
```

```go
// go run create_webhook.go, with an Admin key in VATIS_KEY
package main

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

func main() {
	body := strings.NewReader(`{"url": "https://crm.example.com/vatis", "name": "crm"}`)
	request, err := http.NewRequest("POST", "https://api.eu.vatis.tech/v1/webhooks", body)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))
	request.Header.Set("Content-Type", "application/json")

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()
	var webhook struct {
		ID, Secret string
		Error      struct{ Code, Message string }
	}
	check(json.NewDecoder(response.Body).Decode(&webhook))
	if response.StatusCode >= 400 {
		check(fmt.Errorf("%d %s: %s",
			response.StatusCode, webhook.Error.Code, webhook.Error.Message))
	}
	// the secret is shown only now: keep it with your receiver
	fmt.Println(webhook.ID, webhook.Secret)
}

// check stops the program on an error.
func check(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```python
"""python3 create_webhook.py, with an Admin key in VATIS_KEY"""
import os

import httpx

response = httpx.post("https://api.eu.vatis.tech/v1/webhooks", json={"url": "https://crm.example.com/vatis", "name": "crm"},
                      headers={"Authorization": f"Bearer {os.environ['VATIS_KEY']}"})
webhook = response.json()
if response.is_error:
    raise SystemExit(f"{response.status_code} {webhook['error']['code']}: {webhook['error']['message']}")
print(webhook["id"], webhook["secret"])  # the secret is shown only now: keep it with your receiver
```

```java
// java CreateWebhook.java, with an Admin key in VATIS_KEY
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class CreateWebhook {
    public static void main(String[] args) throws Exception {
        String url = "https://api.eu.vatis.tech/v1/webhooks";
        String body = "{\"url\": \"https://crm.example.com/vatis\", \"name\": \"crm\"}";
        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        Object webhook = Json.parse(response.body());
        if (response.statusCode() >= 400) {
            Object error = get(webhook, "error");
            System.err.println(response.statusCode() + " " + get(error, "code") + ": "
                + get(error, "message"));
            System.exit(1);
        }
        // the secret is shown only now: keep it with your receiver
        System.out.println(get(webhook, "id") + " " + get(webhook, "secret"));
    }

    // The value at a path of names in read JSON, as get(answer, "error", "code").
    static Object get(Object json, String... path) {
        for (String name : path) {
            json = ((Map<?, ?>) json).get(name);
        }
        return json;
    }

    // Reads JSON into maps, lists, strings, doubles, booleans and null: Java
    // has no JSON parser built in, a real program would use a library.
    static class Json {
        final String text;
        int at = 0;

        Json(String text) {
            this.text = text;
        }

        static Object parse(String text) {
            return new Json(text).value();
        }

        // The next character that is not white space.
        char next() {
            while (Character.isWhitespace(text.charAt(at))) {
                at++;
            }
            return text.charAt(at++);
        }

        Object value() {
            char first = next();
            if (first == '{') {
                Map<String, Object> object = new LinkedHashMap<>();
                if (next() != '}') {
                    at--;
                    do {
                        String name = (String) value();
                        next(); // the colon
                        object.put(name, value());
                    } while (next() == ',');
                }
                return object;
            }
            if (first == '[') {
                List<Object> array = new ArrayList<>();
                if (next() != ']') {
                    at--;
                    do {
                        array.add(value());
                    } while (next() == ',');
                }
                return array;
            }
            if (first == '"') {
                StringBuilder string = new StringBuilder();
                for (char c = text.charAt(at++); c != '"'; c = text.charAt(at++)) {
                    if (c == '\\') {
                        c = text.charAt(at++);
                        if (c == 'u') {
                            c = (char) Integer.parseInt(text.substring(at, at + 4), 16);
                            at += 4;
                        } else if ("bfnrt".indexOf(c) >= 0) {
                            c = "\b\f\n\r\t".charAt("bfnrt".indexOf(c));
                        }
                    }
                    string.append(c);
                }
                return string.toString();
            }
            // a number, true, false or null
            int start = at - 1;
            while (at < text.length() && ",:]} \t\r\n".indexOf(text.charAt(at)) < 0) {
                at++;
            }
            String word = text.substring(start, at);
            if (word.equals("null")) {
                return null;
            }
            if (word.equals("true") || word.equals("false")) {
                return Boolean.valueOf(word);
            }
            return Double.valueOf(word);
        }
    }
}
```

```csharp
// dotnet run --project create_webhook, with an Admin key in VATIS_KEY
// (first dotnet new console -o create_webhook, then put this in create_webhook/Program.cs)
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;

var url = "https://api.eu.vatis.tech/v1/webhooks";
var json = """{"url": "https://crm.example.com/vatis", "name": "crm"}""";
using var http = new HttpClient();
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("VATIS_KEY"));

var body = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await http.PostAsync(url, body);
var webhook = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
if (!response.IsSuccessStatusCode)
{
    var error = webhook.GetProperty("error");
    var message = error.GetProperty("message");
    Console.Error.WriteLine($"{(int)response.StatusCode} {error.GetProperty("code")}: {message}");
    return 1;
}
// the secret is shown only now: keep it with your receiver
Console.WriteLine($"{webhook.GetProperty("id")} {webhook.GetProperty("secret")}");
return 0;
```

**Expected result:** `201` and the webhook, with its `secret`. The secret is shown only this once: keep it with your receiver, which checks every delivery with it.

```json
{"id": "wh_a97581d905c54b46", "url": "https://crm.example.com/vatis", "name": "crm", "enabled": true, "retry": true,
 "headers": {}, "created_at": "2026-11-12T09:14:03Z", "secret": "whsec_..."}
```

## 2. Send each file with its webhook

Add `webhook_id` to the request, and `metadata` to recognise the result when it comes back. `webhook=true` instead posts to every webhook that is turned on.

```bash
WEBHOOK_ID=wh_a97581d905c54b46   # the "id" of your webhook
curl -sS -H "Authorization: Bearer $VATIS_KEY" https://api.eu.vatis.tech/v1/speech-to-text \
  -F model_id=vatis_ro_v9 -F webhook_id=$WEBHOOK_ID -F metadata='{"case": "2026-118"}' -F file=@speech.wav
```

```javascript
// node send_file.mjs, with your API key in VATIS_KEY
import { openAsBlob } from "node:fs";

const webhookId = "wh_a97581d905c54b46"; // the "id" of your webhook
const form = new FormData();
form.append("model_id", "vatis_ro_v9");
form.append("webhook_id", webhookId);
form.append("metadata", JSON.stringify({ case: "2026-118" }));
form.append("file", await openAsBlob("speech.wav"), "speech.wav");

const response = await fetch("https://api.eu.vatis.tech/v1/speech-to-text", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.VATIS_KEY}` },
  body: form,
});
const answer = await response.text();
if (!response.ok) {
  console.error(`${response.status}: ${answer}`);
  process.exit(1);
}
console.log(answer);
```

```go
// go run send_file.go, with your API key in VATIS_KEY
package main

import (
	"bytes"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"os"
)

func main() {
	webhookID := "wh_a97581d905c54b46" // the "id" of your webhook
	var body bytes.Buffer
	form := multipart.NewWriter(&body)
	check(form.WriteField("model_id", "vatis_ro_v9"))
	check(form.WriteField("webhook_id", webhookID))
	check(form.WriteField("metadata", `{"case": "2026-118"}`))
	audio, err := os.Open("speech.wav")
	check(err)
	defer audio.Close()
	part, err := form.CreateFormFile("file", "speech.wav")
	check(err)
	_, err = io.Copy(part, audio)
	check(err)
	check(form.Close())

	request, err := http.NewRequest("POST", "https://api.eu.vatis.tech/v1/speech-to-text", &body)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))
	request.Header.Set("Content-Type", form.FormDataContentType())

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()
	answer, err := io.ReadAll(response.Body)
	check(err)
	if response.StatusCode >= 400 {
		check(fmt.Errorf("%d: %s", response.StatusCode, answer))
	}
	fmt.Println(string(answer))
}

// check stops the program on an error.
func check(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```python
"""python3 send_file.py, with your API key in VATIS_KEY"""
import json
import os

import httpx

url = "https://api.eu.vatis.tech/v1/speech-to-text"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}
webhook_id = "wh_a97581d905c54b46"  # the "id" of your webhook
data = {
    "model_id": "vatis_ro_v9",
    "webhook_id": webhook_id,
    "metadata": json.dumps({"case": "2026-118"}),
}
with open("speech.wav", "rb") as audio:
    response = httpx.post(url, headers=headers, data=data, files={"file": audio}, timeout=600)
if response.is_error:
    raise SystemExit(f"{response.status_code}: {response.text}")
print(response.text)
```

```java
// java SendFile.java, with your API key in VATIS_KEY
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.nio.charset.StandardCharsets.UTF_8;

public class SendFile {
    static final String boundary = "vatis" + System.nanoTime();

    public static void main(String[] args) throws Exception {
        String url = "https://api.eu.vatis.tech/v1/speech-to-text";
        String webhookId = "wh_a97581d905c54b46"; // the "id" of your webhook
        ByteArrayOutputStream form = new ByteArrayOutputStream();
        addPart(form, "name=\"model_id\"", "vatis_ro_v9".getBytes(UTF_8));
        addPart(form, "name=\"webhook_id\"", webhookId.getBytes(UTF_8));
        addPart(form, "name=\"metadata\"", "{\"case\": \"2026-118\"}".getBytes(UTF_8));
        byte[] audio = Files.readAllBytes(Path.of("speech.wav"));
        addPart(form, "name=\"file\"; filename=\"speech.wav\"", audio);
        form.write(("--" + boundary + "--\r\n").getBytes(UTF_8));

        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .header("Content-Type", "multipart/form-data; boundary=" + boundary)
            .POST(HttpRequest.BodyPublishers.ofByteArray(form.toByteArray()))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.statusCode() + ": " + response.body());
            System.exit(1);
        }
        System.out.println(response.body());
    }

    // Adds one part to the form: Java has no multipart body built in.
    static void addPart(ByteArrayOutputStream form, String disposition, byte[] value)
            throws Exception {
        String head = "--" + boundary + "\r\n"
            + "Content-Disposition: form-data; " + disposition + "\r\n\r\n";
        form.write(head.getBytes(UTF_8));
        form.write(value);
        form.write("\r\n".getBytes(UTF_8));
    }
}
```

```csharp
// dotnet run --project send_file, with your API key in VATIS_KEY
// (first dotnet new console -o send_file, then put this in send_file/Program.cs)
using System.Net.Http.Headers;

var url = "https://api.eu.vatis.tech/v1/speech-to-text";
var webhookId = "wh_a97581d905c54b46"; // the "id" of your webhook
using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(10) };
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("VATIS_KEY"));

using var form = new MultipartFormDataContent();
form.Add(new StringContent("vatis_ro_v9"), "model_id");
form.Add(new StringContent(webhookId), "webhook_id");
form.Add(new StringContent("""{"case": "2026-118"}"""), "metadata");
using var audio = File.OpenRead("speech.wav");
form.Add(new StreamContent(audio), "file", "speech.wav");

using var response = await http.PostAsync(url, form);
var answer = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine($"{(int)response.StatusCode}: {answer}");
    return 1;
}
Console.WriteLine(answer);
return 0;
```

**Expected result:** the answer comes at once, as for every request, with the transcript queued: `{"id": "tr_bcf217549e124b7a", "status": "queued", ...}`.

## 3. Receive the result

When the transcript is done, your address gets a `POST` with a JSON body:

```json
{"event": "transcript.completed", "created_at": 1794474845,
 "data": {"id": "tr_bcf217549e124b7a", "status": "completed", "metadata": {"case": "2026-118"}, "text": "...", "words": [...], "segments": [...], "speakers": [...]}}
```

`data` is the whole transcript ([The transcript object](https://platform.vatis.tech/docs/transcript-object)). A transcription that failed posts `transcript.failed`, with `data.status` `failed` and `data.error`. Your receiver must:

1. **Check the signature** of the raw body, before anything else, and answer `401` if it is wrong ([Check the signature](https://platform.vatis.tech/docs/batch/webhooks#check-the-signature)).
2. **Answer `2xx` at once**, then process the result. A slow answer, or an error, makes the API try again later.
3. **Process each `data.id` once.** A result can arrive twice, for example when your answer was lost.

## Check the signature

Every delivery carries a `Vatis-Signature` header: `Vatis-Signature: t=1794474845,v1=5f0c3c4e...`

- `t` is when it was signed, in Unix seconds. Refuse a `t` more than 5 minutes away from now: an old delivery sent again by someone else.
- `v1` is the HMAC-SHA256 of `<t>.<raw body>` with your webhook's secret, in hex. Compare it in constant time, on the raw bytes as they arrived, before parsing them.
- Never accept a delivery without the header.

A small receiver that checks each delivery, on port 8080, with its language's standard library (C#: an ASP.NET Core app, from `dotnet new web`):

```javascript
// node receiver.mjs, with the webhook's secret in VATIS_WEBHOOK_SECRET
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";

// Vatis-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>" with the webhook's secret>
function verify(rawBody, header, secret, toleranceS = 300) {
  const parts = Object.fromEntries((header ?? "").split(",").map((p) => [p.slice(0, p.indexOf("=")), p.slice(p.indexOf("=") + 1)]));
  const t = Number(parts.t);
  if (!Number.isInteger(t) || !parts.v1 || Math.abs(Date.now() / 1000 - t) > toleranceS) return false; // missing, or replayed
  const expected = Buffer.from(createHmac("sha256", secret).update(`${parts.t}.`).update(rawBody).digest("hex"));
  const given = Buffer.from(parts.v1);
  return given.length === expected.length && timingSafeEqual(given, expected); // takes the same time, right or wrong
}

createServer(async (request, response) => {
  const chunks = [];
  for await (const chunk of request) chunks.push(chunk);
  const rawBody = Buffer.concat(chunks); // the bytes as signed, not the parsed JSON
  if (!verify(rawBody, request.headers["vatis-signature"], process.env.VATIS_WEBHOOK_SECRET)) {
    response.writeHead(401).end();
    return;
  }
  response.writeHead(204).end(); // answer at once, then process
  const delivery = JSON.parse(rawBody);
  console.log(delivery.event, delivery.data.id, delivery.data.metadata);
}).listen(8080);
```

```go
// go run receiver.go, with the webhook's secret in VATIS_WEBHOOK_SECRET
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

// Vatis-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>"
// with the webhook's secret>
func verify(rawBody []byte, header, secret string, tolerance time.Duration) bool {
	parts := map[string]string{}
	for _, part := range strings.Split(header, ",") {
		if name, value, found := strings.Cut(part, "="); found {
			parts[name] = value
		}
	}
	t, err := strconv.ParseInt(parts["t"], 10, 64)
	if err != nil || parts["v1"] == "" || time.Since(time.Unix(t, 0)).Abs() > tolerance {
		return false // missing, or replayed
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(parts["t"] + "."))
	mac.Write(rawBody)
	expected := hex.EncodeToString(mac.Sum(nil))
	return hmac.Equal([]byte(parts["v1"]), []byte(expected)) // takes the same time, right or wrong
}

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		rawBody, err := io.ReadAll(r.Body) // the bytes as signed, not the parsed JSON
		header, secret := r.Header.Get("Vatis-Signature"), os.Getenv("VATIS_WEBHOOK_SECRET")
		if err != nil || !verify(rawBody, header, secret, 5*time.Minute) {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		w.WriteHeader(http.StatusNoContent) // answer at once, then process
		w.(http.Flusher).Flush()
		var delivery struct {
			Event string
			Data  struct {
				ID       string
				Metadata json.RawMessage
			}
		}
		if err := json.Unmarshal(rawBody, &delivery); err != nil {
			log.Print(err)
			return
		}
		fmt.Println(delivery.Event, delivery.Data.ID, string(delivery.Data.Metadata))
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}
```

```python
"""python3 receiver.py, with the webhook's secret in VATIS_WEBHOOK_SECRET"""
import hashlib
import hmac
import json
import os
import time
from http.server import BaseHTTPRequestHandler, HTTPServer

def verify(raw_body: bytes, header: str | None, secret: str, tolerance_s: int = 300) -> bool:
    """Vatis-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>" with the webhook's secret>."""
    parts = dict(p.split("=", 1) for p in (header or "").split(",") if "=" in p)
    t, v1 = parts.get("t", ""), parts.get("v1", "")
    if not t.isdigit() or not v1 or abs(time.time() - int(t)) > tolerance_s:  # missing, or replayed
        return False
    expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected.encode(), v1.encode())  # takes the same time, right or wrong

class Receiver(BaseHTTPRequestHandler):
    def do_POST(self):
        raw_body = self.rfile.read(int(self.headers.get("Content-Length", 0)))  # the bytes as signed
        if not verify(raw_body, self.headers.get("Vatis-Signature"), os.environ["VATIS_WEBHOOK_SECRET"]):
            self.send_response(401)
            self.end_headers()
            return
        self.send_response(204)  # answer at once, then process
        self.end_headers()
        delivery = json.loads(raw_body)
        print(delivery["event"], delivery["data"]["id"], delivery["data"]["metadata"])

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

```java
// java Receiver.java, with the webhook's secret in VATIS_WEBHOOK_SECRET
import com.sun.net.httpserver.HttpServer;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import static java.nio.charset.StandardCharsets.UTF_8;

public class Receiver {
    // Vatis-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>"
    // with the webhook's secret>
    static boolean verify(byte[] rawBody, String header, String secret, long toleranceS) {
        Map<String, String> parts = new HashMap<>();
        for (String part : (header == null ? "" : header).split(",")) {
            int at = part.indexOf('=');
            if (at >= 0) {
                parts.put(part.substring(0, at), part.substring(at + 1));
            }
        }
        String t = parts.getOrDefault("t", ""), v1 = parts.getOrDefault("v1", "");
        double now = System.currentTimeMillis() / 1000.0;
        if (!t.matches("[0-9]{1,18}") || v1.isEmpty()
                || Math.abs(now - Long.parseLong(t)) > toleranceS) {
            return false; // missing, or replayed
        }
        byte[] digest;
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(UTF_8), "HmacSHA256"));
            mac.update((t + ".").getBytes(UTF_8));
            digest = mac.doFinal(rawBody);
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e); // every Java has HMAC-SHA256
        }
        String expected = String.format("%064x", new BigInteger(1, digest));
        // takes the same time, right or wrong
        return MessageDigest.isEqual(expected.getBytes(UTF_8), v1.getBytes(UTF_8));
    }

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/", (exchange) -> {
            byte[] rawBody = exchange.getRequestBody().readAllBytes(); // the bytes as signed
            String header = exchange.getRequestHeaders().getFirst("Vatis-Signature");
            if (!verify(rawBody, header, System.getenv("VATIS_WEBHOOK_SECRET"), 300)) {
                exchange.sendResponseHeaders(401, -1);
                exchange.close();
                return;
            }
            exchange.sendResponseHeaders(204, -1); // answer at once, then process
            exchange.close();
            Object delivery = Json.parse(new String(rawBody, UTF_8));
            Object data = get(delivery, "data");
            System.out.println(get(delivery, "event") + " " + get(data, "id") + " "
                + get(data, "metadata"));
        });
        server.start();
    }

    // The value at a path of names in read JSON, as get(answer, "error", "code").
    static Object get(Object json, String... path) {
        for (String name : path) {
            json = ((Map<?, ?>) json).get(name);
        }
        return json;
    }

    // Reads JSON into maps, lists, strings, doubles, booleans and null: Java
    // has no JSON parser built in, a real program would use a library.
    static class Json {
        final String text;
        int at = 0;

        Json(String text) {
            this.text = text;
        }

        static Object parse(String text) {
            return new Json(text).value();
        }

        // The next character that is not white space.
        char next() {
            while (Character.isWhitespace(text.charAt(at))) {
                at++;
            }
            return text.charAt(at++);
        }

        Object value() {
            char first = next();
            if (first == '{') {
                Map<String, Object> object = new LinkedHashMap<>();
                if (next() != '}') {
                    at--;
                    do {
                        String name = (String) value();
                        next(); // the colon
                        object.put(name, value());
                    } while (next() == ',');
                }
                return object;
            }
            if (first == '[') {
                List<Object> array = new ArrayList<>();
                if (next() != ']') {
                    at--;
                    do {
                        array.add(value());
                    } while (next() == ',');
                }
                return array;
            }
            if (first == '"') {
                StringBuilder string = new StringBuilder();
                for (char c = text.charAt(at++); c != '"'; c = text.charAt(at++)) {
                    if (c == '\\') {
                        c = text.charAt(at++);
                        if (c == 'u') {
                            c = (char) Integer.parseInt(text.substring(at, at + 4), 16);
                            at += 4;
                        } else if ("bfnrt".indexOf(c) >= 0) {
                            c = "\b\f\n\r\t".charAt("bfnrt".indexOf(c));
                        }
                    }
                    string.append(c);
                }
                return string.toString();
            }
            // a number, true, false or null
            int start = at - 1;
            while (at < text.length() && ",:]} \t\r\n".indexOf(text.charAt(at)) < 0) {
                at++;
            }
            String word = text.substring(start, at);
            if (word.equals("null")) {
                return null;
            }
            if (word.equals("true") || word.equals("false")) {
                return Boolean.valueOf(word);
            }
            return Double.valueOf(word);
        }
    }
}
```

```csharp
// dotnet run --project receiver, with the webhook's secret in VATIS_WEBHOOK_SECRET
// (first dotnet new web -o receiver, then put this in receiver/Program.cs)
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;

var app = WebApplication.Create(args);
app.MapPost("/", async (HttpContext context) =>
{
    using var body = new MemoryStream();
    await context.Request.Body.CopyToAsync(body);
    var rawBody = body.ToArray(); // the bytes as signed, not the parsed JSON
    var header = context.Request.Headers["Vatis-Signature"].ToString();
    if (!Verify(rawBody, header, Environment.GetEnvironmentVariable("VATIS_WEBHOOK_SECRET")!))
    {
        context.Response.StatusCode = 401;
        return;
    }
    context.Response.StatusCode = 204; // answer at once, then process
    await context.Response.CompleteAsync();
    var delivery = JsonDocument.Parse(rawBody).RootElement;
    var data = delivery.GetProperty("data");
    var metadata = data.GetProperty("metadata");
    Console.WriteLine($"{delivery.GetProperty("event")} {data.GetProperty("id")} {metadata}");
});
app.Run("http://*:8080");

// Vatis-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>"
// with the webhook's secret>
static bool Verify(byte[] rawBody, string header, string secret, int toleranceS = 300)
{
    var parts = new Dictionary<string, string>();
    foreach (var part in header.Split(','))
    {
        var at = part.IndexOf('=');
        if (at >= 0)
        {
            parts[part[..at]] = part[(at + 1)..];
        }
    }
    var t = parts.GetValueOrDefault("t", "");
    var v1 = parts.GetValueOrDefault("v1", "");
    var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() / 1000.0;
    if (!long.TryParse(t, out var seconds) || v1 == "" || Math.Abs(now - seconds) > toleranceS)
    {
        return false; // missing, or replayed
    }
    var signed = Encoding.UTF8.GetBytes(t + ".").Concat(rawBody).ToArray();
    var hash = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), signed);
    var expected = Encoding.UTF8.GetBytes(Convert.ToHexString(hash).ToLowerInvariant());
    // takes the same time, right or wrong
    return CryptographicOperations.FixedTimeEquals(expected, Encoding.UTF8.GetBytes(v1));
}
```

Keep your server's clock right: the 5 minute window depends on it.

To check your receiver, send it a test event from the console's [Webhooks](https://platform.vatis.tech/webhooks) page (the webhook's menu, Send test event). A test is signed like any delivery and never retried, and its `data.id` is always `tr_0000000000000000`, so your receiver can tell it from a real job.

## Deliveries

| What | Rule |
|---|---|
| Events | `transcript.completed`, `transcript.failed`. |
| Body | `{"event", "created_at", "data"}`, fixed when the job ends. `created_at`: Unix seconds, when the job ended. `data`: the whole transcript object, with its words, segments and `exports`. |
| Targets | The webhook of `webhook_id`, or every webhook enabled when the job ends (`webhook=true`), if it has the event in its `events`. A job that names a webhook without its event sends it nothing. |
| Headers | `Content-Type: application/json`, `Vatis-Signature`, and the webhook's own `headers`. |
| Signature | Signed again at each attempt, with a new `t`. |
| Success | Any `2xx` answer, within 15 s for the whole attempt. The body of your answer is not read. |
| Retries | After a `5xx`, `408` or `429` answer, a timeout or a connection error: 5 more attempts, about 30 s, 2 min, 8 min, 30 min and 30 min apart, unless the webhook's `retry` is off. Pending deliveries are not lost when the service restarts. |
| Not retried | Other `4xx` answers, redirects (a `3xx` is not followed), and an address the API may not reach. |
| `store=false` | The transcript and its upload are deleted after the last delivery attempt. |

## Manage webhooks

With an Admin key. A Member key gets `403` `admin_only`, though its jobs can still use a webhook by its id.

### Create a webhook

`POST /v1/webhooks`

Body: a JSON object. Answers `201` and the webhook with its `secret`, shown only here.

| Field | Values | Default | What it does |
|---|---|---|---|
| `url` | `http://` or `https://`, up to 2048 characters | required | Where deliveries go. |
| `name` | up to 200 characters, or `null` |  | A name for your own use. |
| `headers` | a JSON object of strings |  | Your own headers, sent with each delivery. |
| `retry` | `true`, `false` | `true` | Retry failed deliveries. |
| `events` | a JSON list of `transcript.completed`, `transcript.failed` or both | both | Which ends of a batch job it gets. |

- **`url`** must be reachable from the internet: loopback, link-local and private network addresses are refused (`400` `invalid_parameter`). A name that leads to one passes here, and its deliveries then fail without a retry.
- **`headers`:** at most 20; valid header names up to 256 characters; values of printable ASCII up to 4096 characters. Not `Content-Type`, `Content-Length`, `Host`, `Vatis-Signature`, `Transfer-Encoding`, `Connection`, `Keep-Alive`, `Upgrade`, `TE`, `Trailer`, `Expect`, or any `Proxy-` header.
- **`events`:** each once; an empty list or another name is `400` `invalid_parameter`.
- **At most 50 webhooks** in a workspace: the 51st is `400` `invalid_request`.
- **The secret cannot be changed:** create a new webhook, move your receiver to its secret, then delete the old one.
- A new webhook is on (`enabled` `true`). `enabled` is not a field here: turn it off with an update.

### List webhooks

`GET /v1/webhooks`

The workspace's webhooks, oldest first, never with their secrets.

```bash
curl -sS -H "Authorization: Bearer $VATIS_KEY" https://api.eu.vatis.tech/v1/webhooks
```

```javascript
// Needs Node.js 22 or newer, no packages.
// Set VATIS_KEY to your API key, then run: node sample.mjs

const url = "https://api.eu.vatis.tech/v1/webhooks";
const response = await fetch(url, {
  headers: { Authorization: `Bearer ${process.env.VATIS_KEY}` },
});
const answer = await response.text();
if (!response.ok) {
  console.error(`${response.status}: ${answer}`);
  process.exit(1);
}
console.log(answer);
```

```go
// Needs Go 1.23 or newer, standard library only.
// Set VATIS_KEY to your API key, then run: go run main.go
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	url := "https://api.eu.vatis.tech/v1/webhooks"

	request, err := http.NewRequest("GET", url, nil)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()

	answer, err := io.ReadAll(response.Body)
	check(err)
	if response.StatusCode >= 400 {
		check(fmt.Errorf("%d: %s", response.StatusCode, answer))
	}
	fmt.Println(string(answer))
}

// check stops the program on an error.
func check(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```python
# Needs Python 3.10 or newer and httpx (pip install httpx).
# Set VATIS_KEY to your API key, then run: python3 sample.py
import os

import httpx

url = "https://api.eu.vatis.tech/v1/webhooks"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}

response = httpx.get(url, headers=headers, timeout=60)
if response.is_error:
    raise SystemExit(f"{response.status_code}: {response.text}")
print(response.text)
```

```java
// Needs Java 11 or newer, nothing to install.
// Set VATIS_KEY to your API key, then run: java Sample.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Sample {
    public static void main(String[] args) throws Exception {
        String url = "https://api.eu.vatis.tech/v1/webhooks";

        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.statusCode() + ": " + response.body());
            System.exit(1);
        }
        System.out.println(response.body());
    }
}
```

```csharp
// Needs .NET 8 or newer, no packages. In a new folder:
// dotnet new console -o sample, then put this in sample/Program.cs
// Set VATIS_KEY to your API key, then run: dotnet run --project sample
using System.Net.Http.Headers;

var url = "https://api.eu.vatis.tech/v1/webhooks";

using var http = new HttpClient();
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);

using var response = await http.GetAsync(url);
var answer = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine($"{(int)response.StatusCode}: {answer}");
    return 1;
}
Console.WriteLine(answer);
return 0;
```

```json
{"webhooks": [{"id": "wh_a97581d905c54b46", "url": "https://crm.example.com/vatis", "name": "crm", "enabled": true,
               "retry": true, "headers": {}, "events": ["transcript.completed", "transcript.failed"],
               "created_at": "2026-11-12T09:14:03Z"}]}
```

| Field | What it is |
|---|---|
| `id` | `wh_` and 16 hex digits. |
| `url` | Where deliveries go. |
| `name` | Your name for it, or `null`. |
| `enabled` | Whether deliveries go out. |
| `retry` | Whether failed deliveries are retried. |
| `headers` | Your own headers for each delivery, `{}` when there are none. |
| `events` | The events it gets: `transcript.completed`, `transcript.failed` or both, in that order. |
| `created_at` | ISO 8601, UTC. |

### Update a webhook

`PATCH /v1/webhooks/{id}`

Send only the fields to change: any of `url`, `name`, `enabled`, `retry`, `headers`, `events`, with the rules of [Create a webhook](https://platform.vatis.tech/docs/batch/webhooks#create-a-webhook). `headers` and `events` replace the whole list. Answers `200` and the webhook, without its secret.

```bash
curl -sS -X PATCH -H "Authorization: Bearer $VATIS_KEY" -H "Content-Type: application/json" \
  -d '{"enabled": false}' https://api.eu.vatis.tech/v1/webhooks/wh_a97581d905c54b46
```

```javascript
// Needs Node.js 22 or newer, no packages.
// Set VATIS_KEY to your API key, then run: node sample.mjs

const webhookId = "wh_a97581d905c54b46";

const url = `https://api.eu.vatis.tech/v1/webhooks/${webhookId}`;
const response = await fetch(url, {
  method: "PATCH",
  headers: {
    Authorization: `Bearer ${process.env.VATIS_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ enabled: false }),
});
const answer = await response.text();
if (!response.ok) {
  console.error(`${response.status}: ${answer}`);
  process.exit(1);
}
console.log(answer);
```

```go
// Needs Go 1.23 or newer, standard library only.
// Set VATIS_KEY to your API key, then run: go run main.go
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

func main() {
	webhookID := "wh_a97581d905c54b46"
	url := "https://api.eu.vatis.tech/v1/webhooks/" + webhookID
	body := strings.NewReader(`{"enabled": false}`)

	request, err := http.NewRequest("PATCH", url, body)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))
	request.Header.Set("Content-Type", "application/json")

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()

	answer, err := io.ReadAll(response.Body)
	check(err)
	if response.StatusCode >= 400 {
		check(fmt.Errorf("%d: %s", response.StatusCode, answer))
	}
	fmt.Println(string(answer))
}

// check stops the program on an error.
func check(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```python
# Needs Python 3.10 or newer and httpx (pip install httpx).
# Set VATIS_KEY to your API key, then run: python3 sample.py
import os

import httpx

webhook_id = "wh_a97581d905c54b46"
url = f"https://api.eu.vatis.tech/v1/webhooks/{webhook_id}"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}
data = {"enabled": False}

response = httpx.patch(url, headers=headers, json=data, timeout=60)
if response.is_error:
    raise SystemExit(f"{response.status_code}: {response.text}")
print(response.text)
```

```java
// Needs Java 11 or newer, nothing to install.
// Set VATIS_KEY to your API key, then run: java Sample.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Sample {
    public static void main(String[] args) throws Exception {
        String webhookId = "wh_a97581d905c54b46";
        String url = "https://api.eu.vatis.tech/v1/webhooks/" + webhookId;
        String body = "{\"enabled\": false}";

        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .header("Content-Type", "application/json")
            .method("PATCH", HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.statusCode() + ": " + response.body());
            System.exit(1);
        }
        System.out.println(response.body());
    }
}
```

```csharp
// Needs .NET 8 or newer, no packages. In a new folder:
// dotnet new console -o sample, then put this in sample/Program.cs
// Set VATIS_KEY to your API key, then run: dotnet run --project sample
using System.Net.Http.Headers;
using System.Text;

var webhookId = "wh_a97581d905c54b46";
var url = $"https://api.eu.vatis.tech/v1/webhooks/{webhookId}";

using var http = new HttpClient();
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);
var json = """{"enabled": false}""";
var body = new StringContent(json, Encoding.UTF8, "application/json");

using var response = await http.PatchAsync(url, body);
var answer = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine($"{(int)response.StatusCode}: {answer}");
    return 1;
}
Console.WriteLine(answer);
return 0;
```

**Expected result:** the webhook, with `"enabled": false`. Jobs sent with its id are then refused (`400` `invalid_parameter`, `param` `webhook_id`).

### Delete a webhook

`DELETE /v1/webhooks/{id}`

Deletes the webhook, and drops the deliveries still pending for it. Answers `204`, with no body.

```bash
curl -sS -X DELETE -H "Authorization: Bearer $VATIS_KEY" -w "%{http_code}\n" https://api.eu.vatis.tech/v1/webhooks/wh_a97581d905c54b46
```

```javascript
// Needs Node.js 22 or newer, no packages.
// Set VATIS_KEY to your API key, then run: node sample.mjs

const webhookId = "wh_a97581d905c54b46";

const url = `https://api.eu.vatis.tech/v1/webhooks/${webhookId}`;
const response = await fetch(url, {
  method: "DELETE",
  headers: { Authorization: `Bearer ${process.env.VATIS_KEY}` },
});
if (!response.ok) {
  console.error(`${response.status}: ${await response.text()}`);
  process.exit(1);
}
console.log(response.status);
```

```go
// Needs Go 1.23 or newer, standard library only.
// Set VATIS_KEY to your API key, then run: go run main.go
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	webhookID := "wh_a97581d905c54b46"
	url := "https://api.eu.vatis.tech/v1/webhooks/" + webhookID

	request, err := http.NewRequest("DELETE", url, nil)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))

	response, err := http.DefaultClient.Do(request)
	check(err)
	defer response.Body.Close()

	answer, err := io.ReadAll(response.Body)
	check(err)
	if response.StatusCode >= 400 {
		check(fmt.Errorf("%d: %s", response.StatusCode, answer))
	}
	fmt.Println(response.StatusCode)
}

// check stops the program on an error.
func check(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

```python
# Needs Python 3.10 or newer and httpx (pip install httpx).
# Set VATIS_KEY to your API key, then run: python3 sample.py
import os

import httpx

webhook_id = "wh_a97581d905c54b46"
url = f"https://api.eu.vatis.tech/v1/webhooks/{webhook_id}"
headers = {"Authorization": f"Bearer {os.environ['VATIS_KEY']}"}

response = httpx.delete(url, headers=headers, timeout=60)
if response.is_error:
    raise SystemExit(f"{response.status_code}: {response.text}")
print(response.status_code)
```

```java
// Needs Java 11 or newer, nothing to install.
// Set VATIS_KEY to your API key, then run: java Sample.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Sample {
    public static void main(String[] args) throws Exception {
        String webhookId = "wh_a97581d905c54b46";
        String url = "https://api.eu.vatis.tech/v1/webhooks/" + webhookId;

        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .DELETE()
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.statusCode() + ": " + response.body());
            System.exit(1);
        }
        System.out.println(response.statusCode());
    }
}
```

```csharp
// Needs .NET 8 or newer, no packages. In a new folder:
// dotnet new console -o sample, then put this in sample/Program.cs
// Set VATIS_KEY to your API key, then run: dotnet run --project sample
using System.Net.Http.Headers;

var webhookId = "wh_a97581d905c54b46";
var url = $"https://api.eu.vatis.tech/v1/webhooks/{webhookId}";

using var http = new HttpClient();
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);

using var response = await http.DeleteAsync(url);
var answer = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine($"{(int)response.StatusCode}: {answer}");
    return 1;
}
Console.WriteLine((int)response.StatusCode);
return 0;
```

### Errors when managing webhooks

| Status and code | When |
|---|---|
| `400` `missing_parameter` | No `url` when creating one. |
| `400` `invalid_parameter` | A field unknown or not valid, or a query parameter (these endpoints take none). `param` names it. |
| `400` `invalid_request` | A body that is not a JSON object, or a 51st webhook. |
| `401` `unauthorized` | No key, or a wrong, revoked or expired one. |
| `403` `admin_only` | A Member key. |
| `404` `not_found` | An unknown webhook id. |
| `413` `request_too_large` | A body over 64 KB. |

## Next steps

- [Keeping nothing](https://platform.vatis.tech/docs/batch/manage-transcripts#keeping-nothing): delete each transcript after its delivery, with `store=false`.
- [Files with the transcript itself](https://platform.vatis.tech/docs/batch/exports#files-with-the-transcript-itself): text and subtitles in the delivery.
- [Errors](https://platform.vatis.tech/docs/errors): every code, and what to do about it.
