Authentication

Pass your API key as a Bearer token on every request.

Authorization: Bearer rtk_…
  • Keys are scoped to a single organization: every request, upload, job and quota check stays inside that organization — a key can never see another organization's data.
  • A revoked key stops authenticating immediately, with no grace period — the next request made with it gets a 401.
  • If your organization is suspended or permanently deleted, every key on it stops working immediately too, even though the key record itself is untouched.
  • GET /languages and GET /openapi.json are the two exceptions — public reference endpoints that need no key at all.

Quotas and credits

Every service draws from one shared credit pool per organization — there's no separate quota per service.

  • A transcription job is charged one credit per second of audio, rounded up, when processing starts and the length is known. A job your remaining credits cannot cover fails with QUOTA_EXCEEDED, and a job that fails is refunded.
  • A document job is charged OCR_CREDITS_PER_PAGE credits per page, deducted once the page count is known — at completion, not at submit time.

The submit-time check for documents and voice is loose

Submitting a document job or starting a voice session only checks that your organization has credits remaining, not that its eventual cost fits inside what's left. A large document or a long call can push your balance negative before it finishes — it is never rejected up front for being too expensive to complete.

View your balance and full ledger

Errors

Every error response has the same shape. reason appears only on some errors. requestId is on every error and is also returned in the x-request-id header; quote it when you contact support. Branch on code, never on message:

{ "error": { "code": "...", "message": "...", "reason": "...", "requestId": "..." } }

Codes returned by the endpoints below:

CodeStatusMeaning
UNAUTHORIZED401Missing, malformed, unknown or revoked API key.
RATE_LIMITED429You've exceeded the rate limit below.
FORBIDDEN403The organization behind the key is suspended or deleted, or the audio_token or document_token you supplied belongs to a different organization.
INVALID_REQUEST400The request body failed validation.
QUOTA_EXCEEDED402Your organization has no credits remaining.
JOB_NOT_FOUND404No job with that id exists for your organization.
JOB_NOT_READY409The job hasn't reached a completed state yet.
FORMAT_NOT_AVAILABLE404That result format wasn't requested when the job was submitted.
DOCUMENT_TOO_LARGE413The document exceeds the configured size limit.
DOCUMENT_NOT_FOUND404The uploaded document object could not be found.
INVALID_SOURCE400The document or audio source could not be fetched.
UNSUPPORTED_FORMAT415The document extraction service rejected the file format.
TOO_MANY_PAGES413The document exceeds the extraction service's page limit.
ENCRYPTED_PDF422The PDF is password-protected and can't be processed.
OCR_UNAVAILABLE503The document extraction service is temporarily unavailable.
NOT_FOUND404No voice session with that id exists for your organization.
SESSION_ACTIVE409The voice session is still live — end it (hang up) before deleting it.
VOICE_UNAVAILABLE503The voice service isn't configured for this deployment.
JOB_IN_PROGRESS409The text-to-speech job is still running. Delete it after it completes or fails.
UPSTREAM_ERROR502Text to speech failed while producing the audio.
SERVICE_BUSY503Text to speech is at capacity. Retry after the number of seconds in the Retry-After header.
SERVICE_UNAVAILABLE503Text to speech is temporarily unavailable.
SYNTHESIS_UNAVAILABLE503Text to speech isn't configured for this deployment.

Rate limits

Enforced per API key, not per organization. Design against 60 requests per minute per key, refilling at about one request per second, so a key that hasn't been used recently can burst up to 60 requests at once. A request over the limit gets 429 RATE_LIMITED with a Retry-After header giving the number of seconds to wait.

Treat 429 and Retry-After as authoritative rather than tracking an exact budget yourself. The limiter currently holds its counters in memory per running instance, so the figure above is not a hard guarantee: counters reset when the service is deployed or restarted, and a horizontally scaled deployment enforces the allowance per instance rather than globally.

Webhooks

Set callback_url when you submit a job and rafiq-api POSTs the result to it once the job reaches a terminal state, so you don't have to poll GET .../{id}. The URL must be https on a public host; a redirect counts as a failure and is not followed, and each attempt times out after 15 seconds. Delivery is at-least-once: dedupe on the webhook-id header, which is the same on every retry.

