Developer API

OCR (ocr-pdf)

Turn scans and photos into searchable PDFs, text, Markdown, JSON or Word with the ocr-pdf document operation, alone or as one step of a workflow. OCR is billed in credits from your plan.

OCR is a document operation

Run OCR like any other tool: POST /api/v2/document-operations with toolId ocr-pdf on a stored PDF or image version (PNG, JPEG, TIFF or WebP), then read the operation. Depending on outputMode, the output is the next version of the same document (a searchable PDF) or a new document (text, Markdown, JSON or Word). OCR can be any step of a chain or workflow, and the next step reads its output without a new upload.

cURL
#!/usr/bin/env bash
# Needs curl and jq.
# Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
set -euo pipefail
API="${WELLFRIEND_API_URL:-https://wellfriend.dev}"
WELLFRIEND_API_KEY="${WELLFRIEND_API_KEY:-YOUR_API_KEY}"
AUTH="Authorization: Bearer $WELLFRIEND_API_KEY"
RUN=$(uuidgen) # reuse this value to retry safely

# upload FILE CONTENT_TYPE KEY: prints the document id and its version id
upload() {
  curl -sS --fail-with-body -X POST "$API/api/v2/documents" -H "$AUTH" -H "Idempotency-Key: $3" \
    -H "Content-Type: $2" -H "X-Wellfriend-Filename: $(basename "$1")" --data-binary "@$1" \
    | jq -r '"\(.document.id) \(.document.currentVersion.id)"'
}

read -r DOCUMENT_ID VERSION_ID < <(upload 'scan.pdf' 'application/pdf' "$RUN-upload")

# Run ocr-pdf
OP=$(jq -n --arg doc "$DOCUMENT_ID" --arg ver "$VERSION_ID" --arg key "$RUN-1"  \
  --argjson parameters '{"languages":"en,hi"}' \
  '{documentId: $doc, versionId: $ver, toolId: "ocr-pdf", parameters: $parameters, idempotencyKey: $key}' \
  | curl -sS --fail-with-body -X POST "$API/api/v2/document-operations" -H "$AUTH" \
      -H "Content-Type: application/json" -H "Idempotency-Key: $RUN-1" --data-binary @- | jq -r .operation.id)
while :; do
  RESULT=$(curl -sS --fail-with-body "$API/api/v2/document-operations/$OP" -H "$AUTH")
  STATE=$(echo "$RESULT" | jq -r .operation.state)
  case "$STATE" in completed) break ;; failed|cancelled|canceled) echo "$RESULT" >&2; exit 1 ;; esac
  sleep 1
done
DOCUMENT_ID=$(echo "$RESULT" | jq -r .operation.outputDocumentId)
VERSION_ID=$(echo "$RESULT" | jq -r .operation.outputVersionId)

# Download the result
curl -sS --fail-with-body "$API/api/v2/documents/$DOCUMENT_ID/versions/$VERSION_ID/content" -H "$AUTH" -o 'scan-wellfriend.pdf'
Node
// Node.js 20+, no dependencies. An ES module (top-level await): save it as .mjs.
import { readFile, writeFile } from "node:fs/promises";
import { basename } from "node:path";

// Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
const API = process.env.WELLFRIEND_API_URL ?? "https://wellfriend.dev";
const auth = { Authorization: `Bearer ${process.env.WELLFRIEND_API_KEY ?? "YOUR_API_KEY"}` };
const run = crypto.randomUUID(); // reuse this value to retry safely
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function call(path, init = {}) {
  const response = await fetch(`${API}${path}`, { ...init, headers: { ...auth, ...init.headers } });
  if (!response.ok) throw new Error(`${response.status} ${path}: ${await response.text()}`);
  return response;
}

async function post(path, body) {
  const response = await call(path, { method: "POST", headers: { "Content-Type": "application/json", "Idempotency-Key": body.idempotencyKey }, body: JSON.stringify(body) });
  return response.json();
}

async function upload(path, contentType, key) {
  const response = await call("/api/v2/documents", {
    method: "POST",
    headers: { "Content-Type": contentType, "X-Wellfriend-Filename": basename(path), "Idempotency-Key": `${run}:${key}` },
    body: await readFile(path),
  });
  const { document } = await response.json();
  return { documentId: document.id, versionId: document.currentVersion.id };
}

