Developer API

Snippets

Ready code for every tool and every API feature: 210 snippets in cURL, JavaScript, Python, the TypeScript and Python SDKs and the CLI.

How the snippets are made

Every snippet is generated from the API's own definitions, not written by hand: 49 tools, 143 API operations from /docs/api/openapi.json, and 18 OCR job and template calls. SDK and CLI snippets use only methods and commands that exist in the published clients.

Tool snippets upload a sample file, run the tool with its default settings, wait for the operation and download the result. Change the parameters to the values you need; the Tool reference lists every option. Feature snippets send one request with the example body from the API contract and placeholders such as <documentId> for ids from earlier responses.

Your key goes in the WELLFRIEND_API_KEY environment variable on your server. Never put it in browser code: browser code should call your own server, which adds the key. A 202 response means accepted: read the returned operation, chain or run until it is completed.

Find a snippet

Search by tool, feature, path, scope or SDK method, filter by area, and pick a language once for every snippet. Each snippet has its own link, for example #merge-pdf or #secure-links.create.

Language

Area

210 snippets

PDF tools 21

Convert tools 21

Image tools 7

Documents and uploads 12

Document operations 3

Chains 5

Deal Rooms 21

Portals 8

Signatures 5

E-signatures 7

Forms 5

Annotations 5

Templates 5

OCR jobs and templates 18

Automations and workflows 11

Webhooks 13

Connectors 10

Embeds 9

Analytics 4

API keys and usage 6

Platform 2

MCP 1

End-to-end journey

The same document journey in three languages, as one runnable file each: upload input.pdf, process its exact version, poll the operation and download output.pdf. Each run uses new idempotency keys; reuse a key only to retry the same request.

cURL and jq
#!/usr/bin/env bash
set -euo pipefail
: "${WELLFRIEND_API_KEY:?Set WELLFRIEND_API_KEY to a wf_v2_test or wf_v2_live key}"
API="https://wellfriend.dev/api/v2"
AUTH="Authorization: Bearer ${WELLFRIEND_API_KEY}"
RUN_ID="$(date +%s)"

# 1. Ingest: the request body is the file itself. Keep the returned version ID.
DOCUMENT=$(curl --fail-with-body --max-time 120 -X POST "$API/documents" \
  -H "$AUTH" \
  -H "Content-Type: application/pdf" \
  -H "X-Wellfriend-Filename: input.pdf" \
  -H "Idempotency-Key: ingest-$RUN_ID" \
  --data-binary @./input.pdf)
DOCUMENT_ID=$(jq -r '.document.id' <<<"$DOCUMENT")
VERSION_ID=$(jq -r '.document.currentVersion.id' <<<"$DOCUMENT")

# 2. Process that exact immutable version (HTTP 202 = accepted, not finished).
OPERATION_ID=$(curl --fail-with-body --max-time 30 -X POST "$API/document-operations" \
  -H "$AUTH" \
  -H "Content-Type: application/json" \
  --data "{\"documentId\":\"$DOCUMENT_ID\",\"versionId\":\"$VERSION_ID\",\"toolId\":\"compress-pdf\",\"parameters\":{},\"idempotencyKey\":\"process-$RUN_ID\"}" \
  | jq -r '.operation.id')

# 3. Poll until the operation reaches a final state.
DEADLINE=$(( $(date +%s) + 600 ))
while :; do
  OPERATION=$(curl --fail-with-body --max-time 30 "$API/document-operations/$OPERATION_ID" -H "$AUTH")
  STATE=$(jq -r '.operation.state' <<<"$OPERATION")
  case "$STATE" in
    queued|running|cancelling) ;;
    completed) break ;;
    *) jq -c '.operation | {state, errorCode, errorMessage}' <<<"$OPERATION" >&2; exit 1 ;;
  esac
  [ "$(date +%s)" -lt "$DEADLINE" ] || { echo "Timed out waiting for $OPERATION_ID" >&2; exit 1; }
  sleep 2
done

# 4. Download the exact output version.
OUTPUT_DOCUMENT_ID=$(jq -r '.operation.outputDocumentId // .operation.documentId' <<<"$OPERATION")
OUTPUT_VERSION_ID=$(jq -r '.operation.outputVersionId' <<<"$OPERATION")
curl --fail-with-body --max-time 120 "$API/documents/$OUTPUT_DOCUMENT_ID/versions/$OUTPUT_VERSION_ID/content" \
  -H "$AUTH" -o ./output.pdf
Node.js 20+
import { readFile, writeFile } from "node:fs/promises";

const apiKey = process.env.WELLFRIEND_API_KEY;
if (!apiKey) throw new Error("Set WELLFRIEND_API_KEY to a wf_v2_test or wf_v2_live key.");
const API = "https://wellfriend.dev/api/v2";
const auth = { Authorization: `Bearer ${apiKey}` };
const runId = Date.now();

