# DOCumenter Partner API v1 — Developer Guide

> **Provenance:** Generated from DOCumenter's public [developer documentation](https://api.documenter.ch/developers) as a portable narrative guide for implementation.
>
> **Scope:** This guide applies only to DOCumenter's EHR integration API. API results remain pollable for up to one hour for delivery and webhook recovery. The standalone web/mobile platform is separate and does not keep clinical processing results after delivery — they are queued for deletion when delivered to the user's browser and removed by automatic background cleanup (no fixed time guarantee).
>
> **Schema authority:** [`/v1/openapi.json`](https://api.documenter.ch/v1/openapi.json) is the authoritative EHR integration contract for request and response schemas. Use [Swagger UI](https://api.documenter.ch/v1/docs) to browse it interactively.
>
> **Security:** Never provide patient data, clinical documents, API keys, webhook signing secrets, physician JWTs or identifiers, real pairing codes, or other credentials to an external AI assistant. The fixed `DOC-SBX*` sandbox pairing codes are synthetic test fixtures.

## 1. Get started

### 1.1 Your first request

Submit a job, then fetch its result. Start here for a working request; use Swagger UI when you want to inspect every field interactively.

1. **Get your API key** — Sandbox keys are created by your organisation’s members in Settings → Developers, once DOCumenter has registered your organisation — write to [dev@documenter.ch](mailto:dev@documenter.ch) to get registered (response within 1 business hour). The key and the three parity pairing codes are shown together, so you can call the API immediately. A sandbox key needs no contract: it runs the production pipeline against a mock model and never touches patient content. Production keys are different: they are unlocked once the partnership contract is signed, after which an organisation mints its own in the developer console.
2. **POST your content** — Send text, audio, PDFs, DOCX — any combination, even text alone — to `/v1/process/upload`. A quick-evaluation sandbox key needs only the Authorization header; partner-parity sandbox uses the pairing-code header described below.
3. **GET /v1/process/{id}** — Poll until completed. Or set a webhook_url and we push results to you.

#### Choose the tool that fits your workflow

- [**Swagger UI — browse and try**](https://api.documenter.ch/v1/docs) — Best for humans exploring endpoints, schemas, defaults, and live requests.
- [**OpenAPI — generate and validate**](https://api.documenter.ch/v1/openapi.json) — Best for SDK generation, Postman/Insomnia import, and CI contract checks.
- [**Postman — runnable collection**](https://api.documenter.ch/developers/samples/Documenter.postman_collection.json) — Best for saved examples you can execute and share with your integration team.

Skipping curl? Drop your sandbox key into [Try It Live](https://api.documenter.ch/developers#test) in the browser, or import the [Postman collection](https://api.documenter.ch/developers/samples/Documenter.postman_collection.json) — both run the full integration in under a minute.

#### Document mode: Notes → Report

Send clinical notes, get a structured report back. No `prompt_id` required — the default template handles standard consultation notes. (Add audio + `tardoc:true` for the full transcription + report + Swiss billing-code chain — see [Try with Real Data](https://api.documenter.ch/developers#test-real-data).) **· [Run this in the playground →](https://api.documenter.ch/developers#test-live)**

#### curl

```bash
# Requires curl + jq. Runs end-to-end without copying the job ID.
JOB_ID=$(curl -fsS -X POST https://api.documenter.ch/v1/process/upload \
	-H "Authorization: Bearer YOUR_SANDBOX_KEY" \
	-F "mode=document" \
	-F "text=Patient de 45 ans. Cephalees frontales bilaterales depuis 2 semaines. TA 130/85. Examen neurologique normal. Paracetamol 1g x3/jour." \
	-F "locale=fr" | jq -er '.job_id')

curl -fsS "https://api.documenter.ch/v1/process/$JOB_ID" \
	-H "Authorization: Bearer YOUR_SANDBOX_KEY" | jq
```

#### Python

```python
import time
import httpx

headers = {"Authorization": "Bearer YOUR_SANDBOX_KEY"}
deadline = time.monotonic() + 300

with httpx.Client(timeout=30) as client:
    resp = client.post("https://api.documenter.ch/v1/process/upload", headers=headers, data={
        "mode": "document",
        "text": "Patient de 45 ans. Cephalees frontales...",
        "locale": "fr",
    })
    resp.raise_for_status()
    job_id = resp.json()["job_id"]

    while time.monotonic() < deadline:
        resp = client.get(f"https://api.documenter.ch/v1/process/{job_id}", headers=headers)
        resp.raise_for_status()
        result = resp.json()
        if result["status"] in ("completed", "error", "cancelled"):
            break
        time.sleep(5)
    else:
        raise TimeoutError(f"Job {job_id} did not finish within 5 minutes")

if result["status"] == "error":
    raise RuntimeError(result["error"])
if result["status"] == "cancelled":
    raise RuntimeError("Job was cancelled")

report_html = result["results"]["generation"]["content"]
```

Using C#, Java, PHP, or another stack? Import [the OpenAPI spec](https://api.documenter.ch/v1/openapi.json) to generate a typed client instead of translating this example by hand.

#### Response

```text
{
  "status": "completed",
  "results": {
    "generation": {
      "content": "<article class=\"documenter-report\">\n  <section data-key=\"anamnese\">\n    <h2>Anamnèse</h2>\n<p>Patient de 45 ans...</p>\n  </section>\n</article>",
      "format": "html",
      "tokens_out": 420
    }
  }
}

# Want TARDOC billing codes? Add "tardoc": true with audio — see the audio example below.
```

Want to send **real audio + PDFs** together? See [Try with Real Data](https://api.documenter.ch/developers#test-real-data). Don't want to install anything? [Try It Live](https://api.documenter.ch/developers#test-live) in your browser (paste your sandbox key, no install needed).

### 1.2 Sandbox vs production

Everything below is exercisable **entirely in sandbox** — no production key or real physician code required. Build and self-test your whole integration against three fake pairing codes, then flip a handful of values to go live.

#### The test triad

Like Stripe's test cards, three fake pairing codes drive all three plan tiers in sandbox. Put a code in `X-User-Token`: `GET /v1/entitlements` returns that tier's capabilities, and submits behave exactly as the live tier gate would. Use the fixed codes below with a sandbox partner key minted in your organisation’s developer console.

**Each code is a different doctor.** The three synthetic physicians carry DIFFERENT saved preferences, so switching code changes the output the way switching doctor does in production — which is what lets you assert on per-doctor resolution rather than on one anonymous default. They are SHARED, READ-ONLY fixtures: every partner testing against sandbox resolves the same three doctors, so the values below are stable and are re-seeded if anything edits them. To test against your OWN saved preferences, use your own pairing code with your organisation’s sandbox key — your real subscription, tier and entitlements apply then, exactly as they will live.

| Pairing code | Tier | Renaming settings (`results.renaming.format`) | Personal instruction (a real `prompt_id` you can pass) |
| --- | --- | --- | --- |
| `DOC-SBXSCRB1` | Scribe | `surname, birthdate, docdate, doctype, type_detail` (the platform default) NOM (DDN) - DATE Type Détail | Sandbox — Note de suite (Scribe) `titre, motif_consultation, anamnese, traitements` |
| `DOC-SBXIAST2` | IA-ssistant | `doctype, surname, docdate` Type - NOM DATE | **private prompt** `titre, motif_consultation, appreciation, suivi` — deliberately shorter than the house default, so switching `prompt_id` visibly changes the output |
| `DOC-SBXPRO03` | IA-ssistant Pro | `surname, docdate, type_detail, source` NOM - DATE - Détail - Établissement | Sandbox — Rapport détaillé (Pro) `titre, motif_consultation, anamnese, examen_clinique, appreciation, suivi` |

| Pairing code (tier) | `/v1/entitlements` → `capabilities` | Submit behavior |
| --- | --- | --- |
| **Scribe** (tier 1) `DOC-SBXSCRB1` | `transcription:true`, `generation_from_transcript:true`, `generation_from_documents:false`, `tardoc:false`, `form_fill:false` | Transcript-grounded generation only. Uploading documents or free-text notes → `403 DOC_BILL_001` (nothing runs), and so does `mode: "form"`. `tardoc:true` is dropped with a `DOC_BILL_002` `billing_notices[]` entry (transcript + note still returned). |
| **IA-ssistant** (tier 2) `DOC-SBXIAST2` | `generation_from_documents:true`, `form_fill:true`, `tardoc:false` (others `true`) | Documents, notes and `mode: "form"` all run normally. `tardoc:true` is dropped with a `DOC_BILL_002` `billing_notices[]` entry. |
| **IA-ssistant Pro** (tier 3) `DOC-SBXPRO03` | All five `true` | Documents, forms and `tardoc` all run — the full transcription + report + Swiss billing-code chain. |

Sandbox jobs produce a synthetic result rather than running a model, so real latency and the pairing-code lifecycle are not exercised (see [Authentication](https://api.documenter.ch/developers#authenticate)). The poll ladder IS: a sandbox submit returns `202 {"status": "processing"}` and the job becomes `completed` on your first poll, so the state machine and the webhook timing you build against are the ones you will meet live. (One exception, by construction: [`mode: "form"`](https://api.documenter.ch/developers#modes) really parses and really renders your form in sandbox, so it stays `processing` for a few seconds and completes on a later poll — only the answers are synthetic.) Everything else — auth, tier gates, entitlements, per-key rate and concurrency limits, idempotency, webhook signatures — matches production. The sandbox runs the SAME pipeline as production with the model mocked: your organisation’s field map is applied to the result, the acting physician’s own preferences and naming convention resolve exactly as they would live, and the output formats are identical. Only generated report text and transcription content are synthetic.

#### Sandbox → production: what changes, what stays

Migrating is a small, well-defined swap — four things change; your integration logic does not.

| Changes | Stays the same |
| --- | --- |
| Key prefix: `doc_test_` → `doc_partner_`. Each fake pairing code → the physician's real code (created on their Profile page). **Webhook signing secret** — sandbox and prod keys carry separately-generated secrets; verify with the prod key's secret. **Refresh `prompt_id`s from prod `GET /v1/prompts`** — the sandbox curated UUIDs are synthetic and return `404 DOC_VAL_007` in prod. | Request schemas and endpoints (environment-specific values such as `prompt_id` change). Polling and webhook delivery. Idempotency logic. Error handling. Entitlement-gated UI. |

### 1.3 Go-live checklist

- **Idempotency:** send a unique `Idempotency-Key` per logical job so retries are safe (see [Request shape → Idempotency](https://api.documenter.ch/developers#request-shape)).
- **Retry / backoff:** on `429` and `503`, honor the `Retry-After` header before retrying — do not hammer, and do not rotate your key on a `503`.
- **Webhooks:** verify `X-Webhook-Signature` before processing, and dedup on `X-Webhook-Delivery-ID` (constant across retries of one payload) — process each delivery once.
- **Bounded polling:** terminate on `status` in `completed` / `error` / `cancelled`. A cancelled job never becomes completed, so a loop that waits only for `completed` spins forever.
- **HTTP status first:** check the response status code before parsing the body as a job — a `4xx` / `5xx` body is an error envelope, not a job.
- **Entitlement → UI capability map** (from [`GET /v1/entitlements`](https://api.documenter.ch/developers#endpoints); always treat per-request `billing_notices[]` as the runtime authority):
  - `transcription` → the transcript-only path
  - `generation_from_transcript` → audio-to-note
  - `generation_from_documents` → PDF / DOCX / notes generation
  - `form_fill` → the fill-a-form action (`mode: "form"`)
  - `tardoc` → the TARDOC toggle
- **Key rotation:** rotate keys from the developer console on [documenter.ch](https://documenter.ch); pairings are org-bound and survive rotation, so physicians do not re-pair.
- **Alerting:** alert on sustained `4xx` (integration bug) and `5xx` (retry, then escalate) rates; quote the `X-Request-Id` of any failing response in support tickets.

## 2. Authenticate

How many headers a request needs depends on the key:

| Environment | Required headers |
| --- | --- |
| **Quick-evaluation sandbox** (`doc_test_`) | API key only. Physician auth and plan gates are bypassed so you can make a first request quickly. |
| **Partner-parity sandbox** (`doc_test_`) | API key **+** `X-User-Token` containing one of the supplied fake pairing codes. This is the sandbox to use for production integration testing. |
| **Production** (`doc_partner_` / `doc_live_`) | API key **+** `X-User-Token` — the physician identifier (a pairing code or a signed JWT, per your integration model below). |

**Sandbox shortcut (quick eval):** A plain sandbox key (`doc_test_`) skips the **JWT / pairing-code / subscription / billing** checks and returns mock results — just the API key is enough, no `X-User-Token` needed. **Request validation still applies:** the body schema, prompt resolution, file/document extraction (a corrupt file still returns `400 DOC_VAL_001`), the `tardoc`-needs-audio rule, the webhook SSRF guard, and the `Idempotency-Key` length cap all run exactly as on a live key — so what you validate in sandbox matches production. Sandbox keys are created by your organisation’s members in Settings → Developers, once DOCumenter has registered your organisation — write to [dev@documenter.ch](mailto:dev@documenter.ch) to get registered (response within 1 business hour). The key and the three parity pairing codes are shown together, so you can call the API immediately. A sandbox key needs no contract: it runs the production pipeline against a mock model and never touches patient content.

**Sandbox parity (partner simulation):** To build and self-test your WHOLE partner integration before go-live, ask [dev@documenter.ch](mailto:dev@documenter.ch) for a **sandbox partner key** plus **three fake pairing codes** (one per plan tier). This key runs the REAL partner path — real auth, the real tier gate, real `/v1/entitlements` — against the tier the pairing code carries; only the generated report is mocked (returned instantly). You pick the **simulated plan by which pairing code you put in `X-User-Token`**. The per-tier behavior, and what the sandbox does and does not simulate, are laid out in [Sandbox vs production → The test triad](https://api.documenter.ch/developers#sandbox-production).

**Curated prompts.** `GET /v1/prompts` on a sandbox partner key returns exactly three stable prompts — *Rapport de consultation*, *Synthese de dossier*, *Courrier medical* — and those are the only `prompt_id`s a submit accepts (any other returns `404 DOC_VAL_007`; omitting it uses *Rapport de consultation*). The generated report **varies by prompt AND by what you sent**: it reflects a transcript section when you include audio, a documents section when you upload files, and a notes line when you send free text — across all four locales (`fr`/`de`/`it`/`en`), rendered exactly as a live key would render it.

EHR Vendor / Partner

Institution / Hospital

The **primary path for EHR vendors.** Individual physicians subscribe on documenter.ch and self-provision a pairing code — no JWT signing, no token expiry to manage. Every `/v1/process` request carries **two headers**. Every API key is issued a **signing secret** at creation time; it is only required if you verify webhook signatures — polling-only integrations can ignore it.

| Header | Value | Purpose |
| --- | --- | --- |
| `Authorization` | `Bearer doc_partner_<secret>` | Your EHR vendor API key — **the secret**. Admin-minted by DOCumenter and issued to you out-of-band. One key per vendor; never expose it client-side. |
| `X-User-Token` | `DOC-XXXXXXXX` | The physician's pairing code — **an identifier, not a secret** (like an IBAN). It says which physician's DOCumenter subscription this request bills against. |

### How it works

**One-time setup per physician:** the doctor logs in to [documenter.ch](https://documenter.ch), opens their **Profile** page, finds the **“Patient record integration”** card, **creates** a pairing code (e.g., `DOC-A7K2M3P9`) — generated on demand, never minted automatically — and pastes it into your EHR's settings panel. Done. They self-provision — you never handle their credentials.

The pairing code is **not a secret**; it's an identifier. The physician can't call the API with it alone (they don't have your partner key), and your key alone can't act for a physician (it has no pairing code). Security comes from the **combination** of both headers — the secret API key plus the physician identifier.

```text
# Partner integration: secret API key + physician pairing code. That's it.
curl -X POST https://api.documenter.ch/v1/process \
  -H "Authorization: Bearer doc_partner_YOUR_KEY" \
  -H "X-User-Token: DOC-A7K2M3P9" \
  -H "Content-Type: application/json" \
  -d '{"mode":"document","content":"..."}'
# Full body in Quickstart above.
```

**Pairing-code lifecycle.** The physician explicitly creates the code on their Profile page (it is not minted on first visit). An **unpaired** code expires **1 year** after creation, and a newly-created code never used within **7 days** is deactivated (use it or lose it). Once the code is **paired** it no longer expires, so a working integration is never cut off by a lapsing code — revoking or regenerating from the “Patient record integration” card is how a paired code is ended. The **first `/v1/process` submit (any mode — document, transcript, chat, or rename) binds the code to your EHR vendor** (trust-on-first-use): after that only your keys can use that code — another vendor’s keys are rejected, and a physician switching EHR vendors regenerates the code to re-pair. Regenerating from the “Patient record integration” card revokes the old code immediately. A code that is unknown, revoked, expired, never-activated, or bound to a different vendor returns `401 DOC_AUTH_005` — prompt the physician to paste a fresh code. The token is matched case- and whitespace-insensitively, with or without the `DOC-` prefix.

**Partner auth errors:** `DOC_AUTH_001` (invalid key) and `DOC_AUTH_002` (revoked key) are `401`; `DOC_AUTH_005` (pairing code missing, unknown, revoked, expired, never-activated, or bound to another vendor) is `401`; and if the paired physician has no active subscription, the API returns `403 DOC_SUB_001` with a link to subscribe.

For hospitals and institutions that **buy physician licenses**. Your IT signs a JWT for each physician.

| Header | Value | Purpose |
| --- | --- | --- |
| `Authorization` | `Bearer doc_live_xxx...` | Your institution |
| `X-User-Token` | `eyJhbGci...` | Physician JWT (signed with your signing secret) |

```text
# Institution integration: API key + signed physician JWT
curl -X POST https://api.documenter.ch/v1/process \
  -H "Authorization: Bearer doc_live_YOUR_KEY" \
  -H "X-User-Token: YOUR_PHYSICIAN_JWT" \
  -H "Content-Type: application/json" \
  -d '{"mode":"document","content":"..."}'
# Full body in Quickstart above.
```

**Why JWT?** The JWT lets your IT assign physician identities from your own directory (Active Directory, HIN, etc.). We count distinct physicians per billing month against your license cap.

### Sign a Physician JWT

Your backend signs a short-lived JWT using **HS256** with the signing secret provided with your API key. Required claims: `sub`, `name`, `org`, `exp`.

| Claim | Rules |
| --- | --- |
| `sub` | The physician's identity. Must be **stable across every request** for that physician — it drives physician identity, license counting, and prompt scoping, so a value that changes between requests fragments their history and can over-count seats. Non-empty (rejected as `401 DOC_AUTH_004` if blank/whitespace) and **≤ 255 characters**. Use a durable id from your directory (e.g. an email or a stable internal user id), not a per-session token. |
| `exp` | Expiry (Unix seconds). Keep tokens short-lived. Validation allows **±5 minutes** of clock skew, so your signer and our verifier don't need perfectly synced clocks. An expired token returns `401 DOC_AUTH_003`. |
| `name`, `org` | Display name and organization label, for attribution and reporting. |

#### Python

```python
import jwt, time

token = jwt.encode({
    "sub": "dr.muller@chuv.ch",
    "name": "Dr. Sarah Mueller",
    "org": "CHUV",
    "iat": int(time.time()),
    "exp": int(time.time()) + 3600,
}, "your_signing_secret", algorithm="HS256")
```

#### C#

```csharp
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_signing_secret"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
    claims: new[] {
        new Claim("sub", "dr.muller@chuv.ch"),
        new Claim("name", "Dr. Sarah Mueller"),
        new Claim("org", "CHUV"),
    },
    expires: DateTime.UtcNow.AddHours(1),
    signingCredentials: creds
);

string jwt = new JwtSecurityTokenHandler().WriteToken(token);
```

#### Java

```java
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

var key = Keys.hmacShaKeyFor("your_signing_secret".getBytes());
String token = Jwts.builder()
    .claim("sub", "dr.muller@chuv.ch")
    .claim("name", "Dr. Sarah Mueller")
    .claim("org", "CHUV")
    .issuedAt(new Date())
    .expiration(new Date(System.currentTimeMillis() + 3600000))
    .signWith(key)
    .compact();
```

#### PHP

```php
use Firebase\JWT\JWT;

$token = JWT::encode([
    'sub' => 'dr.muller@chuv.ch',
    'name' => 'Dr. Sarah Mueller',
    'org' => 'CHUV',
    'iat' => time(),
    'exp' => time() + 3600,
], $signingSecret, 'HS256');
```

If license cap is exceeded (e.g., physician #81 on an 80-seat plan), the API returns `403` with error code `DOC_LIC_001` on every `/v1` route except `GET /v1/health` and `GET /v1/entitlements`, which stay reachable for that physician. Slots free up monthly when physicians stop making requests.

**JWT errors (institution mode).** The three failure modes return distinct codes so your backend can react precisely: an **expired** JWT returns `401 DOC_AUTH_003` (sign a fresh token), an **invalid signature or malformed** JWT returns `401 DOC_AUTH_004` (check your signing secret and encoding), and a **missing** `X-User-Token` returns `401 DOC_AUTH_005`.

**What authentication does not cover.** API-key management (`POST` / `GET` / `DELETE` `/v1/keys` and `POST /v1/keys/{id}/rotate`) is driven from a logged-in browser session on [documenter.ch](https://documenter.ch) — not from an API key — so those routes are not part of the machine-to-machine surface documented here (calling them with a partner key returns `403 DOC_AUTH_006`).

### 2.1 Onboard a doctor (signup intents)

If your organisation is enabled for it (contact [dev@documenter.ch](mailto:dev@documenter.ch)), you can prepare a DOCumenter signup for a doctor and receive their pairing code automatically once they finish. The doctor still creates the account in their own browser: the account's keys are generated on their device, so no API can create it for them. These two routes take your API key only (live or sandbox, **no** `X-User-Token`) and have their own budget of **10 requests/minute per key**.

| Call | Returns |
| --- | --- |
| `POST /v1/partner/signup-intents` `{email, first_name, last_name, phone?, specialty?, address?, external_ref?, return_url?}` | `201 {intent_id, status: "open", signup_url, expires_at}`. Send the doctor to `signup_url` (valid 7 days, single link). Calling again for the same email while the intent is open returns `200` with the same `intent_id` and a new link; the previous link stops working. `specialty` is a TARDOC dignity code, `external_ref` is your own reference (max 128 chars, echoed back), `return_url` must be https. `403 DOC_SIGNUP_001` if your organisation is not enabled. |
| `GET /v1/partner/signup-intents/{intent_id}` | `{intent_id, status, external_ref, pairing_code, completed_at, expires_at, livemode}`. `status` is `open`, `completed`, `delivered` or `expired`. `pairing_code` is present only during the hour after completion, then always `null`. `livemode` is `false` for an intent created with a sandbox key. An intent created by another organisation, or with a key of the other mode (sandbox vs production), returns `404`. |

**Callback.** When the doctor completes the signup, we POST `{"intent_id", "external_ref", "pairing_code", "status": "completed", "livemode"}` to the callback URL your organisation sets in the developer console (`/settings/dev`; never a URL sent in the request), signed with the creating key's signing secret and the same headers as job webhooks (`X-Webhook-Signature`, `X-Webhook-Timestamp`, `X-Webhook-Delivery-ID` = `intent_id`). **A 2xx response is the acknowledgement: return 2xx only after you have stored the pairing code, and deduplicate on `intent_id`**. Delivery is at-least-once: the same callback can arrive more than once (for example when your 2xx is lost), so treat a repeat as success. Non-2xx responses and timeouts are retried with backoff for up to 1 hour after completion; after that we stop, and polling no longer returns the code. If the creating key has been revoked, no callback is sent. With no registered callback URL, poll the `GET` route within that hour instead. After the hour (or at expiry), the contact details stored for this intent (name, email, phone, address) are deleted; the account the doctor created keeps its own profile. `external_ref` and `return_url` are kept with the intent as an audit record, so do not put personal data in them.

**Sandbox.** With a `doc_test_` key, `POST` validates the body exactly as live but creates no account, no trial and no signup page, and stores none of the doctor's contact details (only a keyed hash of the email, so a repeat call within the hour returns the same intent; it is cleared afterwards). It answers `201 {intent_id, status: "completed", signup_url: null, expires_at, pairing_code}` right away, where `pairing_code` is the IA-ssistant Pro sandbox code listed in your developer console, and fires the normal signed callback. Polling returns the code for 1 hour, so you can test the whole integration. The same email within that hour returns the same intent (`200`). `409 DOC_SIGNUP_008` means no sandbox code is available in this environment.

**Good to know.** In production, the pairing code minted for your organisation is bound to it and never expires until the doctor revokes or regenerates it. Over the 10 requests/minute budget, these routes return `429 DOC_RATE_001` with `Retry-After`.

| Code | Meaning |
| --- | --- |
| `403 DOC_SIGNUP_001` | Your organisation is not enabled for signup intents. |
| `404 DOC_SIGNUP_002` | Unknown `intent_id`, one created by another organisation, or one created with a key of the other mode (sandbox vs production). |
| `409 DOC_SIGNUP_003` | Signup page: the link was already completed by another account. |
| `410 DOC_SIGNUP_004` | Signup page: the link expired (7 days). |
| `404 DOC_SIGNUP_005` | Signup page: unknown or replaced link. |
| `409 DOC_SIGNUP_006` | The doctor is completing this signup right now, so it cannot be re-created with a new link. Poll the intent; if the doctor's attempt fails, the intent is released and can be re-created. |
| `422 DOC_SIGNUP_007` | Signup page: the doctor used a disposable email address. |
| `409 DOC_SIGNUP_008` | Sandbox key: no IA-ssistant Pro sandbox pairing code is available in this environment. |
| `503 DOC_SVC_001` | `POST`: the intent for this email is locked by a concurrent request. Retry after the `Retry-After` delay (5 seconds). |
| `503 DOC_SRV_001` | `POST`: signup intents are temporarily unavailable on our side. Retry later. |

## 3. Quickstart

Three copy-pasteable requests: submit text, submit files, poll for the result. Nothing to configure — no `prompt_id`, no `length`, no mapping. Replace `doc_partner_YOUR_KEY` with your key and `DOC-A7K2M3P9` with the physician's pairing code (or a signed JWT in institution mode — see [Authenticate](https://api.documenter.ch/developers#authenticate)).

**Every response on this page is a real capture.**

**Omitting `prompt_id` is the shortest path to a usable note.**

It selects the platform default instruction — *Note de suite — Cabinet* at the `equilibre` length, the everyday follow-up note. It is a **structured** instruction, so `output_format: "json"` returns the six canonical sections below, in this order: `titre`, `motif_consultation`, `anamnese`, `examen_clinique`, `appreciation` (titled « Attitude et suivi »), `traitements` (titled « Traitement prescrit »). A section with nothing to say is dropped silently, so treat all six as **optional on arrival** and route on `key`, never on position. Anything else the instruction produces lands on `autre`, and document chrome such as a closing salutation lands on `unmapped` — see [Structured JSON output](https://api.documenter.ch/developers#responses-json).

### 3.1 Text only, zero configuration

Post clinical notes as JSON. The pipeline infers a single `generation` step because there is no audio to transcribe.

#### curl

```bash
curl -X POST https://api.documenter.ch/v1/process \
  -H "Authorization: Bearer doc_partner_YOUR_KEY" \
  -H "X-User-Token: DOC-A7K2M3P9" \
  -H "Content-Type: application/json" \
  -d '{
    "mode": "document",
    "content": "Consultation de suivi, patient de 58 ans connu pour une hypertension arterielle et un diabete de type 2. Revient pour le controle trimestriel. Bonne observance du traitement, aucun episode hypoglycemique. Se plaint depuis trois semaines de douleurs du genou droit a la marche prolongee, sans traumatisme. Pas de fievre, pas de gonflement rapporte. Marche environ trente minutes par jour. Tension arterielle 138/84 mmHg, pouls 72/min regulier, poids 88 kg stable. Auscultation cardiaque et pulmonaire sans particularite. Genou droit sans epanchement, douleur a la palpation de la face interne, mobilite conservee. Derniere HbA1c a 7.1 pourcent il y a trois mois, fonction renale conservee. Poursuite du traitement antihypertenseur et antidiabetique sans changement. Introduction de paracetamol en reserve pour la gonalgie, radiographie du genou droit demandee, controle dans six semaines.",
    "output_format": "json",
    "locale": "fr"
  }'
```

#### 202 Accepted

```text
{
  "job_id": "doc_job_bzZu1Nls1CqRFZPn_wXw_g",
  "status": "processing",
  "mode": "document",
  "steps": ["generation"],
  "poll_url": "/v1/process/doc_job_bzZu1Nls1CqRFZPn_wXw_g",
  "estimated_seconds": 30,
  "billing_notices": []
}
```

`steps` is what the pipeline inferred from your inputs, `poll_url` is where 3.3 goes next, and `billing_notices` is empty because every requested step was dispatched (it fills in when a step is dropped for lack of entitlement — see [Poll & webhooks](https://api.documenter.ch/developers#polling)).

### 3.2 Audio, a PDF and notes in one request

`POST /v1/process/upload` takes raw files — no base64. Repeat the `files` field per file (**at most one audio file per request**) and put any free-text notes in `text`. Everything is fused into one consultation: the audio is transcribed, the PDF's text is extracted, and the note is appended.

#### curl

```bash
curl -X POST https://api.documenter.ch/v1/process/upload \
  -H "Authorization: Bearer doc_partner_YOUR_KEY" \
  -H "X-User-Token: DOC-A7K2M3P9" \
  -F "mode=document" \
  -F "files=@consultation.mp3" \
  -F "files=@protocole_operatoire.pdf" \
  -F "text=Controle a six semaines de la cholecystectomie. Cicatrices calmes, pas de douleur parietale. La patiente signale des brulures epigastriques le soir. Poursuite du pantoprazole 40 mg 1x/jour le matin pendant un mois. Reprise du travail autorisee." \
  -F "output_format=json" \
  -F "locale=fr"
```

#### 202 Accepted

```text
{
  "job_id": "doc_job_8J0v_HyWxUR7l91c_lmXtg",
  "status": "processing",
  "mode": "document",
  "steps": ["transcription", "generation"],
  "poll_url": "/v1/process/doc_job_8J0v_HyWxUR7l91c_lmXtg",
  "estimated_seconds": 75,
  "billing_notices": []
}
```

Same envelope as 3.1 — only `steps` and `estimated_seconds` changed, because the audio added a `transcription` step ahead of `generation`. The response shape does not depend on which endpoint you submitted to.

### 3.3 Poll until the job is done

`GET /v1/process/{job_id}` with the **same auth headers** you submitted with. Stop when `status` is `completed`, `error`, or `cancelled` — a cancelled job never becomes completed, so a loop that waits only for `completed` spins forever. Poll no faster than **every 2 seconds per job**; a tighter loop returns `429 DOC_RATE_001` with a `Retry-After` header. Results are available for one hour, then the job returns `410`.

#### curl

```bash
curl https://api.documenter.ch/v1/process/doc_job_bzZu1Nls1CqRFZPn_wXw_g \
  -H "Authorization: Bearer doc_partner_YOUR_KEY" \
  -H "X-User-Token: DOC-A7K2M3P9"
```

#### While it runs

```text
{
  "job_id": "doc_job_bzZu1Nls1CqRFZPn_wXw_g",
  "status": "processing",
  "mode": "document",
  "steps": ["generation"],
  "current_step": "generation",
  "estimated_seconds_remaining": null,
  "results": null,
  "error": null,
  "billing_notices": [],
  "created_at": "2026-08-29T22:39:56.341223Z",
  "completed_at": null
}
```

#### When it is done (3.1's job)

`results.generation.content` is always a **string**. With `output_format: "json"` that string is JSON — parse it to get the sections object.

```text
{
  "job_id": "doc_job_bzZu1Nls1CqRFZPn_wXw_g",
  "status": "completed",
  "mode": "document",
  "steps": ["generation"],
  "current_step": null,
  "estimated_seconds_remaining": null,
  "results": {
    "generation": {
      "content": "{\n  \"schema_version\": 1,\n  \"output_mode\": \"structured\",\n  \"sections\": […",
      "format": "json",
      "tokens_in": 6553,
      "tokens_out": 864
    }
  },
  "error": null,
  "billing_notices": [],
  "created_at": "2026-08-29T22:39:56.341223Z",
  "completed_at": "2026-08-29T22:40:03.128407Z"
}
```

#### Parsed `generation.content`

```text
{
  "schema_version": 1,
  "output_mode": "structured",
  "sections": [
    {
      "key": "titre",
      "title": "Note de suite",
      "parent": null,
      "content": ""
    },
    {
      "key": "motif_consultation",
      "title": "Motif de consultation",
      "parent": null,
      "content": "Contrôle trimestriel, gonalgie droite"
    },
    {
      "key": "anamnese",
      "title": "Anamnèse",
      "parent": null,
      "content": "1. **Hypertension artérielle et diabète de type 2**\nBonne observance du traitement. Aucun épisode hypoglycémique rapporté.…"
    },
    {
      "key": "examen_clinique",
      "title": "Examen clinique",
      "parent": null,
      "content": "Constantes : TA 138/84 mmHg, pouls 72/min régulier, poids 88 kg stable\n__Cardio-vasculaire__ : auscultation sans particularité…"
    },
    {
      "key": "appreciation",
      "title": "Attitude et suivi",
      "parent": null,
      "content": "1. **Hypertension artérielle et diabète de type 2**\nLe contrôle trimestriel est satisfaisant avec une bonne observance et des paramètres stables.…"
    },
    {
      "key": "traitements",
      "title": "Traitement prescrit",
      "parent": null,
      "content": "Paracétamol en réserve"
    }
  ],
  "extracted_at": "2026-08-29T22:40:03.128247+00:00"
}
```

#### The transcription block (3.2's job)

A job that ran `transcription` returns it alongside `generation`, under its own key. `generation` is the same shape as above — that run returned the same six sections, written from the audio, the PDF and the note together.

```text
"results": {
    "transcription": {
      "text": "[Medecin] Bonjour, madame de Lafleur…",
      "speakers": [
        {"id": 1, "label": "Medecin"},
        {"id": 2, "label": "Patient"}
      ],
      "medications": [
        {"name": "Pantoprazol", "dosage": null, "frequency": null},
        {"name": "Irfen", "dosage": null, "frequency": null},
        {"name": "Freka-Clyss", "dosage": null, "frequency": null}
      ],
      "audio_events": [],
      "duration_seconds": null,
      "language": null
    },
    "generation": { /* as in 3.1 */ }
  }
```

`medications` lists Swissmedic-matched names, and a dictated drug with no reliable match under its spoken name; `dosage` and `frequency` are declared but not surfaced today, so read them as always `null`. `language` is reported only when language identification ran, and `audio_events` is often empty — treat both as possibly absent rather than as fields you can key on. `audio_events` and `medications` are always ARRAYS, empty or not.

#### What next

- **Map the keys to your own fields.** Fetch the full catalogue from [`GET /v1/section-keys`](https://api.documenter.ch/developers#section-keys), or have DOCumenter return your EHR's field names directly — configured in the developer console's Mapping tab ([Structured JSON output](https://api.documenter.ch/developers#responses-json)).
- **Stop polling.** Pass `webhook_url` at submit time and we POST the finished job to you, signed with `X-Webhook-Signature` ([Poll & webhooks](https://api.documenter.ch/developers#polling)).
- **Choose another instruction.** [`GET /v1/prompts`](https://api.documenter.ch/developers#prompts-list) lists the instructions available to the physician, the sections each produces (with your field map applied) and which one is the default; pass its `id` as `prompt_id`, and `length` (`concis` / `equilibre` / `exhaustif`) when it has a length family ([Instruction library & section keys](https://api.documenter.ch/developers#prompts)).
- **Handle the five errors that matter.** `401` (bad key), `403` (plan does not include the step), `429` and `503` (honor `Retry-After`), `410` (results expired) — every code with its client action is in the [error catalogue](https://api.documenter.ch/developers#errors).

## 4. Send a request

### 4.1 Endpoints

**Use Swagger UI to explore; use OpenAPI for tooling.**

This page teaches the integration flow and operational decisions. The OpenAPI document is the authoritative EHR integration contract for request and response schemas; Swagger UI renders that contract as a human-friendly, interactive explorer. The error catalog below adds the client action for each `DOC_*` code. If you find a mismatch, treat the OpenAPI schema as authoritative and report it with the page's [support details](https://api.documenter.ch/developers#status).

#### Swagger UI

Interactive explorer — browse and try every endpoint in your browser.

[Open /v1/docs](https://api.documenter.ch/v1/docs)

#### OpenAPI spec

Import into Postman/Insomnia, generate a typed SDK with [openapi-generator](https://openapi-generator.tech/), or validate requests in CI.

[Download /v1/openapi.json](https://api.documenter.ch/v1/openapi.json)

A map for orientation. For full request/response detail, follow the linked narrative section or the [Swagger UI](https://api.documenter.ch/v1/docs) above.

| Method | Path | Purpose |
| --- | --- | --- |
| GET | `/v1/section-keys` | The canonical section-key catalogue your field mapping targets. See [Section keys](https://api.documenter.ch/developers#section-keys). |
| POST | `/v1/process` | Submit a job with a JSON body (all modes; chat is JSON-only). See [Modes](https://api.documenter.ch/developers#modes). |
| POST | `/v1/process/upload` | Submit a job with raw file uploads (multipart) — document, transcript, dictation, rename, or form. Same response envelope. |
| GET | `/v1/process/{job_id}` | Poll for status and results. `410` after the 1-hour result TTL. |
| DELETE | `/v1/process/{job_id}` | Cancel an in-progress job. A cancelled job polls as `{status:"cancelled", error:null}`. |
| GET | `/v1/prompts` | List the prompt templates visible to your key. See [Prompt Library](https://api.documenter.ch/developers#prompts). |
| GET | `/v1/entitlements` | Read the physician's plan tier + capabilities before submitting. See [Poll & webhooks](https://api.documenter.ch/developers#polling). |
| POST | `/v1/partner/signup-intents` | Prepare a doctor signup and get its link (API key only, no `X-User-Token`; organisation must be enabled). See [Onboard a doctor](https://api.documenter.ch/developers#signup-intents). |
| GET | `/v1/partner/signup-intents/{intent_id}` | Signup intent status, with the pairing code during the hour after completion. See [Onboard a doctor](https://api.documenter.ch/developers#signup-intents). |
| GET | `/v1/health` | Liveness check, no auth. Returns `{"status":"ok"}`. |

**Uploads (`/v1/process/upload`):** multipart `files` (repeatable; at most one audio file per request), plus `mode`, `text`, `transcript`, `transcript_token`, `prompt_id`, `length`, `tardoc`, `output_format`, `locale`, `webhook_url`, and `form` (the blank form to fill, required with `mode=form` and ignored otherwise). Accepted file formats and size caps are in [Limits & Edge Cases](https://api.documenter.ch/developers#limits); full field types are in the [Swagger UI](https://api.documenter.ch/v1/docs).

### 4.2 Request shape

**One endpoint for files and text.**

`POST /v1/process/upload` (multipart) accepts any combination of audio, PDFs, DOCX, images, and free text — even text-only with no files. **At most one audio file per request**; combine that one audio with any number of documents, images, and text (more than one audio returns `400 DOC_VAL_001`). Use it for document, transcript, dictation, rename and form modes (form mode adds one more part, `form`, for the blank form itself).

Chat mode uses `POST /v1/process` (JSON) instead — the `messages` array doesn't map cleanly to multipart form-data.

#### Request fields (JSON body, `POST /v1/process`)

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `mode` | `"document"` \| `"transcript"` \| `"dictation"` \| `"form"` \| `"chat"` \| `"rename"` | Yes | Processing mode: `"document"`, `"transcript"`, `"dictation"` (see [Dictation mode](https://api.documenter.ch/developers#dictation-mode)), `"form"`, `"chat"`, or `"rename"`. Required for JSON `POST /v1/process` — the request body is a discriminated union selected by this field, so omitting it returns `422`. Only the multipart `POST /v1/process/upload` defaults to `"document"`. `"form"` takes its own `form` field / file part — see [Form mode](https://api.documenter.ch/developers#modes). |
| `content` | string \| null | Conditional | Clinical text, or base64-encoded audio when `content_type: "audio"`. For raw file uploads use `/v1/process/upload`. At least one of `content` / `documents` / (uploaded) audio is required for the inferred steps. |
| `content_type` | `"text"` \| `"audio"` \| null | No | How to treat `content`. `"text"` (default) → report generation; `"audio"` → the base64 content is transcribed. |
| `documents` | array<DocumentAttachment> \| null | No | Base64-encoded attachments (text extracted automatically). See the DocumentAttachment table below. |
| `prompt_id` | string (UUID) \| null | No | Prompt template for generation. Omit to use the platform default (*Note de suite - Cabinet*, `equilibre`); for production stability pass an explicit id from `GET /v1/prompts`. |
| `length` | `"concis"` \| `"equilibre"` \| `"exhaustif"` \| null | No | Length variant. Valid only when the chosen prompt has a length family (non-empty `lengths` on `GET /v1/prompts`); otherwise returns `400 DOC_VAL_008`. The platform default prompt has one. Omit to use the family's `default_length`. |
| `output_format` | `"text"` \| `"markdown"` \| `"html"` \| `"json"` \| `"docx"` | No (default `"html"`) | Output format for the generated report. `"json"` returns the structured-section schema as a JSON-encoded string in `content`; `"docx"` returns base64-encoded Word bytes in `content` (see [Word (.docx) output](https://api.documenter.ch/developers#responses-docx)). |
| `tardoc` | boolean | No (default `false`) | When `true`, append TARDOC billing-code extraction. Accepted in `document` *and* `transcript` mode. Requires an audio source (transcription step), else `400 DOC_VAL_006`. Requires an **ia-ssistant-pro** subscription: without it the step is silently **dropped** (the rest of the pipeline still runs) and a `billing_notices[]` entry (`DOC_BILL_002`) is added — not a hard error. |
| `locale` | `"fr"` \| `"de"` \| `"it"` \| `"en"` | No (default `"fr"`) | Report language and TARDOC code descriptions. |
| `webhook_url` | string (https URL) \| null | No | HTTPS callback for result delivery. Must resolve to a public IP (SSRF-guarded). A non-`https://` URL is rejected as `422 DOC_VAL_001`. |

#### DocumentAttachment (items of `documents`)

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `type` | `"pdf"` \| `"text"` \| `"image"` | Yes | Attachment kind. `pdf` → text layer + OCR fallback; `image` → OCR; `text` → decoded UTF-8. |
| `name` | string | Yes | Original filename (used as the document label). |
| `data` | string (base64) | Yes | Base64-encoded file content. |

**chat**, **rename** and **form** modes share `locale` and `webhook_url`; see their tabs below for mode-specific fields (**form** requires its own `form` field and rejects the note-shaping ones). Multipart form fields for `POST /v1/process/upload` are listed in the [Endpoints](https://api.documenter.ch/developers#endpoints) section.

Use a `prompt_id` from [`GET /v1/prompts`](https://api.documenter.ch/developers#endpoints). For prompts with a length family, pass `length` too. See [Prompt Library](https://api.documenter.ch/developers#prompts) for scoping (defaults + your org + the physician's personal library) and the length-variant guide.

#### Idempotency — sending the same request twice

Add an `Idempotency-Key` header (a UUID is ideal). The key is scoped to the **API key + physician**. Repeating the same logical request replays the original job and adds `Idempotent-Replayed: true` to the `202` response. JSON object-key order, whitespace, and omitted versus explicit defaults do not matter; multipart boundary/header serialization does not matter. JSON array order, file order, filenames, media types, file bytes, and field values do matter. A meaningful change returns **409 `DOC_VAL_016`**; use a new key for a new logical job. Works on both submission endpoints and has no TTL.

### 4.3 Modes

Every request has a `mode`. The quickstart used `"document"`, which **always generates a note**: audio-only transcribes then generates from that transcript, text/documents produce a report, and audio + documents transcribes then generates from both. For transcription only (no note), send `"mode": "transcript"`. Add `"tardoc": true` together with audio to extract Swiss billing codes — it works in **both** `document` and `transcript` mode (requires an **ia-ssistant-pro** subscription — see below). To fill an official form instead of writing a note, send `"mode": "form"` with the blank form. Here are all five.

Document most common

Transcript

Form

Chat

Rename

Document mode **always generates a note** and adapts to what you send: audio alone transcribes *then* generates from that transcript; text produces a report; audio + documents transcribes first then generates with both as context. No need to specify steps. Want the transcript only, with no note? Use [`"transcript"` mode](https://api.documenter.ch/developers#modes).

| You send | Steps run | Duration |
| --- | --- | --- |
| Text / PDFs only | Generation | ~30-120s |
| Audio only | Transcription → Generation (note from the transcript). Use `"mode": "transcript"` for transcription only. | ~45-150s |
| Audio + text/PDFs | Transcription → Generation (with context) | ~55-190s |

**Uploaded documents require ia-ssistant.** Generating from the request's own audio transcript is available on every plan (Scribe included). Grounding the note in uploaded documents / PDFs / free-text notes requires an **ia-ssistant** subscription: a Scribe physician that attaches non-transcript sources is **hard-rejected** with `403 DOC_BILL_001` and nothing runs (a partial note that silently omitted the documents would be clinically misleading). Call [`GET /v1/entitlements`](https://api.documenter.ch/developers#endpoints) to check a physician's plan up front.

**More documents from one transcript, on every plan.** Each transcript comes back with a `transcript_token`. Send the transcript as `content` together with `transcript_token` to generate another document from it: it still counts as a transcript, so Scribe physicians can use it too. On `/v1/process/upload`, send it in the `transcript` field with `transcript_token`; it stays the consultation next to a `text` note and `files`. Store the token next to the transcript; it does not expire. Line endings, surrounding whitespace and Unicode normalization do not matter; an edited transcript, or a token issued to another physician, is treated as a free-text note.

**TARDOC billing codes (ia-ssistant-pro):** Set `"tardoc": true` together with audio to also extract Swiss TARDOC billing codes (tax points, quantities). Adds ~10s. Default is `false`. Codes use the chapter-prefixed format `AA.00.0010` (consultation), `AA.00.0110` (neuro exam), etc. TARDOC requires an **ia-ssistant-pro** subscription. Unlike documents, an under-entitled request is **not** rejected: the tardoc step is **dropped**, the transcript + note are still returned, and a [`billing_notices[]`](https://api.documenter.ch/developers#response-schemas) entry (`DOC_BILL_002`) explains the drop. You are billed only for the steps that ran.

```text
// Excerpt of results.tardoc on a real consultation:
"tardoc": {
  "codes": [
    {"code": "AA.00.0010", "description": "Consultation de base", "tp": 9.57, "quantity": 1},
    {"code": "AA.00.0020", "description": "Consultation, +5 min", "tp": 9.57, "quantity": 3},
    {"code": "AA.00.0110", "description": "Examen neurologique", "tp": 15.45, "quantity": 1}
  ],
  "total_tp": 53.73,
  "currency": "CHF"
}
```

**Transcription only.** Submit audio, get back a speaker-labeled transcript with medications — a note is **never** generated. This is the no-note counterpart to the note-generating `document` mode. Available on **every** plan (Scribe included). Add `"tardoc": true` to also extract billing codes from the transcript (still no note).

| Field | Required | Description |
| --- | --- | --- |
| `mode` | Yes | `"transcript"` |
| `content` | Either | Base64-encoded audio. Or upload a raw audio file via `POST /v1/process/upload` with `mode=transcript`. |
| `content_type` | No | Always `"audio"` (the default). Transcript mode is audio-only. |
| `tardoc` | No | Default `false`. When `true`, TARDOC billing codes are extracted from the transcript — still with no note. Same **ia-ssistant-pro** gate as in document mode (dropped with a `DOC_BILL_002` notice when unentitled). |

Audio-only by construction: `documents`, `prompt_id`, `length` and `output_format` are meaningless here and rejected with `422 DOC_VAL_001` — on the multipart upload endpoint too, so both surfaces agree. Shares `locale` and `webhook_url` with the other modes. Duration: ~15-60s.

```text
{
  "mode": "transcript",
  "content": "<base64 audio>",
  "content_type": "audio"
}
```

#### Dictation mode

**One speaker dictating, plain text out.** Send `"mode": "dictation"` (or `mode=dictation` on `POST /v1/process/upload`) with the audio, exactly as in transcript mode. Use it when a physician dictates a letter or a report rather than recording a consultation. Available on every plan.

`results.transcription` keeps the transcript shape: `text` is the dictated text with no speaker tags, `speakers` and `audio_events` are always `[]`, `language` is `null`, and `medications` and `duration_seconds` are filled as in transcript mode. A dictation carries no `transcript_token`: it is not a consultation transcript. The poll, the webhook and an idempotent replay report `"mode": "dictation"`.

**Spoken punctuation (French).** The physician can dictate the punctuation: *virgule*, *point*, *deux points*, *point-virgule*, *point d'interrogation*, *à la ligne*, *nouveau paragraphe*, *tiret*, *ouvrez/fermez la parenthèse*. They arrive in `text` as symbols, line breaks (`\n`) and blank lines (`\n\n`); keep line breaks when you display or store the text. When the context is ambiguous the command word is left as dictated rather than risk removing a clinical word ("trois points de suture", "point d'appel", "ligne médiane" stay words), so the physician may occasionally see a stray *point* to correct. A decimal dictated with digits joins (*11 virgule 4* becomes `11,4`). French dictations only.

Audio-only with no add-on: `documents`, `prompt_id`, `length`, `output_format`, `tardoc`, `transcript`, `transcript_token`, free `text` and non-audio files are rejected with `422 DOC_VAL_001` on both endpoints.

```text
{
  "mode": "dictation",
  "content": "<base64 audio>",
  "content_type": "audio"
}
```

**Fill an official form from the consultation.** Send the blank form and the sources it should be answered from; you get the **same form back, filled**, plus every field's value as data. The output follows the input: a **PDF AcroForm** comes back as a filled PDF (still an editable AcroForm, so the physician can correct any value in a normal PDF viewer), a **Word form** with native controls comes back as a filled `.docx`. No note is generated. Requires an **ia-ssistant** subscription ([`GET /v1/entitlements`](https://api.documenter.ch/developers#endpoints) → `capabilities.form_fill`); below that, the submit is rejected with `403 DOC_BILL_001` and nothing runs.

The **doctor's own identity** (GLN, RCC, practice address, signature) is **always left blank**.

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `mode` | `"form"` | Yes | Selects form mode. Available on both `POST /v1/process` (JSON) and `POST /v1/process/upload` (multipart). |
| `form` | object `{filename, content_base64}` | Yes | The blank form. On the multipart endpoint it is its own `form` file part instead (exactly one; a second `form` part is `400 DOC_VAL_001`), kept separate from `files` so a source document can never be mistaken for the form. The type is admitted from the file's **own bytes**, never from `filename` or the part's content type: a PDF AcroForm (max **8 MB**) or a Word form with native controls, `.docx`/`.dotx` (max **2 MB**). Anything else — a text file, an image — is rejected at submit with `400 DOC_VAL_001`. Fillable fields are not checked at submit: a PDF with none (a scan, a flattened form) is accepted with `202` and the job ends with `DOC_FORM_006`. |
| `content` | string \| null | Conditional | A source: clinical text, or base64-encoded audio with `content_type: "audio"`. At least one source is required — `content`, `documents`, or an uploaded file. |
| `content_type` | `"text"` \| `"audio"` \| null | No | How to treat `content`. With `"audio"` the recording is transcribed first and the transcript becomes a source, so `results.transcription` is returned alongside `results.form`. |
| `documents` | array<DocumentAttachment> \| null | No | Base64-encoded source attachments (same shape as in document mode; text is extracted automatically). On the multipart endpoint these are the `files` parts, plus the `text` field. |
| `locale` | `"fr"` \| `"de"` \| `"it"` \| `"en"` | No (default `"fr"`) | Language of the answering. |
| `webhook_url` | string (https URL) \| null | No | HTTPS callback for the result — same delivery, signing, and SSRF guard as the other modes. |

There is no note to shape here, so `prompt_id`, `length`, `output_format` and `tardoc` are **rejected** with `422 DOC_VAL_001` — on the multipart endpoint too, so both surfaces agree.

#### Submitting

Multipart is the natural shape: the form and the sources are files. The JSON endpoint takes the same request with the form base64-encoded.

```text
# multipart — the form in its own part, the sources in files/text
curl -X POST https://api.documenter.ch/v1/process/upload \
  -H "Authorization: Bearer doc_live_YOUR_KEY" \
  -H "X-User-Token: DOC-XXXXXXXX" \
  -F "mode=form" \
  -F "form=@rapport_medical_laa.pdf" \
  -F "files=@Consultation.ogg" \
  -F "text=Accident du 20.09.2026, chute d'une echelle."
```

```text
// JSON — same request, form base64-encoded
{
  "mode": "form",
  "form": {
    "filename": "rapport_medical_laa.pdf",
    "content_base64": "JVBERi0xLjcK..."
  },
  "content": "Accident du 20.09.2026, chute d'une echelle. Fracture du poignet droit...",
  "locale": "fr"
}
```

#### Steps & states

`steps` is `["form"]`, or `["transcription", "form"]` when you send audio. The job walks the **same** state machine as every other mode — `202 {"status": "processing"}`, then `GET /v1/process/{job_id}` until `completed` / `error` / `cancelled`, or a `webhook_url`. `DELETE /v1/process/{job_id}` cancels it. Answering runs page by page, so the time scales with the form: a 59-field, 3-page form measured about **11 s** (plus the transcription time when you send audio). The `202`'s `estimated_seconds` is a conservative `120` — poll or use a webhook rather than budgeting on a fixed number.

#### `results.form`

```text
{
  "status": "completed",
  "mode": "form",
  "steps": ["form"],
  "results": {
    "form": {
      "document": {
        "content_base64": "JVBERi0xLjcKJc...",
        "format": "pdf",
        "media_type": "application/pdf",
        "sha256": "1bc089c1b4dc..."
      },
      "fields": [
        {
          "key": "p001:q001:f001",
          "question": "Numero de sinistre",
          "label": "Numéro de sinistre:",
          "section": "Rapport médical LAA",
          "page": 1,
          "type": "text",
          "options": null,
          "value": "24.128.456"
        },
        {
          "key": "p002:q004:f001",
          "question": "Incapacite de travail",
          "label": "Incapacité de travail",
          "section": "Incapacité",
          "page": 2,
          "type": "choice",
          "options": ["oui", "non"],
          "value": "oui"
        }
      ],
      "summary": {
        "field_count": 59,
        "answered_count": 26,
        "failed_page_count": 0,
        "unplaced_field_count": 0,
        "continuation_page_count": 1
      }
    }
  }
}
```

| document — the filled form |  |  |
| --- | --- | --- |
| `content_base64` | string | **Base64-encoded** file bytes — decode before writing them to a file. |
| `format` | `"pdf"` \| `"docx"` | Follows the form you submitted. Never a conversion: a PDF form returns a PDF, a Word form returns a Word document. |
| `media_type` | string | `application/pdf`, or the Word package media type. Use it verbatim when you store or serve the file. |
| `sha256` | string | SHA-256 hex digest of the *decoded* bytes — verify your decode against it. |
| fields[] — every field of the form, in form order |  |  |
| `key` | string | Stable field key, **deterministic for a given form file**: the same blank form always yields the same keys, so a mapping you build once keeps working. It is not stable across two different versions of a form. |
| `question` | string? | The question the model restated for this field, when it did. **May be null** — and is always null in sandbox. |
| `label` | string? | The form's own label for the field, as printed on it. May be null when the control carries none. |
| `section` | string? | The form section the field belongs to. May be null. |
| `page` | int | 1-based page of the submitted form. |
| `type` | string | Field type: `text`, `date`, `number`, `checkbox`, `choice`, `signature`, … Treat it as an open set and fall back to text rendering. |
| `options` | array<string>? | The accepted values of a choice field; `null` for every other type. A non-empty `value` of a choice field is always one of them. |
| `value` | string | The value written into the field — always a string, `""` when the field was left blank (not answered, or the physician's to fill: signatures, attachments, the treating doctor's identity). |
| summary — what the fill achieved |  |  |
| `field_count` | int | Fields the form declares — always `fields.length`. |
| `answered_count` | int | Fields that received a non-empty value. A low count on a long form usually means the sources did not cover it, not that the fill failed. |
| `failed_page_count` | int | Pages whose answering failed; their fields come back blank. **Not an error** — the job still completes and the rest of the form is filled. |
| `unplaced_field_count` | int | Fields whose value did not fit its control and was moved to an appended annex page. |
| `continuation_page_count` | int | Pages appended to the returned document to carry overflow text. Expect the returned file to have more pages than the blank form when this is non-zero. |

#### Limits

- **The form:** 8 MB for a PDF, 2 MB for a Word form. Over either → `413 DOC_VAL_004`.
- **The sources:** at most **16** of them, and **512 KiB** of extracted text in total — counted after extraction, and *including the transcript* when you send audio, so a very long recording can push a request over the limit mid-job and terminate it with `DOC_VAL_004`.
- **Per key:** unchanged — the usual 30 requests/minute and 10 concurrent jobs (see [Limits & data handling](https://api.documenter.ch/developers#limits)).
- **Result TTL:** unchanged — 1 hour, like every other job.

#### Errors

| Code | When |
| --- | --- |
| `DOC_FORM_006` | The uploaded form cannot be filled: no native fillable fields, a scan, a flattened form, a Word file whose controls are not native, refused active content, or bytes we cannot read. Also when the filled document would exceed **9 MB** — the ceiling on what a single result may carry. Arrives as `error.error` inside a `200` poll body with `"status": "error"`, with no `error.reason`. **Do not retry the same file** — re-export the form from its source with its fields intact, or send a different one. |
| `DOC_VAL_001` 400 / 422 | The `form` part is not a PDF or a Word form (admitted from its bytes), its `content_base64` is not valid base64, more than one `form` part was sent, or the request carries a note-only field (`prompt_id`, `length`, `output_format`, `tardoc`). |
| `DOC_VAL_002` 400 | No `form` part with `mode=form`. Also when no readable text could be extracted from any source — and, as a terminal job error, when the audio produced no transcript and nothing else was supplied. |
| `DOC_VAL_004` 413 | The form exceeds its size limit, or the sources exceed 16 files / 512 KiB of extracted text (as a terminal job error when the transcript is what pushed them over). |
| `DOC_BILL_001` 403 | The physician's plan does not include form filling (ia-ssistant+). Nothing runs. Read `capabilities.form_fill` from [`GET /v1/entitlements`](https://api.documenter.ch/developers#endpoints) to gray the option out up front. |
| `DOC_SVC_001` 200, terminal | The fill did not finish (it exceeded its processing deadline, or the answering failed). Resubmit under a **new** `Idempotency-Key`. |
| `DOC_SVC_001` 503 at submit | Form filling runs on the instance that accepts your request, and that instance is already holding as many form jobs as it will take. Nothing was queued and no job id was minted. Honor `Retry-After` and resubmit — you may reuse the same `Idempotency-Key`. |

A page whose answering failed is **not** an error: its fields come back blank and are counted in `summary.failed_page_count`, and the job completes normally.

#### In sandbox

A `doc_test_` key runs the **real** lane: your form is really parsed, and the document you get back is really rendered — the same bytes-level path a live key takes. Only the *answers* are synthetic: no model is called, every text field is filled with `"Exemple"`, a choice field takes its first option, and `question` is `null`. So `fields[]`, the keys, the types, the options and the returned file are all exactly what you will parse in production. Unlike the other modes, a form job is **not** complete on your first poll: it goes `202 processing` → `completed` within a few seconds, so poll (or use a webhook) as you would live. With audio, the transcription step returns the usual sandbox mock transcript.

**Medical AI assistant** for clinical questions. Multi-turn conversation. Currently async (poll for response). Streaming via SSE is on the roadmap.

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `mode` | `"chat"` | Yes | Selects chat mode. Chat is JSON-only — `POST /v1/process`, not the multipart upload endpoint. |
| `messages` | array<{role, content}> | Yes | Non-empty conversation history. Only roles `user` and `assistant` are accepted (each with a string `content`). We apply our own medical system instruction — passing `role: "system"` returns `422`. |
| `locale` | `"fr"` \| `"de"` \| `"it"` \| `"en"` | No (default `"fr"`) | Reply language. |
| `webhook_url` | string (https URL) \| null | No | HTTPS callback for the reply — same delivery, signing, and SSRF guard as the other modes. |

**Multi-turn: send the whole history each call.** The API is stateless — there are no session IDs to track. On every turn, your EHR sends the full conversation so far (every prior user/assistant pair plus the new user question) and we return the next reply. Append it to your local history, then send it back next time.

```text
{
  "mode": "chat",
  "messages": [
    {"role": "user",      "content": "Diagnostics differentiels pour cephalees frontales?"},
    {"role": "assistant", "content": "Céphalées de tension, migraine, sinusite, HTIC..."},
    {"role": "user",      "content": "Patiente 45 ans, depuis 2 semaines, aggravées par le stress. Lequel?"}
  ]
}
```

Duration: ~5-30s. Streaming via SSE is on the roadmap; meanwhile poll `GET /v1/process/{job_id}` or set a `webhook_url`.

**AI-powered document renaming.** Extracts patient name, date, document type, and suggests a structured filename.

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `mode` | `"rename"` | Yes | Selects rename mode. |
| `content` | string \| null | Either | Document text to analyze. |
| `documents` | array<DocumentAttachment> \| null | Either | Base64-encoded document attachments (alternative to `content`); same shape as the Document-mode DocumentAttachment table above. Or upload raw files via `/v1/process/upload`. |
| `locale` | `"fr"` \| `"de"` \| `"it"` \| `"en"` | No (default `"fr"`) | Language hint for the extraction. |
| `webhook_url` | string (https URL) \| null | No | HTTPS callback for the result. |

Provide **at least one** of `content` or `documents` (via `/v1/process/upload`, an uploaded file's extracted text becomes `content`). An empty / whitespace-only request returns `400 DOC_VAL_002`. Duration: ~10-30s

**Filename layout.** There are **no format parameters on the request**. The naming convention lives on your API key: set it in the developer console (Keys → naming convention) as either *imposed* (it beats the doctor's own preference) or *default* (the doctor's preference wins and the key is the fallback). Allowed fields are `surname`, `firstname`, `birthdate`, `docdate`, `doctype`, `type_detail`, `doctor`, `source`, `recipient`. Listing `type_detail` splits the document type in two: `doctype` then renders the bare catalogue label (“Imagerie”) and `type_detail` the precision on its own (“CT de la hanche”). Both are in the platform default layout `NOM (DDN) - DATE Type Détail`; leave `type_detail` out of your own order and `doctype` falls back to the merged form. Every response reports which convention was actually applied in `results.renaming.format`. The composed filename is capped at 120 characters before the extension; over the cap whole words are given back from the free-text fields (`type_detail`, then `doctype`, then `source`, then `recipient`), so a name is never cut mid-word and the identity fields are never shortened.

| Convention on the key | Mode | Doctor has a preference | Applied | `format.source` |
| --- | --- | --- | --- | --- |
| set | `override` | either | the key's | `"key"` |
| set | `default` | yes | the doctor's | `"user"` |
| set | `default` | no | the key's | `"key"` |
| none | — | yes | the doctor's | `"user"` |
| none | — | no | the platform default | `"default"` |

### 4.4 Prompts & section keys

`GET /v1/prompts` and the `prompt_id` field on `POST /v1/process` resolve to the union of three tiers, scoped to the API key and (optionally) the physician identified by `X-User-Token`:

| Tier | What it contains | How to populate |
| --- | --- | --- |
| **System defaults** | Templates curated by DOCumenter for common Swiss clinical use cases. | Always visible. Nothing to configure. |
| **Institution library** | Templates your organization shares with every integrated physician. | Sign in to [documenter.ch](https://documenter.ch) as the org account, create or import the prompts you want shared. |
| **Physician's personal library** | The doctor's own templates, writing preferences, and tweaks — whatever they configure on documenter.ch. | Each physician on the EHR is mapped to their DOCumenter account on demand (via pairing code, verified email, or similar). Once mapped, anything they edit on documenter.ch is reflected in the API responses for that physician's requests automatically. |

Quick-evaluation sandbox keys see system defaults. Partner-parity sandbox keys expose the three curated prompt fixtures described under [Sandbox vs production](https://api.documenter.ch/developers#sandbox-production); their UUIDs are sandbox-only.

A `prompt_id` outside these three tiers (e.g. another tenant's private prompt, or a UUID that doesn't exist) returns `404 DOC_VAL_007` on `POST /v1/process`. We return 404 rather than 403 to avoid leaking the existence of other tenants' prompts.

**Note:** The web app's "public" share-link prompts are not surfaced through the developer API. If you need a community prompt for an integration, fork it into your org's library — that surfaces it via the institution tier.

#### Section keys (the mapping contract)

`GET /v1/section-keys` returns the canonical keys that appear in `sections[].key` when you request `output_format: "json"` — the list your field mapping is built against. Each entry has a `key`, a human `label`, and `deprecated`.

**Keys are append-only.** A published key is never renamed or removed. Retirement is `deprecated: true`: the key stays in this list and is still assigned to reports, so an existing mapping keeps working — but you should not point new fields at it.

Poll `catalogue_version` to notice that the vocabulary or the heading-matching rules moved. It is a change signal only — a request cannot pin a version, and results do not carry one. Aliases (the heading phrases that resolve to each key) are intentionally not published; they are internal matching detail.

```text
curl -s https://api.documenter.ch/v1/section-keys \
  -H "Authorization: Bearer doc_live_YOUR_KEY" \
  -H "X-User-Token: YOUR_JWT"
```

```text
{
  "catalogue_version": 1,
  "keys": [
    {"key": "anamnese", "label": "Anamnèse", "deprecated": false},
    {"key": "titre", "label": "Titre du document", "deprecated": false},
    {"key": "unmapped", "label": "Salutations", "deprecated": false},
    {"key": "autre", "label": "Autre section", "deprecated": false}
  ]
}
```

**Prompt listing, defaults, and length variants**

#### Listing prompts

`GET /v1/prompts` returns the templates visible to your key. Each item has a stable `id` (UUID), a `title`, a `visibility`, an optional `description` (`string | null`), an `is_default` flag, an `is_favorite` flag (the physician starred it on documenter.ch; list those first), a `sections` preview, and — for templates that come in length variants — a `lengths` array plus a `default_length`. Singletons return `null` for the last two.

`sections` is what this instruction produces, in the order it declares it, with **your organisation's field map already applied**: `canonical_key` is DOCumenter's own key, and `key` is what you will actually receive in `results.generation.sections[].key`. Two entries may carry the same `key` — that is a many-to-one mapping, and their contents arrive appended under it in report order; they are listed separately so you can see which sections merge. The document title is always the first entry. `sections` is `null` when the instruction does not declare its structure up front (free-text instructions, instructions whose structure the model derives at generation time, and every sandbox instruction).

The map reflected here is your organisation's *current* one. A job that has already completed keeps the map that was in force at its completion, so editing the map never re-keys a finished job — see [Section keys](https://api.documenter.ch/developers#section-keys).

```text
curl -s https://api.documenter.ch/v1/prompts \
  -H "Authorization: Bearer doc_live_YOUR_KEY" \
  -H "X-User-Token: YOUR_JWT"
```

```text
[
  {
    "id": "a8badc28-...",                // singleton — no length family
    "title": "Laboratoire",
    "description": null,
    "visibility": "default",
    "lengths": null,
    "default_length": null,
    "is_default": false,
    "is_favorite": false,
    "sections": null                     // structure not declared up front
  },
  {
    "id": "1d8ba499-...",                // id = the equilibre variant of the family
    "title": "Note de suite - Cabinet",
    "description": "Note de suite pour le dossier médical au cabinet",
    "visibility": "default",
    "lengths": ["concis", "equilibre", "exhaustif"],
    "default_length": "equilibre",
    "is_default": true,                  // used when you omit prompt_id
    "is_favorite": true,                 // starred by this physician
    "sections": [
      {"canonical_key": "titre",              "title": "Titre du document",     "key": "titre",              "presence": "required"},
      {"canonical_key": "motif_consultation", "title": "Motif de consultation", "key": "motif_consultation", "presence": "required"},
      {"canonical_key": "anamnese",           "title": "Anamnèse",             "key": "ehr_history",        "presence": "required"},
      {"canonical_key": "examen_clinique",    "title": "Examen clinique",      "key": "ehr_history",        "presence": "required"},
      {"canonical_key": "appreciation",       "title": "Attitude et suivi",    "key": "appreciation",       "presence": "required"},
      {"canonical_key": "traitements",        "title": "Traitement prescrit",  "key": "traitements",        "presence": "required"}
    ]
  }
]
```

This organisation maps `anamnese` and `examen_clinique` onto the same `ehr_history` field, so both are listed and both arrive under `ehr_history`; the unmapped keys pass through as themselves.

#### Default prompt

`prompt_id` is optional. Omitting it gives you **Note de suite - Cabinet** at `equilibre` length — the everyday follow-up note, and the quickest way to get a result on a first integration before you wire up template selection. For production stability, use an explicit `prompt_id` from `GET /v1/prompts`. Add `output_format: "json"` for the structured, per-section response. The default is a length family, so `length` works without a `prompt_id` too.

```text
curl -s -X POST https://api.documenter.ch/v1/process \
  -H "Authorization: Bearer doc_live_YOUR_KEY" \
  -H "X-User-Token: YOUR_JWT" \
  -H "Content-Type: application/json" \
  -d '{
    "mode": "document",
    "content": "Patient présente fièvre 38.5 et toux sèche.",
    "output_format": "json"
  }'
```

For production, select an explicit `prompt_id` from `GET /v1/prompts` so your output stays stable as platform defaults evolve.

#### Length variants

Some prompts come in three lengths. Items with a non-null `lengths` array are part of a length family; pass the `length` parameter on `POST /v1/process` to pick the variant. Omit `length` to get the variant identified by `default_length` (always `equilibre` when available).

- `concis` — stripped to key facts. ~40-50% fewer tokens than `equilibre`. Use when the EHR slot is small or the doctor wants to skim.
- `equilibre` — balanced detail. **The recommended starting point and what most doctors pick.** If you skip `length`, this is what you get.
- `exhaustif` — maximum detail. ~30-40% more tokens than `equilibre`. Use for legal-quality reports (LAA, AI, expertises) where omitted context can hurt.

All three share the same prompt family — same model, only the requested verbosity differs. If you build a length toggle in your EHR UI, pre-select `equilibre`. Passing `length` on a prompt without a family returns `400 DOC_VAL_008`; the default prompt has one, so omitting `prompt_id` does not.

## 5. Get the results

### 5.1 Poll & webhooks

Two options. Use whichever fits your architecture.

Option A: Polling

Option B: Webhook

Call `GET /v1/process/{job_id}` every 5 seconds with the **same auth headers** you used to submit. The job is tied to your API key and the physician who submitted it — another key, or another physician under the same key, gets 404. Results expire after 1 hour.

```text
# Poll with the same auth headers (job is tied to your API key)
while status == "processing":
    sleep(5)
    result = GET /v1/process/{job_id}
              -H "Authorization: Bearer YOUR_API_KEY"
              -H "X-User-Token: YOUR_TOKEN"

# status: "completed" | "error" | "cancelled"
```

**Recommended strategy:** Poll every 5 seconds for the first 30 seconds, then every 10 seconds. Polls do not count against `rate_limit_rpm`, but polling one job much more often than every 2 seconds returns `429 DOC_RATE_001` — treat 2 seconds as a floor, not a quota. Once the per-minute window is already full, polls are refused too until it frees a slot ([Rate limits](https://api.documenter.ch/developers#limits)). For high-volume integrations, use webhooks instead. While processing, the response contains no partial data:

```text
{
  "job_id": "doc_job_...",
  "status": "processing",
  "mode": "document",
  "steps": ["generation"],
  "current_step": "generation",
  "results": null,
  "error": null
}
```

**Progress tracking.** While `status` is `processing`, the poll response includes the step currently executing:

| `current_step` | string? | Name of the step currently executing (e.g. `"transcription"`, `"generation"`). Present only while processing. |
| --- | --- | --- |

**202 Accepted (submit response).** Every `POST /v1/process` (and `/v1/process/upload`) returns `202 Accepted` immediately with:

```text
{
  "job_id": "doc_job_kVG4OV0K...",
  "status": "processing",
  "mode": "document",
  "steps": ["transcription", "generation"],
  "poll_url": "/v1/process/doc_job_kVG4OV0K...",
  "estimated_seconds": 75,
  "billing_notices": []
}
```

The submit `status` is `"processing"` for every new job, live or sandbox. (A sandbox job becomes `completed` on your first poll; an `Idempotency-Key` replay returns the original job's current status.) `estimated_seconds` is the sum of per-step estimates — roughly 45s transcription, 30s generation, 10s TARDOC — so it varies with the inferred steps; a sandbox submit returns `1`.

**Partial fulfillment — `billing_notices[]`.** When a request asks for a step the physician's plan does not include but the rest of the pipeline can still run, that step is **dropped** (never dispatched, never billed) and a notice is returned in `billing_notices[]` — present on the **202 submit**, every **poll**, and the **webhook** payload (identical in all three). It is **empty** when every requested step ran. Today the only case is TARDOC on a non-pro plan:

```text
{
  "job_id": "doc_job_...",
  "status": "processing",
  "steps": ["transcription", "generation"],   // tardoc dropped
  "billing_notices": [
    {
      "code": "DOC_BILL_002",
      "step": "tardoc",
      "message": "TARDOC billing extraction requires an ia-ssistant-pro subscription; the step was skipped.",
      "required_tier": "ia-ssistant-pro"
    }
  ]
}
```

`billing_notices[]` is the authoritative runtime signal. To check a physician's plan *before* submitting, read [`GET /v1/entitlements`](https://api.documenter.ch/developers#endpoints).

Set `webhook_url` in your request and we POST the full result to your server when done. Must be HTTPS. We make up to **3 delivery attempts**, roughly 30 s apart. After 3 failed attempts the result is **not lost** — it remains pollable via `GET /v1/process/{job_id}` for 1 hour. Any `2xx` acknowledges delivery; redirects are not followed and the request timeout is 30 seconds. Verify, persist/deduplicate, and acknowledge quickly; process heavier downstream work from your own queue.

**A webhook always carries a terminal outcome.** If a finished result is lost *within* the delivery window — an unplanned restart of the processing service, or the result otherwise gone from its store — the callback is delivered as `"status": "error"` with `"results": null` and `error.error` = `DOC_JOB_002`, signed and retried like any other delivery. Poll `GET /v1/process/{job_id}` for the job's own state, then resubmit with a new `Idempotency-Key`. A `completed` callback always carries results. **Delivery attempts stop one hour after the job reaches its terminal state**: a callback that has not succeeded by then is not retried and no further callback of any kind is sent for that job, so treat the 1-hour window as the outer bound on hearing from us at all.

**That error carries its own `X-Webhook-Delivery-ID`.** The delivery id is stable across the retries of one payload, but a job whose earlier attempt already sent you `completed` results (an acknowledgement can be lost after your server stored them) gets a DIFFERENT id for the `DOC_JOB_002` error, so deduplicating on the header never makes the two collapse into one and never makes the error overwrite a result you already hold.

```text
# Submit with webhook — no polling needed
curl -X POST https://api.documenter.ch/v1/process \
  -H "Authorization: Bearer doc_live_YOUR_KEY" \
  -H "X-User-Token: YOUR_JWT" \
  -H "Content-Type: application/json" \
  -d '{
    "mode": "document",
    "content": "Patient de 45 ans...",
    "webhook_url": "https://your-ehr.hospital.ch/webhooks/documenter"
  }'
```

#### Webhook Headers

Every webhook POST includes these headers:

| Header | Value | Purpose |
| --- | --- | --- |
| `Content-Type` | `application/json` | Body is the full result JSON |
| `X-Webhook-Signature` | `a1b2c3d4e5...` (hex HMAC-SHA256) | HMAC-SHA256 over `{timestamp}.{raw_body}`, signed with your API key's signing secret. The timestamp prefix prevents replay. |
| `X-Webhook-Timestamp` | `1714327200` | Unix epoch seconds at signature time. Reject if drift exceeds your tolerance (we recommend 5 minutes). |
| `X-Webhook-Signature-Version` | `v1` | Signature scheme. Reject unknown versions so a future scheme upgrade can't trick old verifiers. |
| `X-Job-Id` | `doc_job_xxx` | Job ID for correlation |
| `X-Webhook-Delivery-ID` | `550e8400-e29b-41d4-a716-446655440000` (UUID) | Unique delivery ID, **constant across all retries of one payload**. A job’s terminal `DOC_JOB_002` error callback carries its own delivery id (see the webhook notes above). Use it to idempotently dedup webhook notifications — if the same delivery ID arrives twice (a retry after a slow ack), process it once. |

#### Verify the Signature

**You must verify `X-Webhook-Signature` before processing the payload.** The signature is `HMAC-SHA256(signing_secret, "{timestamp}." + raw_body)` where `{timestamp}` is the value of `X-Webhook-Timestamp` — the signing secret provided with your API key. Reject any request where the signature doesn't match.

#### Python

```python
import hashlib, hmac, json, time

def verify_webhook(raw_body: bytes, signature: str, timestamp: str, signing_secret: str) -> bool:
    # Reject missing/malformed timestamps and signatures older than 5 minutes.
    try:
        age = abs(int(time.time()) - int(timestamp))
    except (TypeError, ValueError):
        return False
    if age > 300:
        return False
    signed = timestamp.encode() + b"." + raw_body
    expected = hmac.new(signing_secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)

# In your Flask/FastAPI webhook handler:
@app.post("/webhooks/documenter")
async def handle_webhook(request: Request):
    raw_body = await request.body()
    signature = request.headers.get("X-Webhook-Signature", "")
    timestamp = request.headers.get("X-Webhook-Timestamp", "")
    version = request.headers.get("X-Webhook-Signature-Version", "")
    delivery_id = request.headers.get("X-Webhook-Delivery-ID", "")

	if not delivery_id or version != "v1" or not verify_webhook(raw_body, signature, timestamp, SIGNING_SECRET):
        return Response(status_code=401)

    result = json.loads(raw_body)
	# In one DB transaction: INSERT delivery_id into a UNIQUE column and persist
	# the result. If INSERT ... ON CONFLICT DO NOTHING inserts 0 rows, this
	# delivery was already processed: return 200 without applying it twice.
	await webhook_inbox.store_once(delivery_id, result)
    return Response(status_code=200)
```

#### C#

```csharp
using System.Security.Cryptography;

bool VerifyWebhook(byte[] rawBody, string signature, string timestamp, string signingSecret)
{
    // Reject signatures older than 5 minutes (replay defense).
    var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
    if (Math.Abs(now - long.Parse(timestamp)) > 300) return false;

    var signed = Encoding.UTF8.GetBytes(timestamp + ".").Concat(rawBody).ToArray();
    using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(signingSecret));
    var expected = Convert.ToHexString(hmac.ComputeHash(signed)).ToLowerInvariant();
    return CryptographicOperations.FixedTimeEquals(
        Encoding.UTF8.GetBytes(expected),
        Encoding.UTF8.GetBytes(signature));
}

// In your ASP.NET controller:
[HttpPost("/webhooks/documenter")]
public async Task<IActionResult> HandleWebhook()
{
    using var reader = new StreamReader(Request.Body);
    var rawBody = await reader.ReadToEndAsync();
    var signature = Request.Headers["X-Webhook-Signature"].ToString();
    var timestamp = Request.Headers["X-Webhook-Timestamp"].ToString();
    var version = Request.Headers["X-Webhook-Signature-Version"].ToString();

    if (version != "v1" || !VerifyWebhook(Encoding.UTF8.GetBytes(rawBody), signature, timestamp, _signingSecret))
        return Unauthorized();

    var result = JsonSerializer.Deserialize<JsonElement>(rawBody);
    // Process result...
    return Ok();
}
```

#### Java

```java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.HexFormat;

boolean verifyWebhook(byte[] rawBody, String signature, String timestamp, String signingSecret) {
    try {
        // Reject signatures older than 5 minutes (replay defense).
        long now = System.currentTimeMillis() / 1000;
        if (Math.abs(now - Long.parseLong(timestamp)) > 300) return false;

        byte[] signed = ByteBuffer.allocate((timestamp + ".").getBytes().length + rawBody.length)
            .put((timestamp + ".").getBytes()).put(rawBody).array();
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(signingSecret.getBytes(), "HmacSHA256"));
        String expected = HexFormat.of().formatHex(mac.doFinal(signed));
        return MessageDigest.isEqual(expected.getBytes(), signature.getBytes());
    } catch (Exception e) { return false; }
}

// In your Spring controller:
@PostMapping("/webhooks/documenter")
public ResponseEntity<Void> handleWebhook(
        @RequestBody byte[] rawBody,
        @RequestHeader("X-Webhook-Signature") String signature,
        @RequestHeader("X-Webhook-Timestamp") String timestamp,
        @RequestHeader("X-Webhook-Signature-Version") String version) {
    if (!"v1".equals(version) || !verifyWebhook(rawBody, signature, timestamp, signingSecret))
        return ResponseEntity.status(401).build();
    // Process result...
    return ResponseEntity.ok().build();
}
```

#### PHP

```php
// In your webhook endpoint:
$rawBody   = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE']         ?? '';
$timestamp = $_SERVER['HTTP_X_WEBHOOK_TIMESTAMP']         ?? '';
$version   = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE_VERSION'] ?? '';

// Reject unknown scheme version + timestamps older than 5 minutes (replay defense).
if ($version !== 'v1' || abs(time() - (int)$timestamp) > 300) {
    http_response_code(401);
    exit;
}

$signed   = $timestamp . '.' . $rawBody;
$expected = hash_hmac('sha256', $signed, $signingSecret);

if (!hash_equals($expected, $signature)) {
    http_response_code(401);
    exit('Invalid signature');
}

$result = json_decode($rawBody, true);
// Process result...
http_response_code(200);
```

#### Node.js

```text
const crypto = require('crypto');

function verifyWebhook(rawBody, signature, timestamp, signingSecret) {
    // Reject signatures older than 5 minutes (replay defense).
    if (Math.abs(Math.floor(Date.now() / 1000) - parseInt(timestamp, 10)) > 300)
        return false;
    const signed = Buffer.concat([Buffer.from(timestamp + '.'), rawBody]);
    const expected = crypto.createHmac('sha256', signingSecret).update(signed).digest('hex');
    if (expected.length !== signature.length) return false;
    return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
}

// Express.js (use raw body parser):
app.post('/webhooks/documenter', express.raw({type: 'application/json'}), (req, res) => {
    const signature = req.headers['x-webhook-signature'] || '';
    const timestamp = req.headers['x-webhook-timestamp'] || '';
    const version = req.headers['x-webhook-signature-version'] || '';

    if (version !== 'v1' || !verifyWebhook(req.body, signature, timestamp, SIGNING_SECRET))
        return res.status(401).send('Invalid signature');

    const result = JSON.parse(req.body);
    // Process result...
    res.status(200).send();
});
```

**Security notes:** Always use constant-time comparison (shown above) to prevent timing attacks. The signing secret is provided with your API key (both institution and partner keys). For partner-mode integrations, the signing secret is only needed if you use webhooks. Store it securely and never expose it client-side. Rotating an API key from the developer console on [documenter.ch](https://documenter.ch) changes **only the API key** — the signing secret is **not** rotated and stays the same. Rotation is **immediate** (no overlap window — the old key stops working the instant the new one is issued) and **preserves the key class** (a sandbox key stays sandbox, a partner key stays partner). Swap the key in your config before the next call. If you suspect the *signing secret* itself is compromised, contact [dev@documenter.ch](mailto:dev@documenter.ch) — key rotation alone will not replace it.

### 5.2 Response schemas

Job responses use two closely-related envelopes: a compact `202` submission acknowledgement, then the status envelope returned by polling and webhooks. Immediate `4xx`/`5xx` failures use the separate error envelope shown under [Error Codes](https://api.documenter.ch/developers#errors).

#### The envelope, field by field

| Field | 202 submit | processing | completed | error | cancelled |
| --- | --- | --- | --- | --- | --- |
| `job_id` | yes | yes | yes | yes | yes |
| `status` | `"processing"` | `"processing"` | `"completed"` | `"error"` | `"cancelled"` |
| `mode` | yes | yes | yes | yes | yes |
| `steps` | yes | yes | yes | yes | yes |
| `poll_url` | yes | — | — | — | — |
| `estimated_seconds` | yes | — | — | — | — |
| `current_step` | — | yes | — | — | — |
| `estimated_seconds_remaining` (reserved) | — | `null` | `null` | `null` | `null` |
| `billing_notices` | yes | yes | yes | yes | yes |
| `results` | — | `null` | object | `null` | `null` |
| `error` | — | `null` | `null` | `{error, message}` | `null` |
| `created_at` / `completed_at` | — | `created_at` | both | `created_at` | `created_at` |

`billing_notices` is always present as an array — empty when every requested step ran (see [Poll & webhooks](https://api.documenter.ch/developers#polling)). A **cancelled** job carries `error: null` — a deliberate cancel is not a failure. The per-mode `results` shapes follow.

**Detailed result schemas and complete examples**

Full Chain

Chat

Rename

Form

Error

Document mode with transcription + generation + TARDOC. Each key only appears if that step ran.

```text
{
  "job_id": "doc_job_kVG4OV0K...",
  "status": "completed",
  "mode": "document",
  "steps": ["transcription", "generation", "tardoc"],
  "results": {
    "transcription": {
      "text": "[Medecin] Bonjour...\n[Patient] J'ai des maux de tete...",
      "speakers": [
        {"id": 1, "label": "Medecin"},
        {"id": 2, "label": "Patient"}
      ],
      "medications": [
        {"name": "Paracetamol", "dosage": null, "frequency": null}
      ],
      "audio_events": [],
      "duration_seconds": null,
      "language": null
    },
    "generation": {
      "content": "<article class=\"documenter-report\">\n  <section data-key=\"titre\"><h2>Rapport de consultation</h2></section>\n  <section data-key=\"anamnese\"><h2>Anamnèse</h2><p>Patient de 45 ans...</p></section>\n  ...\n</article>",
      "format": "html",
      "tokens_in": 850,
      "tokens_out": 420
    },
    "tardoc": {
      "codes": [
        {"code": "AA.00.0010", "description": "Consultation de base, 5 min", "tp": 9.57, "quantity": 1},
        {"code": "AA.00.0020", "description": "Consultation, +5 min", "tp": 9.57, "quantity": 3}
      ],
      "total_tp": 53.73,
      "currency": "CHF",
      "diagnoses": [
        {"patient_index": 1, "letter": "E", "code_range": "E10-E14", "description": "Diabète sucré"}
      ]
    }
  },
  "error": null,
  "created_at": "2026-04-04T14:30:00Z",
  "completed_at": "2026-04-04T14:31:25Z"
}
```

#### Field Reference

| transcription |  |  |
| --- | --- | --- |
| `text` | string | Full transcript with speaker labels: `[Medecin] ...\n[Patient] ...` |
| `speakers` | array | `[{id: int, label: "Medecin"\|"Patient"}]` |
| `medications` | array | `[{name, dosage, frequency}]`, names matched against the Swissmedic DB (a drug with no reliable match keeps its spoken name). `dosage` and `frequency` are declared but not surfaced today — read them as **always `null`**. |
| `audio_events` | array | Detected non-speech events. **May be empty** — treat `[]` as the normal case rather than a signal. |
| `duration_seconds` | float? | Audio duration in seconds. Populated on every audio job; still declared nullable, so handle null defensively. |
| `language` | string? | Detected language (FR, DE, IT, EN). **May be null** — it is reported only when language identification ran on the audio, so handle null. |
| `transcript_token` | string? | Send it back with this exact `text` as `content` to generate further documents from the transcript on any plan. No expiry. Returned on the poll and in webhooks. |
| generation |  |  |
| `content` | string | The real medical report, always a **string**, rendered in the requested `output_format`. `html`: an `<article class="documenter-report">` wrapping one `<section data-key="…">` per report section (each with an `<h2>` heading). `text`: plain text. `markdown`: Markdown. `json`: a **JSON-encoded string** on a **locked schema** — parse it (e.g. `JSON.parse`) to get the `{schema_version, output_mode, sections, extracted_at}` object; see [Structured JSON output](https://api.documenter.ch/developers#responses-json) just below. `docx`: **base64-encoded** Word bytes — decode before writing the file; see [Word (.docx) output](https://api.documenter.ch/developers#responses-docx). The model's internal `<reasoning>` and per-source `<extraction>` provenance are **never** included in any format. |
| `format` | string | Output format used |
| `tokens_in` | int? | Input tokens consumed |
| `tokens_out` | int? | Output tokens generated |
| tardoc |  |  |
| `codes` | array | `[{code, description, tp: float, quantity: int}]` |
| `total_tp` | float | Total tax points |
| `currency` | string | Always `"CHF"` |
| `diagnoses` | array | `[{patient_index: int, letter, code_range, description}]` — primary diagnosis per patient as extracted by the pipeline: the ICD-10-GM first letter plus the block range containing it and its French label (e.g. `"E"`, `"E10-E14"`, `"Diabète sucré"`). Never the full code. `patient_index` is the 1-based position of the patient in the consultation; patients are never named. Patients without an extracted diagnosis are omitted, so the array may be empty. |

#### Structured JSON output (`output_format: "json"`)

When you request `output_format: "json"`, `generation.content` is a **JSON-encoded string** — parse it (e.g. `JSON.parse` / `json.loads`) to get the structured object on a **locked schema**: `{schema_version, output_mode, sections, extracted_at}`, where the medical report is split into ordered sections, each carrying a stable machine `key` for your EHR to map and the report's original human `title`. (The JSON below is the *parsed* object — on the wire it arrives as a string inside `content`.)

**Breaking change (migration note).** The old shape was `{"sections":[{"name","relevance","content"}], "reasoning", "extracted_at"}`. The `name` field is **renamed and split** into two: `key` (the stable snake_case English machine key) and `title` (the verbatim human heading). The `relevance` and top-level `reasoning` fields are **gone** — the model's reasoning is never emitted. If you previously read `section.name`, switch to `section.key` for routing and `section.title` for display.

```text
{
  "schema_version": 1,
  "output_mode": "structured",
  "sections": [
    {
      "key": "diagnostic",
      "title": "Diagnostic",
      "parent": null,
      "content": "Céphalées de tension chroniques. Hypertension artérielle de stade 1."
    },
    {
      "key": "anamnese",
      "title": "Anamnèse",
      "parent": null,
      "content": "Patiente de 45 ans consultant pour des céphalées frontales bilatérales évoluant depuis 2 semaines, aggravées par le stress."
    },
    {
      "key": "antecedents",
      "title": "Antécédents",
      "parent": null,
      "content": "Pas d'antécédent neurologique. Migraine maternelle."
    },
    {
      "key": "examen_clinique",
      "title": "Examen clinique",
      "parent": null,
      "content": "TA 138/86 mmHg. Examen neurologique sans particularité. Pas de raideur de nuque."
    },
    {
      "key": "laboratoire",
      "title": "Laboratoire",
      "parent": null,
      "content": "FSC, ionogramme et CRP dans les normes."
    },
    {
      "key": "appreciation",
      "title": "Appréciation",
      "parent": null,
      "content": "Tableau compatible avec des céphalées de tension dans un contexte de stress, sans signe d'alarme."
    },
    {
      "key": "suivi",
      "title": "Suivi",
      "parent": null,
      "content": "Contrôle tensionnel à domicile. Réévaluation dans 3 semaines si persistance."
    },
    {
      "key": "unmapped",
      "title": "Salutations",
      "parent": null,
      "content": "Avec mes meilleures salutations,\nDr méd. Anne Favre"
    }
  ],
  "extracted_at": "2026-06-10T14:31:25Z"
}
```

| Field | Type | Description |
| --- | --- | --- |
| `schema_version` | int | Currently `1`. Bumped only on a breaking schema change. |
| `output_mode` | string | `"structured"` = the report was split into canonical sections. `"free_text"` = a narrative / insurance-form template returned as a single section with `key: "free_text"`. The mode is determined by the chosen prompt, not by a request flag. |
| `sections[].key` | string | The **stable machine key** your EHR maps to its own fields (or have DOCumenter return your field names directly — see below) — always snake_case English (e.g. `diagnostic`, `anamnese`, `antecedents`, `examen_clinique`, `laboratoire`, `appreciation`, `traitements`, `suivi`). The canonical catalog is roughly **31 keys** — it is the section taxonomy, not a tiny closed set. Fetch the full, authoritative list from [`GET /v1/section-keys`](https://api.documenter.ch/developers#section-keys) (also shown in the developer console’s Mapping tab). A report-level top heading (the document title) is emitted as `key: "titre"`; document chrome (no heading at all) falls back to `"unmapped"`, and a titled heading the catalog does not recognise falls back to the reserved key `"autre"` (below) — nothing is dropped. Route on this, not on `title`. |
| `sections[].title` | string \| null | The report's original heading, **verbatim**, in the report's language (French, German, or Italian). For display only — it varies by locale and prompt. `null` for a preamble section (text before the first heading) and for the single `free_text` section. |
| `sections[].parent` | string \| null | The original parent heading when a sub-section was promoted to top-level; `null` at the top level. |
| `sections[].content` | string | The clinical text of that section, Markdown-formatted. The clinical content is preserved, but a sub-heading that doesn't match a canonical section may be folded into its parent's content as a **bold label** (e.g. `**Résultats**`) rather than emitted as its own section — so it is faithful, not strictly byte-for-byte verbatim. |
| `extracted_at` | string | ISO 8601 timestamp of when the structured output was produced. Note: timestamps in real responses serialize with a numeric UTC offset (`…+00:00`), not a `Z` suffix — both are valid ISO 8601, so use a parser that accepts either (the examples on this page abbreviate to `Z`). |

**No data is ever dropped.** The report-level title is emitted as `key: "titre"`. A titled heading that doesn't match a canonical key is emitted under the reserved key `"autre"`, with the heading itself preserved verbatim in `title` — so every key you receive is one you can map, and the fallback is never derived from the report's own wording. Document chrome (salutation, signature) and any preamble before the first heading are bucketed under `key: "unmapped"` rather than discarded, so the round-trip is lossless. The same report-body fix applies to `html`, `markdown`, and `text`: they now render the real medical report and never leak the model's `<reasoning>` or `<extraction>` blocks.

**Map keys to your own fields (optional).** By default `key` is the canonical snake_case key above and your EHR maps it on your side. Alternatively, DOCumenter can return **your EHR's own field names directly** — and merge several canonical keys into one of your fields — applied server-side, organisation-wide (one map per organisation, shared by every key your org owns). Unmapped keys pass through unchanged. **One exception to merging:** `autre` is a whole class of unclassified sections rather than a single field, so mapping it remaps each such section *independently* — they keep their own `title` and are never folded together, even when another canonical key targets the same field. You edit the map yourself in the **developer console** (documenter.ch → Developers → Mapping), with a live preview. **The map in force when a job completes is the one applied to it** — a later edit affects new jobs only, never a job that has already finished. **Sandbox honors the same map** — sandbox structured output is rendered through the real converter with your org’s field map applied, so what you see in sandbox matches live exactly.

#### Word (.docx) output (`output_format: "docx"`)

When you request `output_format: "docx"`, `generation.content` is the **base64-encoded bytes** of a Word document and `generation.format` is `"docx"`. The response envelope is unchanged — `content` is still a string, so polling, webhooks and sandbox all work exactly as they do for the text formats. Decode it before writing the file:

```text
# Python
import base64
docx = base64.b64decode(result["results"]["generation"]["content"])
open("rapport.docx", "wb").write(docx)

// JavaScript (Node)
const docx = Buffer.from(result.results.generation.content, "base64")
fs.writeFileSync("rapport.docx", docx)
```

The document is **plain styled** — the same headings-and-paragraphs rendering as the `html` output, with no practice letterhead. Applying your own uploaded canvas template to `/v1` exports is not supported today; if you need letterhead, generate the report as `html` and merge it into your own template on your side.

**On a rendering failure this endpoint does not downgrade.** If the document cannot be built, the poll returns a retryable `503 DOC_SVC_001` rather than a `text` body — the same fail-closed rule `output_format: "json"` follows. Poll again: the result stays available and the conversion is retried. You will never receive a `content` that is plain text while `format` claims `docx`, so it is always safe to base64-decode-and-write once you get a 200.

```text
{
  "job_id": "doc_job_...",
  "status": "completed",
  "mode": "chat",
  "steps": ["chat"],
  "results": {
    "chat": {
      "content": "Les cephalees de tension sont le type le plus frequent...",
      "tokens_in": 120,
      "tokens_out": 85
    }
  }
}
```

| `content` | string | Assistant response text |
| --- | --- | --- |
| `tokens_in` | int? | Input tokens |
| `tokens_out` | int? | Output tokens |

**Sources:** Source citations (Swiss medical references) are available in the web platform. API source citations are on the roadmap and will be added as a `sources` array in a future non-breaking update.

```text
{
  "job_id": "doc_job_...",
  "status": "completed",
  "mode": "rename",
  "steps": ["renaming"],
  "results": {
    "renaming": {
      "suggestions": [{
        "original": "scan005.pdf",
        "suggested": "BERNARD (15.03.1956) - 2026-04-04 Imagerie CT de la hanche.pdf",
        "fields": {
          "surname": "BERNARD",
          "firstname": "Jean-Claude",
          "birthdate": "15.03.1956",
          "docdate": "2026-04-04",
          "doctype": "Imagerie",
          "content": "CT de la hanche",
          "type_detail": "CT de la hanche",
          "type_key": "imaging_report",
          "doctor": "Dr Martin",
          "source": "Cabinet Medical Lausanne",
          "recipient": "Dr Rousseau",
          "category": "imaging",
          "modality": "CT"
        }
      }],
      "format": {
        "field_order": ["surname", "birthdate", "docdate", "doctype", "type_detail"],
        "separators": [" (", ") - ", " ", " "],
        "source": "key"
      }
    }
  }
}
```

| `suggestions[].original` | string | Original filename |
| --- | --- | --- |
| `suggestions[].suggested` | string | Structured filename suggestion |
| `suggestions[].fields` | object | Extracted: surname, firstname, birthdate, docdate, doctype, content, type_detail, type_key, doctor, source, recipient, category, modality. **EVERY value is nullable** — a field is null whenever the document does not name it, which in practice is common for `firstname`, `recipient`, `source` and `doctor`. The keys are always all present; only the values vary. The sandbox fixture returns two of them as null on purpose, so a parser meets that case before production. `doctype` is always the composed type string the filename used, so it stays consistent with `suggested`; `type_key` and `type_detail` give you the parts. `category` is derived from `type_key` by a fixed table, one of `imaging`, `laboratory`, `functional`, `correspondence`, `procedure`, `legal`, `administrative`, `prescription`, `other`; most type changes observed between repeated runs stay within one category, but not all (an operative report read as a discharge letter changes category). `modality` is set only when `type_key` is `imaging_report` and is otherwise null: one of `RX`, `CT`, `IRM`, `US` (including doppler), `PET`, `SCINTI`, `MAMMO`, `DEXA`, `ANGIO` (catheter angiography and coronarography only; an angio-CT is `CT`, an angio-MRI `IRM`). Both vocabularies are additive-only: values may be added, never renamed or removed, so treat an unknown value as `other` / null. |
| `format` | object | The naming convention this job ran under: `field_order` (array), `separators` (array), `source` (`"key"` \| `"user"` \| `"default"`) |

Form mode. `results.form.document` is the filled form itself (base64, in the submitted form's own format); `fields[]` carries the same values as data, in form order. With audio, `results.transcription` is present too. Field-by-field reference: [Form mode](https://api.documenter.ch/developers#modes).

```text
{
  "job_id": "doc_job_...",
  "status": "completed",
  "mode": "form",
  "steps": ["form"],
  "results": {
    "form": {
      "document": {
        "content_base64": "JVBERi0xLjcKJc...",
        "format": "pdf",
        "media_type": "application/pdf",
        "sha256": "1bc089c1b4dc..."
      },
      "fields": [
        {"key": "p001:q001:f001", "question": "Numero de sinistre", "label": "Numéro de sinistre:",
         "section": "Rapport médical LAA", "page": 1, "type": "text", "options": null, "value": "24.128.456"}
      ],
      "summary": {
        "field_count": 59, "answered_count": 26, "failed_page_count": 0,
        "unplaced_field_count": 0, "continuation_page_count": 1
      }
    }
  },
  "error": null
}
```

`value` is an AI draft for the physician to verify; blanks are expected (the treating doctor's identity and signatures are always left for you to fill).

All `/v1` endpoints — including the `/v1/keys` management routes — return errors in the flat `{error, message}` shape below; structured route errors and `422` schema-validation failures both use it (validation failures add an `errors` array). The one exception is an unhandled `500`, which returns a plain `{"detail": "…"}` body. In a poll response the `error` field replaces `results`.

```text
// Job-level error (poll response)
{
  "job_id": "doc_job_...",
  "status": "error",
  "mode": "document",
  "steps": ["generation"],
  "results": null,
  "error": {
    "error": "DOC_SVC_001",
    "message": "audio_truncated",
    "reason": "audio_truncated"  // optional, see Errors → reason
  }
}

// Request-level error (immediate, no job created)
{
  "error": "DOC_AUTH_001",
  "message": "Invalid API key"
}
```

**Request errors** (401, 400, 403, 413) return immediately with `{error, message}`. No job is created.

## 6. Errors & retries

All public machine-to-machine `/v1` endpoints — processing, prompts, entitlements, and health — return errors in the flat envelope below; both structured route errors and `422` schema-validation errors use it, and schema validations also add an `errors` array for debugging (route-raised `400`s do **not** — only `422` schema failures). **Exception:** an unhandled `500` returns a plain `{"detail": "Internal server error"}` body, which does not use the flat `error`/`message` envelope.

```text
// Structured route error (most error codes)
{
  "error": "DOC_VAL_007",
  "message": "prompt_id not found or not accessible to this API key"
}

// Schema validation error (missing field, bad enum, type mismatch)
{
  "error": "DOC_VAL_001",
  "message": "Input should be 'concis', 'equilibre' or 'exhaustif' at `document.length`.",
  "errors": [
    {"type": "literal_error", "loc": ["body","document","length"],
     "msg": "Input should be 'concis', 'equilibre' or 'exhaustif'",
     "input": "banana",
     "ctx": {"expected": "'concis', 'equilibre' or 'exhaustif'"}}
  ]
}
```

Every response (including errors) includes an `X-Request-Id` header with a unique correlation ID for that request. When filing a support ticket at [dev@documenter.ch](mailto:dev@documenter.ch), quote that ID so we can pull the full trace from our logs.

See the [Error tab](https://api.documenter.ch/developers#response-schemas) in Response Schemas for the full response shape.

### Terminal job error reasons

A job that ends in `"status": "error"` may carry `error.reason`: a bounded machine-readable cause, set on any terminal code (most often `DOC_SVC_001`). Branch on `reason`, never on `message`. The field is **absent** when the cause is unknown, and request errors never carry it. The value set is **additive-only**: new values may appear, existing ones never change meaning, so treat an unknown value like an absent one. `DOC_FORM_006` never carries a `reason`: the code alone already means the form itself cannot be filled.

| `reason` | Code | Meaning | Resubmitting the same input helps? |
| --- | --- | --- | --- |
| `upstream_timeout` | `DOC_SVC_001` | A model server did not answer in time. | **Yes**, after a short backoff. |
| `upstream_unavailable` | `DOC_SVC_001` | No processing node could take the job. | **Yes**, after a short backoff. |
| `internal_error` | `DOC_SVC_001` | An unexpected failure on our side. | **Once.** If it fails again, contact support with the `job_id`. |
| `retries_exhausted` | `DOC_SVC_001` | We already retried the job on several nodes and every attempt failed. | **Once**, later. If it fails again, contact support with the `job_id`. |
| `audio_truncated` | `DOC_SVC_001` | The audio file is cut short (an interrupted upload or recording). | **No.** Send the complete file. |
| `audio_unreadable_format` | `DOC_SVC_001` | The audio container cannot be read (for example a missing index). | **No.** Re-export the recording. |
| `audio_proprietary_format` | `DOC_SVC_001` | A proprietary dictaphone format we cannot decode. | **No.** Convert it to a standard format first. |
| `audio_drm_protected` | `DOC_SVC_001` | The audio is copy-protected. | **No.** |
| `audio_decode_failed` | `DOC_SVC_001` | The audio could not be decoded, for no more specific reason. | **No.** Re-export the recording. |
| `audio_empty` | `DOC_SVC_001` | The audio file is empty. | **No.** |
| `audio_silent` | `DOC_SVC_001` | The recording contains no speech. | **No.** |
| `audio_too_large` | `DOC_SVC_001` | The audio exceeds the processing size limit. | **No.** Split or compress the recording. |
| `generation_input_too_large` | `DOC_SVC_001` | The sources and instruction do not fit the model's context. | **No.** Send fewer or shorter sources. |
| `generation_loop` | `DOC_SVC_001` | The model kept repeating itself; we already retried once with different sampling. | **No.** Change the sources or the instruction. |
| `generation_length` | `DOC_SVC_001` | The document hit the output limit; we already retried once with different sampling. | **No.** Request a shorter document or send fewer sources. |
| `exam_type_undetermined` | `DOC_SVC_002` | The dictation did not name the exam. | **No.** See `DOC_SVC_002` below. |
| `form_source_size` | `DOC_VAL_004` | `mode: "form"`: the transcript pushed the sources past 512 KiB. | **No.** Send less source material. |
| `form_no_source` | `DOC_VAL_002` | `mode: "form"`: the audio produced no transcript and nothing else was supplied. | **No.** Supply a source. |

### How to react — the retry taxonomy

Before the per-code table, here is the decision your integration should make for each class of failure. Every failure maps to exactly one action: **retry-now**, **backoff** (honor `Retry-After`), **refresh-credential**, **ask-physician**, **upgrade-plan**, or **never** (fix the request; a blind retry will fail identically).

| Failure class | Signal | Action |
| --- | --- | --- |
| Rate limited | `429` (`DOC_RATE_001`, `DOC_RATE_002`) | **backoff** — wait for `Retry-After`, then retry. Not a bug. |
| Service transient | `503` (`DOC_SRV_001`, `DOC_SVC_001`) | **backoff** — retry with backoff, honoring `Retry-After`. Never rotate your key on a `503`. |
| Async job failed | poll `status: "error"` | **retry-now** — resubmit as a new job (a fresh `Idempotency-Key`), unless `error.reason` says the input itself failed (see [reasons](https://api.documenter.ch/developers#error-reasons)). |
| Async job rejected your input | poll `status: "error"` with `DOC_FORM_006` or `DOC_SVC_002` | **never** — nothing failed on our side and the same file/audio fails identically. Send a fillable form, or supply the exam type. |
| Invalid / revoked key | `401` (`DOC_AUTH_001`, `DOC_AUTH_002`) | **refresh-credential** — fix or replace the API key. Do not retry unchanged. |
| Expired / invalid JWT | `401` (`DOC_AUTH_003`, `DOC_AUTH_004`) | **refresh-credential** — sign a fresh physician JWT with the correct secret. |
| Pairing-code problem | `401` (`DOC_AUTH_005`) | **ask-physician** — have them regenerate the pairing code on documenter.ch. |
| Plan / entitlement | `403` (`DOC_BILL_001`, `DOC_SUB_001`, `DOC_LIC_001`) | **upgrade-plan** — ask the physician to subscribe / upgrade, or free a license seat. Never retry unchanged. |
| Bad request | `400` / `413` / `422` (`DOC_VAL_001`–`009`, `015`) | **never** — fix the request. The same body will fail identically. |
| Idempotency conflict | `409` (`DOC_VAL_016`) | **never** (as-is) — use a new `Idempotency-Key` for the changed logical request, or retry the original request to replay its job. |
| Job gone / expired | `404` (`DOC_JOB_001`) / `410` (`DOC_JOB_002`) | **never** the poll — resubmit a new job if the result expired (1-hour TTL). |

`DOC_BILL_002` is not in this table — it is a non-fatal partial-fulfillment notice in `billing_notices[]`, not an error to react to. The full per-code reference follows; the `DOC_SIGNUP_*` codes of the signup-intent routes are listed with those routes in [Onboard a doctor](https://api.documenter.ch/developers#signup-intents).

**Full `DOC_*` error-code catalog**

| Code | HTTP | Meaning |
| --- | --- | --- |
| `DOC_AUTH_001` | 401 / 403 | **401:** invalid or missing API key — check the `Authorization: Bearer` header. **403:** a valid non-API-key credential (e.g. a logged-in documenter.ch browser session) was used on a `/v1` data-plane endpoint — `/v1` is machine-only and requires API-key auth. |
| `DOC_AUTH_002` | 401 | API key revoked. Issue a new one or contact [dev@documenter.ch](mailto:dev@documenter.ch) |
| `DOC_AUTH_003` | 401 | Physician JWT expired (institution mode) — sign a fresh token |
| `DOC_AUTH_004` | 401 | JWT signature invalid or malformed (institution mode) |
| `DOC_AUTH_005` | 401 | Missing or unrecognized `X-User-Token`. Institution mode: the `X-User-Token` header is **missing** (an expired JWT is `DOC_AUTH_003`; an invalid/malformed JWT is `DOC_AUTH_004` — see those rows). Partner mode: the pairing code is missing, unknown, revoked, expired (an unpaired code expires one year after creation; a code already bound to a vendor, or minted for your organisation through a signup intent, never expires), never activated (a freshly-created code left unused for 7 days is deactivated), **or bound to a different EHR vendor** (a code locks to the first vendor that uses it). All partner-mode conditions return this same code so the API never reveals which one tripped. Have the physician regenerate from documenter.ch → Profile → Patient record integration. |
| `DOC_AUTH_006` | 403 | Key or pairing-code *management* requires a logged-in browser session on documenter.ch, not API-key auth — mint/rotate/revoke keys and manage pairing codes there, not through `/v1`. |
| `DOC_AUTH_007` | 403 | Your API key was used on a non-`/v1` endpoint. Partner keys are restricted to the `/v1` machine surface documented here — browser and account endpoints are not reachable with an API key. |
| `DOC_VAL_001` | 400 / 422 | Schema validation failed: invalid mode, missing required field, bad enum value (e.g. `length: "banana"`, `role: "system"`), or type mismatch — returned as `422` with an `errors` array carrying the per-field validation detail for debugging. The **route-raised `400`** variants — a corrupt or unsupported uploaded/base64 document, more than one audio file in a multipart upload, or (in `form` mode) a `form` that is neither a PDF AcroForm nor a Word form, invalid `form.content_base64`, or more than one `form` part — use the same code but **without** an `errors` array (just `{error, message}`). |
| `DOC_VAL_002` | 400 | No usable input for the inferred steps — document/rename mode with no `content`, no `documents`, and no audio. In `form` mode: no `form` file part with `mode=form`, or no readable text in any source; as a terminal job error, audio that produced no transcript with nothing else supplied. (A missing chat `messages` array is caught earlier as `422 DOC_VAL_001` schema validation, not this code.) |
| `DOC_VAL_003` | 400 | Invalid webhook URL: the URL uses `https://` but resolves to a private or loopback IP (SSRF guard). A `http://` URL is rejected earlier by schema validation as `DOC_VAL_001` (422) because `webhook_url` requires the `https://` scheme. |
| `DOC_VAL_004` | 413 | File too large (100MB/file or 200MB total). In `form` mode the form itself is capped at 8 MB (PDF) / 2 MB (Word) and its sources at 16 files and 512 KiB of extracted text; the source bound is re-checked once a transcript joins, so it can also arrive as a terminal job error. |
| `DOC_VAL_006` | 400 | `tardoc:true` requires an audio source. TARDOC bills against a consultation transcript; send audio via `/v1/process/upload` or with `content_type=audio`. |
| `DOC_VAL_007` | 404 | `prompt_id` not found, malformed, or not accessible to this API key |
| `DOC_VAL_008` | 400 | `length` not valid for the chosen prompt — either the prompt has no length family, or the requested variant doesn't exist in this family. The error message lists what's available for that prompt. |
| `DOC_VAL_009` | 400 | The `Idempotency-Key` header exceeds 255 characters. It is rejected up front (never silently dropped, which would risk a duplicate job). Use a short unique token (e.g. a UUID). |
| `DOC_SRV_001` | 503 | **Retryable.** A server-side failure during authentication or request processing (e.g. a transient database outage) — *not* a problem with your key. Honor `Retry-After` and retry; do not rotate your key. |
| `DOC_RATE_001` | 429 | Per-key request rate exceeded (default 30/min). Honor `Retry-After`. |
| `DOC_RATE_002` | 429 | Concurrent job limit exceeded (default 10 active jobs per key) — wait for active jobs to finish. Returns `Retry-After: 10` (vs `DOC_RATE_001`, whose `Retry-After` is the number of seconds until the window frees a slot, at most 60). |
| `DOC_BILL_001` | 403 | The request includes uploaded documents or free-text notes, which require a higher plan. Tier-1 (Scribe) may only generate from the audio transcript. Upgrade the physician's subscription to IA-ssistant or IA-ssistant Pro to generate from documents in addition to the transcript. `mode: "form"` rides the same boundary: a Scribe-plan form request is rejected the same way (`capabilities.form_fill`). |
| `DOC_BILL_002` | — (notice) | Not an HTTP error — a non-fatal **partial-fulfillment** notice returned in `billing_notices[]` on the 202/poll/webhook. TARDOC was requested without an ia-ssistant-pro subscription, so the tardoc step was dropped; the transcript + note still ran. Upgrade the physician's plan to get billing codes. |
| `DOC_LIC_001` | 403 | License limit reached (institution mode, monthly cap). Blocks every `/v1` call for that physician except `GET /v1/health` and `GET /v1/entitlements`, so a monitoring probe keeps working and you can read the plan that hit the cap. |
| `DOC_SUB_001` | 403 | The paired physician has no active subscription (partner mode) — they must subscribe at documenter.ch |
| `DOC_SVC_001` | 503 / 200 | Processing service unavailable. As a `503` — on submit, or on a poll whose result rendering failed transiently, or whose result could not be fetched transiently — it is retryable as-is: back off and retry, honoring `Retry-After` (the underlying result is untouched; the next poll re-attempts it). As `error.error` inside a `200` poll body (with `"status": "error"`, `"results": null` and no `Retry-After`) the job itself has failed and will never advance — this is the terminal you get when the processing service restarted while your job was in flight (see [Edge cases → Processing restarts mid-job](https://api.documenter.ch/developers#edge-cases)). The terminal form also covers **input-specific failures** (a truncated or unreadable audio file, sources too large for the model) that fail the same way on every resubmission: **check `error.reason` before retrying** (see [reasons](https://api.documenter.ch/developers#error-reasons)). When `reason` is absent or says the failure is transient, it is **retryable by resubmission only:** submit the request again under a **new** `Idempotency-Key`; polling the dead job forever returns the same error, and replaying the original key returns that same dead job. |
| `DOC_SVC_002` | 200 | The exam type could not be determined from the dictation, so no report was generated. Radiology only, and only where the instruction is configured with an exam-template catalogue. Arrives as `error.error` inside a `200` poll body with `"status": "error"` and `"results": null`. **Do not retry the same audio** — the dictation contains no answer, so a retry asks the same question and fails identically. Either resubmit with the exam type supplied, or have the dictation re-recorded with the exam named in the header. Distinct from `DOC_SVC_001` on purpose: nothing failed on our side, and rotating keys or backing off will not help. |
| `DOC_FORM_006` | 200 | The form you submitted with `mode: "form"` cannot be filled: it has no native fillable fields — a scan, a flattened form, a Word file whose controls are not native — or it carries active content we refuse, or bytes we cannot read. Arrives as `error.error` inside a `200` poll body with `"status": "error"` and `"results": null`; the message names the cause, and the error carries no `error.reason`. **Do not retry the same file** — re-export the form from its source with its fields intact, or send a different one. The same code also ends a job whose filled document would exceed **9 MB**: send a lighter form. A form that fills only partially is *not* this error: it completes, with the blank fields counted in `results.form.summary`. |
| `DOC_JOB_001` | 404 | Job not found (or not owned by this API key) |
| `DOC_JOB_002` | 410 | Result expired (1h TTL, resubmit) |
| `DOC_VAL_015` | 400 | On `POST /v1/process`: the requested `prompt_id` is a form-fill preset, which cannot be used via the API (it is driven by an internal PDF form template you can't supply). Pick a prompt from `GET /v1/prompts`. |
| `DOC_VAL_016` | 409 | A submission reused an `Idempotency-Key` for a meaningfully different request. Use a new key for a new logical job. Harmless JSON reserialization and regenerated multipart boundaries are normalized and do not trigger this conflict. |

### Health Check

`GET /v1/health` returns `{"status": "ok"}` when the API is operational. Use this for uptime monitoring and alerting. No authentication required.

### API versioning & stability

**API Stability:** This is API **v1**. Breaking changes will ship under `/v2/` with at least **6 months overlap**. Non-breaking additions (new optional fields, new result types) are added in-place. **Document mode always generates a note** (including audio-only requests); if you want the transcript only, send `"mode": "transcript"`. `mode` is the single note / no-note axis, and `tardoc` is an orthogonal add-on accepted in both modes.

## 7. Limits & data handling

#### Rate Limits

Every API key — partner, institution, and sandbox alike — defaults to **30 requests/minute and 10 concurrent jobs** per key (a partner key's budget is shared across all physicians paired to it); raisable per-key on request. Exceeding returns `429` with `Retry-After`. The `X-RateLimit-Limit` (the per-minute cap) and `X-RateLimit-Window` (always `60` — the window in seconds) headers appear on normal post-auth responses (once the key is resolved), **not** on the early `401` auth-failure responses and **not** on the `429 DOC_RATE_001` rate-limit response (which carries only `Retry-After`: the number of seconds until the window frees a slot, at most `60`).

**Polling does not count.** `GET /v1/process/{job_id}` is exempt from `rate_limit_rpm` — poll as many jobs as you have in flight without spending the budget your submissions need, and the `X-RateLimit-*` headers are therefore not stamped on a poll response. Polling the same job more often than about every 2 seconds returns `429 DOC_RATE_001` with a short `Retry-After`; treat it as a floor on your poll interval, not a precise quota. Poll each job every 5 seconds (10 s after the first 30 s), or register a `webhook_url` and stop polling entirely. Polling job ids you do not own is the one poll shape that DOES spend `rate_limit_rpm`. Once the key's 60 s window is already full (`rate_limit_rpm` requests that spend the budget in the last 60 s), a poll is refused too, before its pairing code or JWT is evaluated, with `429 DOC_RATE_001` and a `Retry-After` of the seconds until the oldest of them leaves the window (1–60), so the poll route cannot be used to guess pairing codes. Keep submissions under the budget, or honour `Retry-After` on polls too.

#### Capacity & concurrency

Defaults are **30 requests/minute and 10 concurrent jobs** per key. When you batch, work queues behind the concurrency cap rather than running in parallel: submissions beyond 10 jobs already `accepted` or `processing` are refused with `429 DOC_RATE_002` and `Retry-After: 10`, and the cap frees a slot as each job reaches a terminal state — so submit as slots free up rather than firing a whole batch at once. **Polls do not spend that budget**: ten jobs in flight polled every five seconds costs nothing against the 30/minute limit, which is reserved for submissions and the other reads. Poll one job much faster than every 2 seconds and that poll returns `429 DOC_RATE_001` with a short `Retry-After` — a floor on the interval, not a precise quota. Polls are free only while the window has room: once submissions fill it, polls also get `429 DOC_RATE_001` until a slot frees. A `webhook_url` removes polling altogether. Transcription is the narrower path: audio jobs drain with limited parallelism, so a batch of recordings queues behind itself — expect the wall-time of a batch to grow with its size, rather than the whole batch finishing in the time one recording takes. Text-only document and chat requests are not bound by that.

#### Audio Duration

Recommended max **~60 minutes per file** (not hard-enforced). Supported: WAV, MP3, M4A, OGG, FLAC, WebM, AAC, Opus, WMA, AMR, MP4, 3GP, DSS, DVF. All audio is converted to WAV 16 kHz mono internally.

#### Forms (`mode: "form"`)

The blank form: **8 MB** for a PDF AcroForm, **2 MB** for a Word form (`.docx`/`.dotx`), admitted from the file's own bytes. Its sources: **16 files** and **512 KiB** of extracted text in total — counted after extraction and including the transcript when you send audio. Over any of them returns `413 DOC_VAL_004`. Per-key rate, concurrency and the 1-hour result TTL are the same as every other mode.

#### Result TTL

Results expire after 1 hour. Fetch them promptly or use a webhook.

**This page documents the EHR integration API only.** API results remain pollable for up to one hour for delivery and webhook recovery. That window is not the standalone web/mobile platform's retention behavior: standalone clinical processing results are not kept after delivery — they are queued for deletion when delivered to the user's browser and removed by automatic background cleanup (no fixed time guarantee).

Need FHIR? The `json` output format gives you structured data you can map to FHIR resources. Native FHIR R4 output (Composition resource) is planned — [let us know](mailto:dev@documenter.ch) if this is a priority for your integration.

### Edge cases

| Scenario | What happens |
| --- | --- |
| Audio is silent / too short | Transcription returns empty (or near-empty) `text` and no medications. The normalized `speakers` array still lists the canonical `Medecin` / `Patient` labels — don't rely on a zero-speaker count to detect silence; check `text` instead. |
| PDF is a scanned image | OCR runs automatically. Quality depends on scan resolution |
| Content is empty | 400 `DOC_VAL_002` — "Content or documents required" |
| Webhook endpoint is down | Up to 3 delivery attempts, roughly 30s apart. After 3 failures, result is still pollable via GET for 1 hour |
| Result not polled within 1 hour | 410 `DOC_JOB_002` — result expired, must resubmit |
| JSON body too large | Recommended max **~10 MB** for the `/v1/process` JSON body. There is no hard 10 MB app-level cap today — the gateway accepts up to ~200 MB — but keep JSON bodies small and send bulky audio / PDFs via `/v1/process/upload` (multipart) instead. |
| Rate limit exceeded | `429 DOC_RATE_001` with **only** a `Retry-After` header (seconds until the window frees a slot, at most 60; a short 1–2 s when it is one job polled faster than the ~2 s floor, which is throttled per job and never spends the per-minute budget; a poll arriving while the window is already full gets the window's `Retry-After`) — the `X-RateLimit-Limit` / `X-RateLimit-Window` headers are **not** on this response (nor on the early `401` auth-failure responses). They appear on normal post-auth responses, and on the route-level `429 DOC_RATE_002` concurrent-job limit (which carries `Retry-After: 10`). |
| Processing restarts mid-job | An unplanned restart of the processing service loses every job it was holding. A **multi-step** job — a chained pipeline such as `transcription → generation` or `transcription → generation → tardoc` — additionally loses the accepted context that carries your uploaded source between steps. What you observe depends on where the job was: **Still running** (any step, single- or multi-step) — the poll keeps returning `processing`, typically for about two and a half minutes after the restart (sooner if the step had already been running a while, longer when our recovery sweep is working through a backlog), then the job terminates as a `200` poll body with `"status": "error"`, `"results": null` and `error.error` = `DOC_SVC_001`. There is no `Retry-After` on this response. You never receive a `completed` carrying a partial result, and never a `5xx`. If you registered a `webhook_url`, this same `"status": "error"` terminal is delivered by webhook — you do not have to be polling to learn the job died. **Already `completed`** — the finished result was held in that service's memory, so the next poll returns `410 DOC_JOB_002` straight away, well before the 1-hour TTL would have expired it. That `410` is reserved for a result the service confirms is gone; while it is merely unreachable you get a retryable `503 DOC_SVC_001` with `Retry-After` instead, so a brief blip never reads as a lost result. If you registered a `webhook_url`, you receive a **terminal error callback** for this case — `"status": "error"`, `"results": null` and `error.error` = `DOC_JOB_002` — so a webhook-only integration learns the result is gone without polling. We never deliver a `completed` callback with no result. The job row itself stays recorded as completed, so the poll keeps answering `410 DOC_JOB_002`. Both outcomes are terminal and retryable: **resubmit with a NEW `Idempotency-Key`**. Replaying the original key returns the original failed job (`202` whose body already carries `"status": "error"`) and starts no new work. Results are pollable only within the stated window and are **not durable across a restart of the processing service**. |

## 8. Test it live

Three ways to validate your integration before going live, in order of fastest to most thorough:

1. **[In the browser](https://api.documenter.ch/developers#test-live)** — paste your sandbox key, click Send. ~30 seconds.
2. **[Postman collection](https://api.documenter.ch/developers/samples/Documenter.postman_collection.json)** — pre-built requests for every endpoint, set `api_key`, hit Send. ~2 minutes.
3. **[Real test files + curl](https://api.documenter.ch/developers#test-real-data)** — download our Bernard sample bundle (audio + PDFs + transcripts) and run the full transcription + report + TARDOC chain end-to-end. ~5 minutes.

### Real test files

Download these synthetic test files (fictional patient, Swiss-realistic) and run the full pipeline yourself. The audio is a ~90-second doctor-patient consultation in French.

#### Bernard Test Files

All 7 files in one download (2.3 MB)

[Download .zip](https://api.documenter.ch/developers/samples/Bernard_test_files.zip)

#### Postman Collection

Pre-built requests for every endpoint. Set your `api_key` variable and Send.

[Download .json](https://api.documenter.ch/developers/samples/Documenter.postman_collection.json)

| File | Description |
| --- | --- |
| `Consultation.ogg` | Doctor-patient dialogue, 85s (audio) |
| `Dictée.mp3` | Doctor dictation, 80s (audio) |
| `Transcript_dictee.txt` | Text transcript of the dictation |
| `lettre_urgences.pdf` | Emergency referral letter to CHUV |
| `resultats_labo.pdf` | Unilabs blood work (troponin, BNP, creatinine) |
| `Rapport_cardio_2025.pdf` | Cardiology report (echo + stress test) |
| `rapport_hospitalier.pdf` | Inpatient discharge summary |

### The Exact Query: Send Raw Files → Get Everything Back

These examples use `POST /v1/process/upload` (multipart) to send raw files directly — no base64, no preprocessing. We extract text from PDFs, transcribe audio, and run the full pipeline.

#### curl

```bash
# Upload raw files — no encoding, no preprocessing
# Audio → transcribed, PDFs → text extracted, .txt → read as-is

curl -X POST https://api.documenter.ch/v1/process/upload \
  -H "Authorization: Bearer doc_live_YOUR_KEY" \
  -H "X-User-Token: YOUR_PHYSICIAN_JWT" \
  -F "tardoc=true" \
  -F "locale=fr" \
  -F "output_format=json" \
  -F "files=@Consultation.ogg" \
  -F "files=@lettre_urgences.pdf" \
  -F "files=@Rapport_cardio_2025.pdf" \
  -F "files=@Transcript_dictee.txt" \
  -F "text=Complément: patient anxieux, épouse présente et informée."

# Returns: {"job_id": "doc_job_...", "poll_url": "/v1/process/doc_job_..."}

# Poll until done (~60-120s)
curl https://api.documenter.ch/v1/process/doc_job_YOUR_ID \
  -H "Authorization: Bearer doc_live_YOUR_KEY" \
  -H "X-User-Token: YOUR_PHYSICIAN_JWT"

# You get back:
#   results.transcription.text        → speaker-labeled transcript from audio
#   results.transcription.medications → extracted medications
#   results.generation.content        → structured report (uses PDF + text context)
#   results.tardoc.codes              → TARDOC billing codes + tax points
```

#### Python

```python
import time
import httpx

API = "https://api.documenter.ch/v1"
headers = {
    "Authorization": "Bearer doc_live_YOUR_KEY",
    "X-User-Token": "YOUR_PHYSICIAN_JWT",
}

# Upload raw files — no encoding needed
resp = httpx.post(f"{API}/process/upload", headers=headers, timeout=120, data={
    "tardoc": "true",
    "locale": "fr",
    "output_format": "json",
    "text": "Complément: patient anxieux, épouse présente.",
}, files=[
    ("files", ("Consultation.ogg", open("Consultation.ogg", "rb"), "audio/ogg")),
    ("files", ("lettre_urgences.pdf", open("lettre_urgences.pdf", "rb"), "application/pdf")),
    ("files", ("Rapport_cardio_2025.pdf", open("Rapport_cardio_2025.pdf", "rb"), "application/pdf")),
    ("files", ("Transcript_dictee.txt", open("Transcript_dictee.txt", "rb"), "text/plain")),
])
resp.raise_for_status()
job_id = resp.json()["job_id"]

# Poll for at most 10 minutes.
deadline = time.monotonic() + 600
while time.monotonic() < deadline:
    poll = httpx.get(f"{API}/process/{job_id}", headers=headers, timeout=30)
    poll.raise_for_status()
    r = poll.json()
    if r["status"] in ("completed", "error", "cancelled"): break
    time.sleep(5)
else:
    raise TimeoutError(f"Job {job_id} did not finish within 10 minutes")

if r["status"] != "completed":
    raise RuntimeError(r.get("error") or "Job was cancelled")

print(r["results"]["transcription"]["text"])
print(r["results"]["generation"]["content"][:500])
for c in r["results"]["tardoc"]["codes"]:
    print(f"  {c['code']} - {c['description']} ({c['tp']} TP)")
```

**See the results**

The completed poll response from the call above — one job, every step back, shown with `output_format: "json"` (trimmed for readability). The `html` and `markdown` shapes, and each step's full field reference, are in [Response Schemas](https://api.documenter.ch/developers#response-schemas).

```text
{
  "job_id": "doc_job_kVG4OV0K...",
  "status": "completed", "mode": "document",
  "steps": ["transcription", "generation", "tardoc"],
  "results": {
    "transcription": {
      "text": "[Medecin] Bonjour Monsieur Bernard, qu'est-ce qui vous amene ?\n[Patient] Des douleurs dans la poitrine depuis deux jours...",
      "speakers": [{"id": 1, "label": "Medecin"}, {"id": 2, "label": "Patient"}],
      "medications": [{"name": "Aspirine Cardio", "dosage": null, "frequency": null}],
      "audio_events": [], "duration_seconds": null, "language": null
    },
    "generation": {
      "content": "{\"schema_version\":1,\"output_mode\":\"structured\",\"sections\":[{\"key\":\"motif_consultation\",\"title\":\"Motif de consultation\",\"parent\":null,\"content\":\"Douleurs thoraciques depuis deux jours.\"}, ...],\"extracted_at\":\"2026-06-10T14:31:25Z\"}", // JSON-encoded string — JSON.parse() it (parsed view below)
      "format": "json", "tokens_in": 3120, "tokens_out": 640
    },
    "tardoc": {
      "codes": [
        {"code": "AA.00.0010", "description": "Consultation de base, 5 min", "tp": 9.57, "quantity": 1},
        {"code": "AA.00.0020", "description": "Consultation, +5 min", "tp": 9.57, "quantity": 4}
      ],
      "total_tp": 47.85, "currency": "CHF"
    }
  },
  "error": null, "completed_at": "2026-06-10T14:31:25Z"
}

// results.generation.content after JSON.parse():
{
  "schema_version": 1, "output_mode": "structured",
  "sections": [
    {"key": "motif_consultation", "title": "Motif de consultation", "parent": null, "content": "Douleurs thoraciques depuis deux jours."},
    {"key": "anamnese", "title": "Anamnèse", "parent": null, "content": "Douleur retrosternale a l'effort, irradiation au bras gauche; dyspnee..."},
    {"key": "examen_clinique", "title": "Examen clinique", "parent": null, "content": "TA 148/88 mmHg, FC 92/min. Auscultation cardiaque sans souffle."},
    {"key": "diagnostic", "title": "Diagnostic", "parent": null, "content": "Suspicion de syndrome coronarien; antecedents cardiologiques (cf. rapport 2025)."}
  ],
  "extracted_at": "2026-06-10T14:31:25Z"
}
```

Each step's full field reference — and the `output_format: "json"` structured-section shape — is in [Response Schemas](https://api.documenter.ch/developers#response-schemas).

All files are synthetic (fictional patient "Jean-Claude BERNARD"). Safe for testing. The audio files are French-language doctor-patient consultations recorded at 48kHz.

## 9. Changelog & status

Notable, partner-visible changes to the `/v1` API, newest first. Non-breaking additions (new fields, new result types) ship in place; breaking changes ship under `/v2` with at least 6 months of overlap.

### Status & support

There is no public status page yet. For a quick operational signal, poll `GET /v1/health`. To report an incident or degraded performance, email [dev@documenter.ch](mailto:dev@documenter.ch) with the `X-Request-Id` of a failing response — we monitor `4xx`/`5xx` rates and API health, and that ID lets us pull the full trace.

**View release history**

- 2026-10-20 Spoken punctuation in dictation In `"mode": "dictation"`, French punctuation commands (*virgule*, *point*, *à la ligne*, …) now come back as punctuation and line breaks in `results.transcription.text`. See [Dictation mode](https://api.documenter.ch/developers#dictation-mode).
- 2026-10-19 Dictation mode New `"mode": "dictation"` on `POST /v1/process` and `/v1/process/upload`: one speaker dictating, plain text in `results.transcription.text`, with `speakers` and `audio_events` always `[]` and no `transcript_token`. Every plan. See [Dictation mode](https://api.documenter.ch/developers#dictation-mode). Additive.
- 2026-10-19 Starred instructions in the listing Each `GET /v1/prompts` item carries `is_favorite`: true when the physician starred that instruction on documenter.ch, where favourites are listed first. Always false without a physician. In the sandbox, the three parity physicians star *Courrier medical*, so you can build against it. Additive.
- 2026-10-17 Returned transcripts on multipart uploads `POST /v1/process/upload` (document mode) accepts `transcript` and `transcript_token`, so a returned transcript keeps counting as the consultation next to a note and documents. Other modes, an audio file sent with `transcript`, or a `transcript_token` without its `transcript` are rejected with `422 DOC_VAL_001`. Additive.
- 2026-10-16 Generate more documents from one transcript, on every plan Transcripts now carry a `transcript_token`. Send it back with the unchanged transcript to generate another document: the text keeps counting as a transcript, so Scribe physicians are no longer refused with `403 DOC_BILL_001`. Additive; nothing else changes.
- 2026-10-04 Markdown links keep their brackets, and render as links in `html` A report link written `[text](url)` used to lose its brackets in every format (`text(url)`). `html` now renders `http` and `https` links as `<a href>` anchors; `text`, `markdown` and `json` keep the markdown `[text](url)`; `docx` shows the link text only, without the URL. A link with any other scheme stays plain text. No field, type or default changes.
- 2026-10-04 Free-text headings render as headings In `free_text` mode, a `#` heading directly followed by text used to appear literally (`## Plan`) inside a paragraph, and could be pulled into the list before it. It now renders as a heading in `html` and `docx` and ends any open list. Structured output is unchanged. No field, type or default changes.
- 2026-10-04 Year-led lines stay text, not numbered lists A line that starts with a year, such as `2019. Cholecystectomy`, is now rendered as text in `html` and `docx` output. Before, it became a numbered list item: the `html` output began a list at `start="2019"`, and could fold the following heading or lines into it. Only markers of up to three digits start a list item. No field, type or default changes.
- 2026-10-04 Bold labels split from their value are rejoined When a report puts a bold label on one line and its colon-led value on the next (`**BP**` then `: 128/92`), every format now renders them as one line, `**BP** : 128/92`. In structured `json`, such a label no longer appears as a section of its own; its value stays in the enclosing section. A label that already ends in a colon is left as it is. No field, type or default changes.
- 2026-10-02 Default concurrent-job cap raised from 5 to 10 Every API key — partner, institution and sandbox — now defaults to **10** concurrent jobs instead of 5, existing keys on the old default included. A key whose cap was set to another value on request keeps it. The 30 requests/minute rate limit is unchanged, as are `429 DOC_RATE_002` and its `Retry-After: 10`. **Additive** — the cap only grows. See [Limits & data handling](https://api.documenter.ch/developers#limits).
- 2026-10-02 Terminal job errors carry an optional `reason` A job that ends in `"status": "error"` may now carry `error.reason`, a bounded cause such as `audio_truncated` or `upstream_timeout`, identical on every poll and in the webhook body. It tells a transient failure apart from one that resubmitting the same input cannot fix. The value set is additive-only and the field is absent when the cause is unknown. **Additive** — no error code, HTTP status or default changed. See [Terminal job error reasons](https://api.documenter.ch/developers#error-reasons). Sandbox: `length` with an explicit `prompt_id` of one of the curated sandbox prompts (which list no `lengths`) now returns `400 DOC_VAL_008`, as in production; omitting `prompt_id` is unchanged.
- 2026-10-01 Rename records carry `category` and `modality` Two additive keys on `suggestions[].fields`. `category` groups `type_key` into nine broad classes through a fixed table, so most changes between neighbouring types leave it unchanged. `modality` is the imaging modality, set only when `type_key` is `imaging_report` and null otherwise. Both value sets are additive-only; see [Rename mode](https://api.documenter.ch/developers#type-rename). Nothing on the request changed.
- 2026-09-26 New: signup intents — onboard a doctor and receive their pairing code Two new routes, `POST /v1/partner/signup-intents` and `GET /v1/partner/signup-intents/{intent_id}`, for organisations enabled for them. They take your API key only (no `X-User-Token`) and have their own 10 requests/minute budget. You get a signup link for the doctor; once they finish, the pairing code minted for your organisation is delivered by signed callback and by polling. New error codes `DOC_SIGNUP_001`–`DOC_SIGNUP_008`. **Additive** — no existing route, field or code changed. See [Onboard a doctor](https://api.documenter.ch/developers#signup-intents).
- 2026-09-25 `results.tardoc.diagnoses`: the primary diagnosis per patient An additive array `[{patient_index, letter, code_range, description}]` on `results.tardoc`: the ICD-10-GM first letter, the block range containing the diagnosis and its French label, never the full code. Patients without an extracted diagnosis are omitted, so the array may be empty. See [Response schemas](https://api.documenter.ch/developers#response-schemas).
- 2026-09-25 New `form` mode: send a blank official form, get it back filled `POST /v1/process` and `POST /v1/process/upload` accept `mode: "form"` with the blank form in its own `form` field / file part and the consultation as sources (text, documents, or audio — audio is transcribed first and `results.transcription` comes back too). The answer is the **same form, filled**, in its own format: a PDF AcroForm returns a filled, still editable AcroForm PDF, a Word form a filled `.docx`. The new `results.form` carries the document (base64 + `sha256`), every field with its value in form order, and bounded counts. Requires **ia-ssistant** (`capabilities.form_fill`, new on `GET /v1/entitlements`); a form that has no fillable fields terminates the job with the new `DOC_FORM_006`. Everything here is **additive** — no existing field, default, status or error code changed. **Values are AI drafts the physician must verify**, and the treating doctor's own identity is always left blank; see [Form mode](https://api.documenter.ch/developers#modes) for the limits.
- 2026-09-11 A paired pairing code no longer expires A pairing code now expires one year after creation only while it is still unpaired. Once bound to your organisation by its first use it never expires, until the physician revokes or regenerates it. No request or response changed; an integration that used to stop with `DOC_AUTH_005` after a year now keeps working. See [Authentication](https://api.documenter.ch/developers#authenticate).
- 2026-09-08 Sandbox submits return `processing`; your own pairing code works on your sandbox key A sandbox submit now returns `202 {"status": "processing", "estimated_seconds": 1}` and the job becomes `completed` on your first poll, so your polling and webhook code meets the same state ladder as live; it used to return `"completed"` at submit. Sandbox jobs also count against the concurrent-job cap. A member of your organisation can use their own pairing code with the organisation's sandbox keys, with their real tier and preferences. No field or error code changed. See [Sandbox vs production](https://api.documenter.ch/developers#sandbox-production).
- 2026-09-05 Rename mode follows a naming convention carried by your API key Set the filename layout once on the key, in either *imposed* or *default* mode — see [Rename mode](https://api.documenter.ch/developers#type-rename) for the resolution table. Two additive response changes: `results.renaming.format` now reports the convention actually applied and where it came from, and `suggestions[].fields` carries four more extracted fields (`type_key`, `doctor`, `source`, `recipient`) plus `type_detail`, the type's precision on its own. `type_detail` is also a filename field, so a convention can print the bare type label and the precision in separate slots. Nothing on the request changed.
- 2026-08-30 `GET /v1/prompts` now shows the sections each instruction produces Every item carries a `sections` preview — `canonical_key`, `title`, the `presence` rule, and the `key` you will actually receive, **with your organisation's field map already applied**. Build your field mapping against the listing instead of running a job to discover what comes back. It is `null` for instructions that do not declare their structure up front. `is_default` marks the one instruction used when you omit `prompt_id`. Both fields are additive — nothing existing changed. See [Listing prompts](https://api.documenter.ch/developers#prompts-list).
- 2026-08-29 Lost results: a terminal error webhook, and `503` split from `410` A result the processing service confirms it lost now fires a **terminal error callback** (`"status": "error"`, `error.error` = `DOC_JOB_002`) under its **own** `X-Webhook-Delivery-ID` — so a webhook consumer learns about the loss without polling, and dedup on the delivery id still works. Polling now distinguishes the two cases: a result that is merely *unreachable* returns a retryable `503 DOC_SVC_001` with `Retry-After: 30`, and the `410` is reserved for a result that is authoritatively gone. If you treated every non-`200` poll as a lost job, retry the `503` instead. See [Edge cases](https://api.documenter.ch/developers#edge-cases).
- 2026-08-29 Polling is off the per-minute budget, with a ~2 s per-job floor `GET /v1/process/{job_id}` no longer spends `rate_limit_rpm`: poll every job you have in flight without competing with your own submissions. In its place, each (key, physician, job) is throttled to about **one poll per 2 seconds** — exceed it and you get `429 DOC_RATE_001` with a short `Retry-After`. Treat it as a floor on your poll interval, not a quota. `Retry-After` on the per-minute limit is now derived from the actual window (seconds until a slot frees, never above `60`) rather than a flat value. Polling job ids you do *not* own still spends the budget. See [Rate limits](https://api.documenter.ch/developers#limits).
- 2026-08-29 `GET /v1/entitlements` and `/v1/health` stay reachable over the licence cap Both routes are now exempt from the licence-cap short-circuit, so they never return `DOC_LIC_001`. A monitoring probe carrying an over-cap physician’s token can still reach `/v1/entitlements` — which is how it discovers the cap it hit — and liveness checks keep working. Every other `/v1` route is unchanged.
- 2026-08-29 Your EHR field map is frozen at completion A job records the field map it completed under, and every later poll and webhook for that job is keyed with that frozen map. Editing your mapping in the developer console no longer silently re-keys results a partner already received, so a replayed webhook and the original delivery agree. New mappings apply to jobs submitted after the edit. See [Section keys](https://api.documenter.ch/developers#section-keys).
- 2026-08-28 Documented: what a processing-service restart does to an in-flight job An unplanned restart of the processing service loses the jobs it was holding. The observable behaviour is now spelled out per case — a running job keeps returning `processing` for roughly two and a half minutes, then terminates as a `200` poll body with `"status": "error"` and `DOC_SVC_001`; you never receive a `completed` carrying a partial result. `DOC_SVC_001` also has its own row in the error catalogue. See [Edge cases](https://api.documenter.ch/developers#edge-cases).
- 2026-08-05 `mode` is the note / no-note axis; `tardoc` works in both `document` mode **always generates a note**, including for **audio-only** requests (transcribe *then* generate from that transcript); for the transcript only, send `"mode": "transcript"`. `"tardoc": true` is now accepted in **transcript** mode too — transcription plus billing codes, with no note. Four shapes in total. See [Four Modes](https://api.documenter.ch/developers#modes).
- 2026-07-31 Closed key set — `autre` replaces ad-hoc fallback keys A titled section the catalogue cannot classify is now emitted under the reserved key `autre` instead of a slug derived from the heading's own wording. The key set is therefore closed: every `key` you receive appears in `GET /v1/section-keys`. The original heading is still preserved verbatim in `title`, and `catalogue_version` was bumped with the addition. If you special-cased unknown slug keys, map `autre` instead. See [Section keys](https://api.documenter.ch/developers#section-keys).
- 2026-07-30 New `GET /v1/section-keys` — the mapping contract, fetchable The canonical section-key catalogue is now an API endpoint instead of a screen in the developer console. Keys are **append-only**: a published key is never renamed or removed, and retirement is `deprecated: true`, which keeps the key in the list and still assigned so existing mappings keep working. Poll `catalogue_version` to notice the vocabulary moving. See [Section keys](https://api.documenter.ch/developers#section-keys).
- 2026-07-12 Sandbox tier simulation (the “test triad”) Three fake pairing codes — Scribe, IA-ssistant, and IA-ssistant Pro — now let you exercise all three plan tiers entirely in sandbox: real auth, real tier gates, and `GET /v1/entitlements`, with only the generated report mocked. Build and self-test your whole integration before you hold a real key. See [Sandbox vs production](https://api.documenter.ch/developers#sandbox-production).
- 2026-07-11 New `transcript` mode Submit audio to the new `transcript` mode for a speaker-labeled transcript with no note generated — a first-class transcription-only path with its own tighter request schema. `document` mode generates a note (including from audio); use `transcript` mode when you only ever want the transcript.
- 2026-07-11 Plan tier gates + partial fulfillment (`billing_notices[]`) Generating from uploaded documents or free-text notes now requires an IA-ssistant plan — a Scribe-tier request that attaches them is rejected with `403 DOC_BILL_001` and nothing runs. TARDOC requires IA-ssistant Pro; on a lower plan the tardoc step is **dropped** (transcript + note still returned) and a `billing_notices[]` entry (`DOC_BILL_002`) explains it. The new `billing_notices[]` array is present on the submit response, every poll, and the webhook.
- 2026-07-11 `GET /v1/entitlements` Read a physician's plan tier and capabilities before submitting, so your UI can gray out unavailable options up front. The per-request `billing_notices[]` remains the authoritative runtime signal.
- 2026-07-11 Idempotency scoped to key + physician; conflict returns `409` An `Idempotency-Key` is now scoped to your API key *and* the physician, so a shared partner key can't let one physician replay another's job. Reusing a key with a **different** logical request returns `409 DOC_VAL_016`; a semantically equivalent retry replays the original job and carries `Idempotent-Replayed: true`. Form-fill preset templates are rejected over the API with `400 DOC_VAL_015`.
- 2026-07-11 Webhook signing secret — self-service reveal When you mint or rotate a key in the developer console, you can now reveal and copy its webhook signing secret once, so a console-minted key can verify the `X-Webhook-Signature` HMAC.
- 2026-06-16 Contract corrections + robustness hardening Malformed inputs that previously returned `500` now return clean `4xx` errors in the standard envelope. Clarified that `mode` is required on JSON `POST /v1/process`, that `output_format: "json"` returns the structured sections as a JSON-encoded string, and that omitting `prompt_id` selects the platform default (*Note de suite - Cabinet*, `equilibre`).
- 2026-06-10 Partner API v1 launch Initial release: submit + poll/webhook, document / chat / rename modes, structured JSON output with a stable per-section key schema and an optional organization-wide field map, plus partner (pairing-code) and institution (JWT) authentication.