let source = await upload("scan.pdf", "application/pdf", "upload");

let { operation } = await post("/api/v2/document-operations", {
  ...source,
  toolId: "ocr-pdf",
  parameters: { languages: "en,hi" },
  idempotencyKey: `${run}:1`,
});
while (!["completed", "failed", "cancelled", "canceled"].includes(operation.state)) {
  await sleep(1000);
  ({ operation } = await (await call(`/api/v2/document-operations/${operation.id}`)).json());
}
if (operation.state !== "completed") throw new Error(`ocr-pdf ${operation.state}: ${JSON.stringify(operation.error ?? null)}`);
source = { documentId: operation.outputDocumentId, versionId: operation.outputVersionId };

const output = await call(`/api/v2/documents/${source.documentId}/versions/${source.versionId}/content`);
await writeFile("scan-wellfriend.pdf", Buffer.from(await output.arrayBuffer()));
Python
# Python 3.9+ with requests (pip install requests).
import os
import time
import uuid

import requests

# Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
API = os.environ.get("WELLFRIEND_API_URL", "https://wellfriend.dev")
AUTH = {"Authorization": "Bearer " + os.environ.get("WELLFRIEND_API_KEY", "YOUR_API_KEY")}
run = uuid.uuid4().hex  # reuse this value to retry safely


def call(method, path, **kwargs):
    response = requests.request(method, API + path, headers={**AUTH, **kwargs.pop("headers", {})}, timeout=300, **kwargs)
    if not response.ok:
        raise RuntimeError(f"{response.status_code} {path}: {response.text}")
    return response


def post(path, body):
    return call("POST", path, json=body, headers={"Idempotency-Key": body["idempotencyKey"]}).json()


def upload(path, content_type, key):
    with open(path, "rb") as handle:
        document = call("POST", "/api/v2/documents", data=handle, headers={
            "Content-Type": content_type,
            "X-Wellfriend-Filename": os.path.basename(path),
            "Idempotency-Key": f"{run}:{key}",
        }).json()["document"]
    return {"documentId": document["id"], "versionId": document["currentVersion"]["id"]}


source = upload("scan.pdf", "application/pdf", "upload")

operation = post("/api/v2/document-operations", {
    **source,
    "toolId": "ocr-pdf",
    "parameters": {"languages": "en,hi"},
    "idempotencyKey": f"{run}:1",
})["operation"]
while operation["state"] not in ("completed", "failed", "cancelled", "canceled"):
    time.sleep(1)
    operation = call("GET", "/api/v2/document-operations" + "/" + operation["id"]).json()["operation"]
if operation["state"] != "completed":
    raise RuntimeError(f"ocr-pdf {operation['state']}: {operation.get('error')}")
source = {"documentId": operation["outputDocumentId"], "versionId": operation["outputVersionId"]}

output = call("GET", f"/api/v2/documents/{source['documentId']}/versions/{source['versionId']}/content")
with open("scan-wellfriend.pdf", "wb") as handle:
    handle.write(output.content)
TypeScript SDK
// wellfriend-document-sdk: npm install wellfriend-document-sdk@latest. An ES module (top-level await): save it as .mts.
// Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
import { Wellfriend } from "wellfriend-document-sdk";

const wf = new Wellfriend({ apiKey: process.env.WELLFRIEND_API_KEY ?? "YOUR_API_KEY" });
const result = await wf.tools.ocrPdf("scan.pdf", { languages: "en,hi" });
await result.save("scan-wellfriend.pdf");
Python SDK
# wellfriend-document-sdk: pip install -U wellfriend-document-sdk
# Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
import os

from wellfriend import Wellfriend

wf = Wellfriend(api_key=os.environ.get("WELLFRIEND_API_KEY", "YOUR_API_KEY"))
result = wf.tools.ocr_pdf("scan.pdf", languages="en,hi")
result.save("scan-wellfriend.pdf")
Go SDK
// go get wellfriend.dev/go/wellfriend@latest
package main

