Working with the API

TypeScript SDK

@pendral/docuflow wraps every endpoint an API key can call in typed methods, follows documents live, reads the event feed, verifies webhooks and retries safely.

Install

npm install @pendral/docuflow

Runs on Node.js 20 or later, Bun, Deno and edge runtimes: anything with fetch and Web Crypto. ESM and CommonJS, no runtime dependencies.

Authenticate

Create a key under Developers → API keys and set it as DOCUFLOW_API_KEY. The client reads it from the environment. A key acts in one workspace, as its creator, narrowed to its scopes; see authentication.

import DocuFlow from "@pendral/docuflow";
const docuflow = new DocuFlow(); // reads DOCUFLOW_API_KEY
const me = await docuflow.whoami();
console.log(me.workspace.name, me.permissions);

Keep keys on your server

The client refuses to start in a browser unless you pass dangerouslyAllowBrowser: true. A key in a page is readable by anyone who opens it, and acts with its creator's permissions.

Upload and review

Upload into a queue, wait for the document to settle, read what was extracted and approve it. waitFor listens on the live stream and re-reads the document as a backstop, so a status reached before the call is never missed.

import { readFile } from "node:fs/promises";
const { documents } = await docuflow.documents.upload({
queue: "invoices",
files: { data: await readFile("invoice-1042.pdf"), name: "invoice-1042.pdf" },
});
const document = await docuflow.documents.waitFor(documents[0].id, { status: "needs_review" });
const { values, fields } = await docuflow.documents.fields.get(document.id);
await docuflow.documents.approve(document.id, { note: "Checked against the purchase order" });

For one call in and structured data out, extract uploads a file and holds the request until its values are ready:

const result = await docuflow.extract({
file: { data: await readFile("invoice-1042.pdf"), name: "invoice-1042.pdf" },
queue: "invoices",
});
if ("values" in result) console.log(result.values);

Follow documents live

Stream document progress in the workspace for as long as you iterate. The stream reconnects on its own, but cannot replay what was sent while it was disconnected.

for await (const event of docuflow.events.stream({ types: ["document.updated"] })) {
console.log(event.documentId, event.status, event.progress);
}

For a feed you can resume, follow the event log. Store each event's cursor after handling it and pass it back as after to pick up exactly where you left off after a restart. Delivery is at least once: deduplicate on event.id.

for await (const event of docuflow.events.log.follow({ after: await loadCursor() })) {
await handle(event);
await saveCursor(event.cursor);
}

Webhooks

Create a webhook once and keep its secret. The secret is returned once, at creation.

const { webhook, secret } = await docuflow.webhooks.create({
name: "Accounts payable",
url: "https://example.com/webhooks/docuflow",
events: ["document.needs_review", "document.approved"],
});
// Store secret as DOCUFLOW_WEBHOOK_SECRET.

createWebhookHandler returns a (Request) => Promise<Response> handler for Next.js route handlers, Hono, Bun, Deno and Workers. It verifies the signature before your code runs.

app/webhooks/docuflow/route.ts
import { createWebhookHandler } from "@pendral/docuflow/webhooks";
export const POST = createWebhookHandler({
secret: process.env.DOCUFLOW_WEBHOOK_SECRET!,
on: {
"document.approved": async (event) => {
await saveValues(event.data.document.id, event.data.fields);
},
},
});
400
Unsigned, wrongly signed or stale deliveries. They never reach your code.
204
Your handler resolved, or the event type has no handler.
500
Your handler threw, so the delivery is retried. Respond within 15 seconds; do slow work after acknowledging.

For Express or anything else, verify with constructEvent. Pass the raw request body, not parsed JSON: re-serializing changes the bytes and breaks the signature.

import { constructEvent, WebhookVerificationError } from "@pendral/docuflow/webhooks";
app.post("/webhooks/docuflow", express.raw({ type: "application/json" }), async (req, res) => {
try {
const event = await constructEvent(req.body, req.headers, process.env.DOCUFLOW_WEBHOOK_SECRET!);
if (event.type === "document.approved") await saveValues(event.data.document.id, event.data.fields);
res.sendStatus(204);
} catch (error) {
if (error instanceof WebhookVerificationError) return res.status(400).send(error.message);
throw error;
}
});

While rotating a secret, pass both: secret: [newSecret, oldSecret]. signPayload signs a body the way DocuFlow does, for testing your handler. The scheme itself is in the webhooks guide.

Pagination

List methods return the first page when awaited, and every item when iterated. The SDK fetches the next page as you go.

