# Idempotency

Send a request again safely after a timeout: the same Idempotency-Key gets the first answer, and no second job starts.

When a request times out or its connection breaks, you cannot know whether the job started. Send an `Idempotency-Key` header with a unique string of your own (1 to 255 printable characters, a UUID for example), and send the same request again with the same key:

```bash
curl -sS -H "Authorization: Bearer $VATIS_KEY" -H "Idempotency-Key: 9b7f3c1e-crm-2026-118" \
  https://api.eu.vatis.tech/v1/speech-to-text -F model_id=vatis_ro_v9 -F file=@speech.wav
```

```javascript
import { openAsBlob } from "node:fs";

const form = new FormData();
form.append("model_id", "vatis_ro_v9");
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}`,
    "Idempotency-Key": "9b7f3c1e-crm-2026-118",
  },
  body: form,
});
const answer = await response.text();
if (!response.ok) {
  console.error(`${response.status}: ${answer}`);
  process.exit(1);
}
console.log(answer);
```

```go
package main

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

func main() {
	url := "https://api.eu.vatis.tech/v1/speech-to-text"

	var body bytes.Buffer
	form := multipart.NewWriter(&body)
	check(form.WriteField("model_id", "vatis_ro_v9"))
	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", url, &body)
	check(err)
	request.Header.Set("Authorization", "Bearer "+os.Getenv("VATIS_KEY"))
	request.Header.Set("Idempotency-Key", "9b7f3c1e-crm-2026-118")
	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
import os

import httpx

url = "https://api.eu.vatis.tech/v1/speech-to-text"
headers = {
    "Authorization": f"Bearer {os.environ['VATIS_KEY']}",
    "Idempotency-Key": "9b7f3c1e-crm-2026-118",
}
data = {"model_id": "vatis_ro_v9"}

with open("speech.wav", "rb") as audio:
    files = {"file": audio}
    response = httpx.post(url, headers=headers, data=data, files=files, timeout=600)
if response.is_error:
    raise SystemExit(f"{response.status_code}: {response.text}")
print(response.text)
```

```java
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 Sample {
    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";

        ByteArrayOutputStream form = new ByteArrayOutputStream();
        addPart(form, "name=\"model_id\"", "vatis_ro_v9".getBytes(UTF_8));
        addPart(form, "name=\"file\"; filename=\"speech.wav\"",
            Files.readAllBytes(Path.of("speech.wav")));
        form.write(("--" + boundary + "--\r\n").getBytes(UTF_8));

        HttpRequest request = HttpRequest.newBuilder(URI.create(url))
            .header("Authorization", "Bearer " + System.getenv("VATIS_KEY"))
            .header("Idempotency-Key", "9b7f3c1e-crm-2026-118")
            .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
using System.Net.Http.Headers;

var url = "https://api.eu.vatis.tech/v1/speech-to-text";

using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(10) };
var apiKey = Environment.GetEnvironmentVariable("VATIS_KEY");
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", apiKey);
http.DefaultRequestHeaders.Add("Idempotency-Key", "9b7f3c1e-crm-2026-118");

using var form = new MultipartFormDataContent();
form.Add(new StringContent("vatis_ro_v9"), "model_id");
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:** sent twice, both answers carry the same id, and no second job starts.

- The same key within 24 hours gets the first request's answer, also while that job still runs.
- The same key with other fields or another file: `409` `idempotency_conflict` (`param` `Idempotency-Key`).
- Keys are remembered for each API key apart.
- If the first transcript was deleted, or sent with `store=false`, the same key starts a new job.

Use a new key for every new job. Use it again only to repeat the same request.