import (
	"context"
	"fmt"
	"os"

	"wellfriend.dev/go/wellfriend"
)

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func run() error {
	// Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
	apiKey := os.Getenv("WELLFRIEND_API_KEY")
	if apiKey == "" {
		apiKey = "YOUR_API_KEY"
	}
	wf := wellfriend.New(wellfriend.WithAPIKey(apiKey))
	ctx := context.Background()
	res, err := wf.Tools.OCRPDF(ctx, wellfriend.File("scan.pdf"), &wellfriend.OCRPDFParams{Languages: wellfriend.String("en,hi")})
	if err != nil {
		return err
	}
	return res.Save(ctx, "scan-wellfriend.pdf")
}
CLI
#!/usr/bin/env bash
# Needs the wellfriend CLI: npm install -g wellfriend-document-sdk@latest
# Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
set -euo pipefail
export WELLFRIEND_API_KEY="${WELLFRIEND_API_KEY:-YOUR_API_KEY}"
wellfriend ocr-pdf scan.pdf -o scan-wellfriend.pdf --param languages=en,hi
Rust SDK
// cargo add wellfriend-document-sdk serde_json && cargo add tokio --features full
use serde_json::json;
use wellfriend::{FileInput, types::OcrPdfParams, Wellfriend};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Your API key: set WELLFRIEND_API_KEY, or replace YOUR_API_KEY (keys: https://wellfriend.dev/dashboard/developer-api/keys).
    let api_key = std::env::var("WELLFRIEND_API_KEY").unwrap_or_else(|_| "YOUR_API_KEY".into());
    let wf = Wellfriend::builder().api_key(api_key).build()?;
    let params: OcrPdfParams = serde_json::from_value(json!({ "languages": "en,hi" }))?;
    wf.tools().ocr_pdf(FileInput::from("scan.pdf"), Some(params)).await?.save("scan-wellfriend.pdf").await?;
    Ok(())
}
MCP
// Wellfriend MCP server (your API key, YOUR_API_KEY, goes in your MCP client's config): call document_process, then operation_get until it is completed.
{
  "tool": "document_process",
  "arguments": {
    "documentId": "<documentId from document_upload_url>",
    "versionId": "<versionId>",
    "toolId": "ocr-pdf",
    "parameters": {
      "languages": "en,hi"
    },
    "idempotencyKey": "<run>:1"
  }
}

Options

OptionValuesNotes
languagesUp to 10 comma-separated codes from the OCR language listLanguages on the page, such as en or en,hi. Default en.
outputModesearchable-pdf, text, markdown, json, docxsearchable-pdf keeps the page images and adds an invisible text layer.
qualityfast, standard, highfast for clean prints, high for difficult scans and handwriting.
pageRangePage numbers and ranges, odd, even, last, last-NRead only these pages; blank reads every page.

Billing: credits from your plan

  • OCR draws credits from the same plan as everything else, at the published credit price: 5 credits for up to 15 pages, then 3.5 credits per further page, rounded up once per job, plus 1 request unit for the operation (or the chain step).
  • The free plan, the Developer D1, D2 and D3 plans and Team seats cover OCR through their credits; there is no separate OCR plan, allowance or pack. Without enough credits the step fails with CREDITS_EXHAUSTED; in a chain, earlier outputs stay readable and you can resume once your plan has credits again.
  • OCR runs in AI mode, so the account must accept the AI processing agreement first.

OCR templates

A template names the fields to extract from one kind of document, such as a supplier's invoices. In the dashboard (OCR, then Templates) you draw it on a sample page: open a document like the ones you will upload, add a field, name it, pick its kind (text, number, amount, date or yes/no) and drag its box into place. The sample stays in your browser; nothing is uploaded or charged.

Through the API, POST /api/ocr/v1/templates creates a template from a name and a JSON schema, a list of questions or a plain-English description; GET, PATCH and DELETE /api/ocr/v1/templates/{id} read, change and remove it. An extract job that sends template_id in its options returns the template's fields. Every template route has a snippet on the Snippets page.

Earlier OCR job routes

Integrations built on the OCR job routes (/api/ocr/v1/jobs, /detect, /jobs/{id}/result) keep working with the same developer key. For new integrations, use ocr-pdf: it chains with every other tool and is available in the SDKs, MCP and the snippet builder.