Quickstart
Before you start
Section titled “Before you start”You need an API key with the documents:write and documents:read scopes. There is no public signup yet: first keys are provisioned by an operator. Set the key in your environment:
export SONIC_API_KEY="your-api-key"The examples default to https://api.sonicdocs.ai/v1, the intended production base URL. Set SONIC_API_BASE to point them somewhere else. The curl example needs curl 7.76 or later, jq and openssl. The JavaScript example needs Node.js 22 or later. The Python example needs Python 3.10 or later and requests.
Upload, wait and download
Section titled “Upload, wait and download”-
Upload the file. Send the raw bytes to
POST /documentswith the file’s media type and a newIdempotency-Key. Addexport=txtto ask for plain text, which is also the default. The service answers202 Acceptedwith a receipt only after the file is stored durably. -
Wait for a terminal state. Poll the receipt’s
links.statusURL untilstateissucceededorfailed. For live progress without polling, see live events and webhooks. -
Download the outputs. Read the result manifest at
links.resultand download each listed file from itsurl.
#!/usr/bin/env bash# Sonic Docs contract example: upload a document, wait for it, download the result.# Written against the planned v1 contract (api/specs/openapi.yaml). It has not yet# been run against a live Sonic Docs API. Requires bash, curl 7.76+, jq and openssl.set -euo pipefail
API_BASE="${SONIC_API_BASE:-https://api.sonicdocs.ai/v1}": "${SONIC_API_KEY:?Set SONIC_API_KEY to a key with documents:read and documents:write}"FILE="${1:?Usage: quickstart.sh path/to/document.pdf}"OUT="${SONIC_OUTPUT_DIR:-sonic-output}"AUTH="Authorization: Bearer $SONIC_API_KEY"
case "$(tr "[:upper:]" "[:lower:]" <<<"$FILE")" in *.pdf) TYPE=application/pdf ;; *.png) TYPE=image/png ;; *.jpg | *.jpeg) TYPE=image/jpeg ;; *) echo "Only PDF, PNG and JPEG files are accepted" >&2; exit 2 ;;esac
# 1. Upload. Reuse the same key if you retry, so the upload is admitted only once.KEY="upload-$(openssl rand -hex 16)"RECEIPT=$(curl -sS --fail-with-body -X POST "$API_BASE/documents?export=txt" \ -H "$AUTH" -H "Idempotency-Key: $KEY" -H "Content-Type: $TYPE" \ --data-binary "@$FILE")STATUS_URL=$(jq -r .links.status <<<"$RECEIPT")RESULT_URL=$(jq -r .links.result <<<"$RECEIPT")echo "Accepted $(jq -r .document_id <<<"$RECEIPT")"
# 2. Poll the status URL until the document succeeds or fails.while :; do SNAPSHOT=$(curl -sS --fail-with-body -H "$AUTH" "$STATUS_URL") case "$(jq -r .state <<<"$SNAPSHOT")" in succeeded) break ;; failed) jq .failure <<<"$SNAPSHOT" >&2; exit 1 ;; *) sleep 2 ;; esacdone
# 3. Read the result manifest and download every published file.mkdir -p "$OUT"curl -sS --fail-with-body -H "$AUTH" "$RESULT_URL" | jq -r '.files | to_entries[] | "\(.key) \(.value.url)"' | while read -r NAME URL; do curl -sS --fail-with-body -H "$AUTH" -o "$OUT/$NAME" "$URL" echo "Saved $OUT/$NAME" done// Sonic Docs contract example: upload a document, wait for it, download the result.// Written against the planned v1 contract; not yet run against a live API.// Usage: SONIC_API_KEY=... node quickstart.mjs path/to/document.pdfimport { randomUUID } from 'node:crypto';import { mkdir, readFile, writeFile } from 'node:fs/promises';import { extname, join } from 'node:path';import { API_BASE, api } from './client.mjs';
const MEDIA_TYPES = { '.pdf': 'application/pdf', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg' };const file = process.argv[2];const mediaType = MEDIA_TYPES[extname(file ?? '').toLowerCase()];if (!mediaType) throw new Error('Pass a .pdf, .png, .jpg or .jpeg file');const outDir = process.env.SONIC_OUTPUT_DIR ?? 'sonic-output';
// 1. Upload. Keep the idempotency key with the file so a retry returns the same receipt.const receipt = await ( await api(`${API_BASE}/documents?export=txt`, { method: 'POST', headers: { 'Content-Type': mediaType, 'Idempotency-Key': `upload-${randomUUID()}` }, body: await readFile(file), })).json();console.log(`Accepted ${receipt.document_id}`);
// 2. Poll the status URL until the document succeeds or fails.let snapshot;do { if (snapshot) await new Promise((resolve) => setTimeout(resolve, 2000)); snapshot = await (await api(receipt.links.status)).json();} while (!['succeeded', 'failed'].includes(snapshot.state));if (snapshot.state === 'failed') throw new Error(`${snapshot.failure.code}: ${snapshot.failure.message}`);
// 3. Read the result manifest and download every published file.const manifest = await (await api(receipt.links.result)).json();await mkdir(outDir, { recursive: true });for (const [name, { url }] of Object.entries(manifest.files)) { await writeFile(join(outDir, name), Buffer.from(await (await api(url)).arrayBuffer())); console.log(`Saved ${join(outDir, name)}`);}"""Sonic Docs contract example: upload a document, wait for it, download the result.
Written against the planned v1 contract; not yet run against a live API.Usage: SONIC_API_KEY=... python quickstart.py path/to/document.pdf"""import osimport sysimport timeimport uuidfrom pathlib import Path
from client import API_BASE, api
MEDIA_TYPES = {".pdf": "application/pdf", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg"}source = Path(sys.argv[1])media_type = MEDIA_TYPES[source.suffix.lower()]out_dir = Path(os.environ.get("SONIC_OUTPUT_DIR", "sonic-output"))
# 1. Upload. Keep the idempotency key with the file so a retry returns the same receipt.receipt = api( "POST", f"{API_BASE}/documents", params={"export": "txt"}, headers={"Content-Type": media_type, "Idempotency-Key": f"upload-{uuid.uuid4()}"}, data=source.read_bytes(),).json()print(f"Accepted {receipt['document_id']}")
# 2. Poll the status URL until the document succeeds or fails.while True: snapshot = api("GET", receipt["links"]["status"]).json() if snapshot["state"] in ("succeeded", "failed"): break time.sleep(2)if snapshot["state"] == "failed": sys.exit(f"{snapshot['failure']['code']}: {snapshot['failure']['message']}")
# 3. Read the result manifest and download every published file.manifest = api("GET", receipt["links"]["result"]).json()out_dir.mkdir(parents=True, exist_ok=True)for name, download in manifest["files"].items(): (out_dir / name).write_bytes(api("GET", download["url"]).content) print(f"Saved {out_dir / name}")What you get back
Section titled “What you get back”The receipt identifies the document and gives you the URLs to follow. Treat the document ID as opaque and use the links rather than building URLs yourself.
{ "document_id": "a~d17", "trace_id": "86bc31a843374ae6b6a3def26d08a011", "state": "accepted", "chunk_pages": 400, "output_plan": { "formats": [ "txt" ], "transformations": [] }, "links": { "status": "https://docs.example/documents/a~d17", "history": "https://docs.example/documents/a~d17/events", "result": "https://docs.example/documents/a~d17/result", "event_tickets": "https://docs.example/documents/a~d17/event-tickets", "events": "wss://docs.example/documents/a~d17/events" }, "expires_at": "2026-12-07T20:00:00Z"}When the document has succeeded, the result manifest lists every published file:
{ "document_id": "a~d17", "page_count": 2, "transformations": [], "files": { "document.txt": { "media_type": "text/plain", "url": "https://docs.example/documents/a~d17/artifacts/document.txt" } }}document.txt is UTF-8 text in reading order, with a form feed (U+000C) between pages.
Next steps
Section titled “Next steps”- Upload documents explains idempotency, retries and file requirements.
- Output formats covers HTML, Markdown and structured JSON.
- Errors lists every status and error code.