async function call(path, init = {}) {
  const response = await fetch(`${API}${path}`, { ...init, headers: { ...auth, ...init.headers }, signal: AbortSignal.timeout(120_000) });
  if (!response.ok) {
    const { error } = await response.json().catch(() => ({ error: {} }));
    throw new Error(`${path}: HTTP ${response.status} ${error.code ?? ""} ${error.message ?? ""} (reference ${error.referenceId ?? "none"})`);
  }
  return response;
}

// 1. Ingest the file bytes and keep the immutable version ID.
const ingested = await (await call("/documents", {
  method: "POST",
  headers: { "Content-Type": "application/pdf", "X-Wellfriend-Filename": "input.pdf", "Idempotency-Key": `ingest-${runId}` },
  body: await readFile("input.pdf"),
})).json();
const documentId = ingested.document.id;
const versionId = ingested.document.currentVersion.id;

// 2. Process that exact version. 202 means accepted, not finished.
const queued = await (await call("/document-operations", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ documentId, versionId, toolId: "compress-pdf", parameters: {}, idempotencyKey: `process-${runId}` }),
})).json();

// 3. Poll with a deadline until the operation is final.
const deadline = Date.now() + 10 * 60_000;
let operation = queued.operation;
while (["queued", "running", "cancelling"].includes(operation.state)) {
  if (Date.now() > deadline) throw new Error(`Timed out waiting for ${operation.id}`);
  await new Promise((resolve) => setTimeout(resolve, 2_000));
  operation = (await (await call(`/document-operations/${encodeURIComponent(operation.id)}`)).json()).operation;
}
if (operation.state !== "completed") throw new Error(`Operation ${operation.state}: ${operation.errorCode ?? "no code"}`);

// 4. Download the exact output version.
const outputDocumentId = operation.outputDocumentId ?? operation.documentId;
const content = await call(`/documents/${encodeURIComponent(outputDocumentId)}/versions/${encodeURIComponent(operation.outputVersionId)}/content`);
await writeFile("output.pdf", Buffer.from(await content.arrayBuffer()));
Python with requests
import os
import time

import requests

API = "https://wellfriend.dev/api/v2"
api_key = os.environ.get("WELLFRIEND_API_KEY")
if not api_key:
    raise SystemExit("Set WELLFRIEND_API_KEY to a wf_v2_test or wf_v2_live key.")
session = requests.Session()
session.headers["Authorization"] = f"Bearer {api_key}"
run_id = int(time.time())


def call(method, path, **kwargs):
    response = session.request(method, f"{API}{path}", timeout=120, **kwargs)
    if not response.ok:
        error = response.json().get("error", {}) if response.content else {}
        raise RuntimeError(f"{path}: HTTP {response.status_code} {error.get('code')} (reference {error.get('referenceId')})")
    return response


# 1. Ingest the file bytes and keep the immutable version ID.
with open("input.pdf", "rb") as source:
    ingested = call("POST", "/documents", data=source.read(), headers={
        "Content-Type": "application/pdf",
        "X-Wellfriend-Filename": "input.pdf",
        "Idempotency-Key": f"ingest-{run_id}",
    }).json()
document_id = ingested["document"]["id"]
version_id = ingested["document"]["currentVersion"]["id"]

# 2. Process that exact version. 202 means accepted, not finished.
operation = call("POST", "/document-operations", json={
    "documentId": document_id,
    "versionId": version_id,
    "toolId": "compress-pdf",
    "parameters": {},
    "idempotencyKey": f"process-{run_id}",
}).json()["operation"]

# 3. Poll with a deadline until the operation is final.
deadline = time.monotonic() + 600
while operation["state"] in ("queued", "running", "cancelling"):
    if time.monotonic() > deadline:
        raise RuntimeError(f"Timed out waiting for {operation['id']}")
    time.sleep(2)
    operation = call("GET", f"/document-operations/{operation['id']}").json()["operation"]
if operation["state"] != "completed":
    raise RuntimeError(f"Operation {operation['state']}: {operation.get('errorCode')}")

# 4. Download the exact output version.
output_document_id = operation.get("outputDocumentId") or operation["documentId"]
content = call("GET", f"/documents/{output_document_id}/versions/{operation['outputVersionId']}/content")
with open("output.pdf", "wb") as target:
    target.write(content.content)

Adapting a snippet for production

  • Keep the key in an environment variable or a secret manager.
  • Check file size, file type and your user's permissions before you upload.
  • Store the document, version and operation IDs with their idempotency keys.
  • Handle every operation state (queued, running, cancelling, completed, failed and cancelled) and the 403, 429 and 503 responses.