The payload shape depends on the job type and outcome:

// Transcription — completed
{ "id": "…", "status": "completed", "transcript": { ... } }

// Transcription — failed
{ "id": "…", "status": "failed", "error": { "code": "...", "message": "..." } }

// Document — completed
{ "id": "…", "status": "completed", "pages": 12, "formats": ["md"] }

// Document — failed
{ "id": "…", "status": "failed", "error": { "code": "...", "message": "..." } }

// Text to speech — completed (GET /api/v1/synthesis/jobs/{id} for the audio_url)
{ "id": "…", "status": "completed", "duration_seconds": 42 }

// Text to speech — failed
{ "id": "…", "status": "failed", "error": { "code": "...", "message": "..." } }

A completed document job's payload carries only the page count and formats, never the extracted text — fetch that separately with GET /api/v1/documents/{id}?format=md|txt|json.

Every delivery is signed and carries three headers: webhook-id (the delivery id, the same on every retry), webhook-timestamp (integer unix seconds, fresh on every attempt) and webhook-signature (one or more space-separated v1,<base64> entries). The signature is base64 of HMAC-SHA256 over webhook-id.webhook-timestamp.body, keyed with the base64-decoded part of your signing secret after whsec_. Use the standardwebhooks library rather than computing it yourself.

webhook-id: <delivery id> webhook-timestamp: <unix seconds> webhook-signature: v1,<base64>

Verify against the exact bytes of the body as received. Parsing the JSON and re-serializing it before verifying produces a different string and will fail intermittently.

After you rotate the secret in Settings → Webhooks, the old secret keeps signing alongside the new one for 24 hours: webhook-signature then carries one entry per secret, so a receiver holding either secret verifies. After 24 hours only the new secret does.

A failed attempt (a non-2xx response, a timeout or a connection error) is retried up to 10 attempts in all, waiting about 5 seconds, 5 minutes, 30 minutes, 2, 5, 10, 14, 20 and 24 hours between them, each with up to 20% jitter, spanning roughly 3 days. A Retry-After header on a 429, 502, 503 or 504 that holds whole seconds lengthens the wait, up to 24 hours. After the tenth attempt rafiq-api stops trying.

Manage your signing secret in Settings → Webhooks

Verify a delivery (Node.js)

import { Webhook } from "standardwebhooks";

// rawBody must be the exact, unparsed request body — the same bytes rafiq-api
// signed. Verifying JSON.parse(rawBody) re-serialized will fail intermittently:
// key order and whitespace are not guaranteed to round-trip identically.
function verifyDelivery(rawBody, headers, secret) {
  const wh = new Webhook(secret); // the whsec_ value, exactly as issued
  return wh.verify(rawBody, {
    "webhook-id": headers["webhook-id"],
    "webhook-timestamp": headers["webhook-timestamp"],
    "webhook-signature": headers["webhook-signature"],
  }); // throws on a bad signature or a timestamp more than 5 minutes off
}

// Delivery is at-least-once: skip a webhook-id you have already processed.

Connecting to a voice session

POST /voice/sessions returns url and token together, but only once: that token is a short-lived LiveKit access token that expires in expires_in seconds, and is never handed out again by GET /voice/sessions/{id}. Connect with it immediately, using a LiveKit client SDK such as livekit-client.

Connect after creating a session (JavaScript)

import { Room } from "livekit-client";

const res = await fetch("https://api.rafiqspace.ai/api/v1/voice/sessions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.RAFIQ_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ instructions: "You are a helpful assistant." }),
});
const session = await res.json();

// session.token is short-lived and returned only by this create call —
// GET /voice/sessions/{id} never returns a fresh one.
const room = new Room();
await room.connect(session.url, session.token);
await room.localParticipant.setMicrophoneEnabled(true);

There is no way to fetch a fresh token for an existing session — if the token expires or the connection drops, the session itself is done. Start a new session instead of trying to reconnect to the old room_name.