Kooma API
Français API keys Sign up

SDKs & examples

There is nothing special to install: the API is plain REST, usable from any HTTP client.

Prerequisites

An HTTP client in your language. In Python, requests ; in JavaScript, fetch (native). Get the API key and keep it server-side.

Specification & playground

OpenAPI spec/openapi.json — import it into Postman, Insomnia or a client generator.
Playground/playground — test each call and copy the generated code.
# import the spec into Postman / Insomnia
curl -O https://api.kooma.ai/openapi.json

Python client

No dependencies: the standard library is enough. Copy, paste, done.

import json, time, urllib.request, urllib.error

class Kooma:
    def __init__(self, cle, base="https://api.kooma.ai/v1"):
        self.cle, self.base = cle, base

    def _appel(self, chemin, corps=None, methode="GET", brut=False):
        données = json.dumps(corps).encode() if corps is not None else None
        entêtes = {"Authorization": f"Bearer {self.cle}"}
        if données:
            entêtes["Content-Type"] = "application/json"
        rq = urllib.request.Request(self.base + chemin, data=données,
                                    headers=entêtes, method=methode)
        for tentative in range(5):
            try:
                with urllib.request.urlopen(rq, timeout=120) as r:
                    return r.read() if brut else json.loads(r.read())
            except urllib.error.HTTPError as e:
                # 429 : on respecte Retry-After plutôt que de réessayer à l'aveugle.
                if e.code == 429 and tentative < 4:
                    time.sleep(int(e.headers.get("Retry-After") or 2 ** tentative))
                    continue
                raise

    # --- appels synchrones ---
    def voix(self):
        return self._appel("/voices")

    def parler(self, texte, voice, response_format="wav"):
        return self._appel("/audio/speech", {"input": texte, "voice": voice,
                                             "response_format": response_format}, "POST", brut=True)

    def traduire(self, texte, source, cible):
        return self._appel("/translations", {"text": texte, "source": source,
                                             "target": cible}, "POST")["translations"][0]["text"]

    # --- job asynchrone : création, attente, récupération ---
    def attendre(self, chemin_job, intervalle=5, limite=1800):
        """Interroge jusqu'à un état terminal. Préférez un webhook si vous le pouvez :
        cette boucle existe pour les cas où vous n'avez pas de serveur joignable."""
        début = time.time()
        while time.time() - début < limite:
            job = self._appel(chemin_job)
            if job.get("status") in ("done", "error"):
                return job
            time.sleep(intervalle)
        raise TimeoutError("le job n'a pas abouti dans le délai imparti")


k = Kooma("sk-intermo-YOUR_KEY")
open("sortie.wav", "wb").write(k.parler("Aw ni ce", voice="modibo"))
print(k.traduire("Bonjour", "fra_Latn", "bam_Latn"))

JavaScript client

No dependencies either: fetch built in, Node 18+ or browser (server-side only — never put your key in code the browser runs).

class Kooma {
  constructor(cle, base = "https://api.kooma.ai/v1") { this.cle = cle; this.base = base; }

  async appel(chemin, { corps, methode = "GET", brut = false } = {}) {
    const entetes = { Authorization: `Bearer ${this.cle}` };
    if (corps) entetes["Content-Type"] = "application/json";
    for (let tentative = 0; tentative < 5; tentative++) {
      const r = await fetch(this.base + chemin, {
        method: methode, headers: entetes,
        body: corps ? JSON.stringify(corps) : undefined,
      });
      // 429 : on respecte Retry-After au lieu de réessayer à l'aveugle.
      if (r.status === 429 && tentative < 4) {
        const attente = parseInt(r.headers.get("Retry-After") || 2 ** tentative, 10);
        await new Promise((s) => setTimeout(s, attente * 1000));
        continue;
      }
      if (!r.ok) throw new Error(`${r.status} ${await r.text()}`);
      return brut ? Buffer.from(await r.arrayBuffer()) : r.json();
    }
  }

  voix()                          { return this.appel("/voices"); }
  parler(texte, voice)            { return this.appel("/audio/speech",
                                      { corps: { input: texte, voice }, methode: "POST", brut: true }); }
  async traduire(texte, source, cible) {
    const d = await this.appel("/translations",
                { corps: { text: texte, source, target: cible }, methode: "POST" });
    return d.translations[0].text;
  }
}

// Enveloppé dans une fonction asynchrone : `await` au premier niveau ferait basculer
// Node en mode module ES, où `require` n'existe pas. Fonctionne tel quel dans les deux cas.
(async () => {
  const fs = require("fs");
  const k = new Kooma("sk-intermo-YOUR_KEY");
  fs.writeFileSync("sortie.wav", await k.parler("Aw ni ce", "modibo"));
})();

Verifying a webhook signature

This is where integrations most often go wrong, and the mistake is silent: a badly verified signature lets anyone through.

import hmac, hashlib, time

def signature_valide(corps: bytes, entete: str, secret: str, tolerance=300) -> bool:
    parts = dict(p.split("=", 1) for p in entete.split(","))
    if abs(time.time() - int(parts["t"])) > tolerance:
        return False                                   # rejoue d'une livraison capturée
    attendu = hmac.new(secret.encode(), f"{parts['t']}.".encode() + corps,
                       hashlib.sha256).hexdigest()
    return hmac.compare_digest(attendu, parts["v1"])   # comparaison en temps constant
↑↓ navigate↵ openesc close