const page = await docuflow.documents.list({ status: "needs_review", limit: 50 });
console.log(page.data.length, page.hasNextPage(), page.nextCursor);
for await (const document of docuflow.documents.list({ status: "needs_review" })) {
console.log(document.id);
}
const recent = await docuflow.documents.list().toArray({ max: 500 });

Errors

10 classes

Every failure is a DocuFlowError carrying status, code, message, requestId, details and retryAfter. The code is the one from the error envelope; subclasses let you branch on the kind of failure.

import { PermissionDeniedError, PlanRequiredError, RateLimitError, NotFoundError } from "@pendral/docuflow";
try {
await docuflow.documents.approve(documentId);
} catch (error) {
if (error instanceof PermissionDeniedError) console.error("Missing", error.required);
else if (error instanceof PlanRequiredError) console.error("Needs the", error.requiredPlan, "plan");
else if (error instanceof NotFoundError) console.error("No such document");
else if (error instanceof RateLimitError) console.error(`Retry in ${error.retryAfter}s`);
else throw error;
}
400, 413, 415BadRequestError
The request is malformed or failed validation. For validation_failed, details lists each issue.
401AuthenticationError
The key is missing, invalid, revoked, or its creator was deactivated.
402PlanRequiredError
The workspace's plan does not allow this. requiredPlan, plan, feature and limit say why.
403PermissionDeniedError
The key's scopes, or its creator's role, lack the permission. required names it.
404NotFoundError
The object does not exist, or is in a workspace or queue the key cannot see.
409ConflictError
The object is not in a state that allows this, or an idempotent request is still running.
422UnprocessableEntityError
An Idempotency-Key reused with a different body.
429RateLimitError
Over the key’s requests per minute. retryAfter says when to try again.
5xxInternalServerError
Something failed on our side. Quote requestId to support.
noneAPIConnectionError, APITimeoutError
The request never got a response.

Retries and idempotency

Rate limits, server errors and dropped connections are retried twice with backoff, honouring Retry-After. Every write sends an Idempotency-Key and its retries reuse it, so the API runs the request once and answers every repeat with the first result. A retried upload never creates a second document.

Pass your own key to make an operation idempotent across your own retries, for example a job that may run twice:

await docuflow.documents.approve(documentId, {}, { idempotencyKey: `approve-${documentId}` });

How the API treats a repeated key is in idempotency.

Configuration

const docuflow = new DocuFlow({
apiKey: process.env.DOCUFLOW_API_KEY,
baseUrl: "https://docuflow.pendral.io",
maxRetries: 2,
timeoutMs: 60_000,
});
apiKey
Your dfk_ API key.Default: DOCUFLOW_API_KEY
baseUrl
The site's origin, without /api/v2. Must be HTTPS.Default: DOCUFLOW_BASE_URL, then https://docuflow.pendral.io
maxRetries
Per request. Override per call with { maxRetries }.Default: 2
timeoutMs
Per attempt. extract waits up to five minutes. Override per call with { timeoutMs }.Default: 60000
logLevel
off, error, warn, info or debug. Never logs keys, bodies or headers.Default: DOCUFLOW_LOG, then warn
fetch
Supply your own for proxies, instrumentation or tests.Default: global fetch
defaultHeaders
Sent with every request. Cannot override authentication.Default: none

Every call also takes { signal, timeoutMs, maxRetries, idempotencyKey, headers } as its last argument. Use withResponse() for the raw response, request id and rate-limit state:

const { data, requestId, rateLimit } = await docuflow.documents.get(documentId).withResponse();

An endpoint newer than your SDK

docuflow.request("documents.get", { path: { id } }) calls any operation by id, and docuflow.raw("GET", "/api/v2/...") calls any path, both with the client's credentials, retries and errors.

Command line

The package includes the docuflow CLI. It reads DOCUFLOW_API_KEY like the client does.

npx -p @pendral/docuflow docuflow whoami
npx -p @pendral/docuflow docuflow listen --forward-to http://localhost:3000/webhooks/docuflow
npx -p @pendral/docuflow docuflow tail --events document.updated
npx -p @pendral/docuflow docuflow events --after <cursor> --follow
npx -p @pendral/docuflow docuflow request GET /api/v2/documents --query status=needs_review
whoami
Which key this is, the workspace it acts in, what it may do and its rate budget.
listen
Forwards the workspace's events to a local URL, signed exactly like real webhook deliveries, so you can build your webhook handler without exposing your machine.
tail
Prints live document progress as it happens. --json prints each event in full.
events
Reads the event log from --after or --since; --follow keeps polling for new events.
request
Calls any endpoint with your key, to try one out before writing code for it.
openapi
Prints the OpenAPI document.

Where to go next