Skip to content

Node.js SDK

@deskew/sdk wraps the /v1 API for Node 18+ with zero runtime dependencies. It ships ESM and CommonJS builds and full TypeScript types for every request and response.

Terminal window
npm install @deskew/sdk
export DESKEW_API_KEY="deskew_test_sk_..."

Current release: @deskew/sdk 0.1.0 on npm. Works with pnpm, yarn and bun as well. Source and issues: Metricall-AI-Lab/deskew-sdks.

import { Deskew, isJob } from "@deskew/sdk";
const client = new Deskew(); // reads DESKEW_API_KEY; or new Deskew({ apiKey: "deskew_test_sk_..." })
const result = await client.extract({ file: "invoice.pdf", output: "json", fields: true, wait: true });
if (isJob(result)) throw new Error("unreachable with wait: true");
console.log(result.markdown);
for (const table of result.tables ?? []) {
console.log(table.rows[0]); // header row
console.log(table.csv);
}
console.log(result.fields?.total_amount);
console.log(result.usage.credits, "credits");

file accepts a Blob/File, Buffer, Uint8Array, ArrayBuffer, a web ReadableStream, a Node Readable such as fs.createReadStream(...), or a path string (Node only). Pass url instead to have Deskew fetch the document. Every option of POST /v1/extract is a camel-cased property with the API’s default: output, tables, bbox, handwriting, fields, language, extractor, quality, mode, webhookUrl, pdfPassword, plus idempotencyKey and filename. schema is still accepted as the deprecated alias for extractor.

extract() resolves to two kinds of value, exactly like the endpoint: an ExtractResult when the document was processed inline (200) and a Job when it was queued (202). The isJob() guard (or "object" in value) narrows the union.

const out = await client.extract({ url: "https://example.com/annual-report.pdf", quality: "accurate" });
const result = isJob(out)
? await client.jobs.wait(out.id, { pollTimeoutMs: 900_000 })
: out;

wait: true does the same in one call: a 200 is returned as is, a 202 is polled (GET /v1/jobs/{id} every pollIntervalMs, or at the job’s own eta_seconds when it reports one, never faster than once a second) and the result is fetched when the job completes.

const result = await client.extract({ file: "big.pdf", mode: "async", wait: true, pollIntervalMs: 2000, pollTimeoutMs: 900_000 });

A job that ends failed or canceled rejects with JobFailedError (with .job and the job’s error code); pollTimeoutMs rejects with JobTimeoutError. Pass { signal } as the second argument to any method to abort. Polling counts against your rate limit; for more than a handful of concurrent jobs, use webhooks.

An extractor is a named, versioned definition of one kind of document and the exact JSON you want out of it. client.extractors covers the whole lifecycle: create a draft, attach a test set, run it, publish, then pass extractor to extract() and read result.extraction.

import { Deskew, ExtractorTestsFailingError, isJob } from "@deskew/sdk";
const client = new Deskew();
// 1. Create a draft (or clone a starter: create("hospital-invoice", { fromStarter: "hospital-invoice" }))
await client.extractors.create("hospital-invoice", {
definition: {
title: "Hospital invoice",
document: { must_contain: ["itemised charges", "a total"], reject_if: ["a prescription"] },
fields: [
{ name: "invoice_number", type: "string", required: true, aliases: ["Bill No"] },
{ name: "total", type: "money", required: true },
{ name: "line_items", type: "group", fields: [
{ name: "description", type: "string" },
{ name: "amount", type: "money" },
] },
],
rules: [{ id: "items_sum", check: "abs(sum(line_items[].amount) - total) <= 1", message: "Line items do not add up" }],
},
});
// 2. Test: attach samples with their expected output, run the set, read the diff
await client.extractors.testDocuments.add("hospital-invoice", {
file: "samples/bill-0912.pdf",
expected: { invoice_number: "INV-2026/0912", total: 29800 },
});
let run = await client.extractors.testRuns.start("hospital-invoice"); // target: "draft"
run = await client.extractors.testRuns.wait("hospital-invoice", run.id); // polls until completed
console.log(run.summary?.field_accuracy, run.summary?.worst_fields);
for (const r of run.results ?? []) console.log(r.file_name, r.passed, r.comparison?.fields);
// 3. Publish; rejected while the latest test run has failures unless { force: true }
try {
await client.extractors.publish("hospital-invoice", { notes: "first version" });
} catch (e) {
if (e instanceof ExtractorTestsFailingError) {
console.log(e.testSummary?.failed, "of", e.testSummary?.documents, "fail; run", e.testRunId);
}
throw e;
}
// 4. Extract with it
const result = await client.extract({ file: "bill.pdf", extractor: "hospital-invoice", wait: true }); // "hospital-invoice@3" pins, "@draft" tries the draft
// output: "data" returns only result.extraction (no evidence) and result.usage: no markdown, text, blocks or tables
if (!isJob(result) && result.extraction) {
const { status, data, evidence, flags } = result.extraction;
console.log(status); // "ok" | "flagged" | "rejected"
console.log(data?.total, evidence?.total?.page, evidence?.total?.source);
for (const flag of flags) console.log(flag.severity, flag.rule, flag.message, flag.fields);
}

saveDraft(name, definition) replaces the draft and resolves to valid plus problems (an invalid definition is not stored); validate(definition) checks one without storing anything. suggest({ file, wait: true }) proposes a definition from a document, following a queued answer through the parse job the way the dashboard does. client.starters lists the Deskew-maintained definitions; client.lists uploads the CSV lookup lists that rules match with lookup():

const proposal = await client.extractors.suggest({ file: "sample-bill.pdf", wait: true });
await client.extractors.create("pharmacy-bill", { definition: proposal.definition! });
await client.lists.put("panel", await readFile("panel.csv"), { key: "name" }); // string, Buffer, ArrayBuffer or Blob
for await (const job of client.extractors.iterRuns("hospital-invoice", { status: "flagged" })) {
console.log(job.id, job.extraction.flags);
}
Method Endpoint Resolves to
client.extractors.list({ includeArchived? }) GET /v1/extractors Extractor[]
client.extractors.create(name, { definition?, fromStarter?, includeTestSet? }) POST /v1/extractors Extractor
client.extractors.get(name, { version?, draft? }) GET /v1/extractors/{name} Extractor (with definition, json_schema)
client.extractors.saveDraft(name, definition) PUT /v1/extractors/{name}/draft DraftResult (valid, problems)
client.extractors.validate(definition) POST /v1/extractors/validate ValidationResult
client.extractors.publish(name, { notes?, force? }) POST /v1/extractors/{name}/publish ExtractorVersion; rejects with ExtractorTestsFailingError on 409
client.extractors.versions(name) GET /v1/extractors/{name}/versions ExtractorVersion[]
client.extractors.version(name, n) GET /v1/extractors/{name}/versions/{n} ExtractorVersion (with definition)
client.extractors.rollback(name, version) POST /v1/extractors/{name}/rollback ExtractorVersion
client.extractors.archive(name) DELETE /v1/extractors/{name} Extractor
client.extractors.runs(name, { status?, limit?, startingAfter? }) GET /v1/extractors/{name}/runs ExtractorRunList (data, has_more, counts)
client.extractors.iterRuns(name, { status?, pageSize? }) paginated AsyncGenerator<ExtractorRun>
client.extractors.suggest({ file?, url?, jobId?, wait?, pollIntervalMs?, pollTimeoutMs? }) POST /v1/extractors/suggest Suggestion (status, definition, dropped)
client.extractors.testDocuments.list(name) GET .../test-documents TestDocument[]
client.extractors.testDocuments.add(name, { file?, filename?, jobId?, expected? }) POST .../test-documents TestDocument
client.extractors.testDocuments.setExpected(name, docId, expected) PUT .../test-documents/{id} TestDocument
client.extractors.testDocuments.remove(name, docId) DELETE .../test-documents/{id} void
client.extractors.testRuns.start(name, { target?, version?, documentIds? }) POST .../test-runs TestRun
client.extractors.testRuns.list(name, { limit? }) GET .../test-runs TestRun[]
client.extractors.testRuns.get(name, runId) GET .../test-runs/{id} TestRun (with results)
client.extractors.testRuns.wait(name, runId, { pollIntervalMs?, pollTimeoutMs?, signal? }) polls get TestRun; rejects with TestRunTimeoutError
client.starters.list() / .get(id) GET /v1/starters[/{id}] Starter[] / Starter (with definition)
client.lists.list() GET /v1/lists LookupList[]
client.lists.put(name, csv, { key? }) PUT /v1/lists/{name} (raw text/csv) LookupList
client.lists.get(name) / .download(name) GET /v1/lists/{name}[?download=true] LookupList / string
client.lists.remove(name) DELETE /v1/lists/{name} void

The definition types ExtractorDefinition, FieldDef, RuleDef, DocumentSpec, OutputSpec and the response types Extractor, ExtractorVersion, DraftResult, ValidationResult, TestDocument, TestRun, TestRunResult, Suggestion, Starter, LookupList, Extraction, ExtractionSummary, Flag, EvidenceEntry are exported. client.schemas.list() / .create() still call the deprecated /v1/schemas compatibility endpoints; see Migrating from schemas.

A packet is several documents submitted together: each is routed to (or assigned) an extractor, and a packet definition names the roles they fill plus cross-document rules. client.packets wraps /v1/packets, client.packets.definitions the definitions and client.packetStarters the Deskew-maintained definitions to clone (top-level, like client.starters).

import { readFile } from "node:fs/promises";
import { Deskew, PacketTimeoutError } from "@deskew/sdk";
const client = new Deskew();
// 1. A definition: roles (each an extractor you have published) and cross-document rules
await client.packets.definitions.create("health-claim", {
definition: {
title: "Health claim packet",
roles: {
claim: { extractor: "health-claim-form", min: 1, max: 1 },
bill: { extractor: "hospital-invoice", min: 1, max: 1 },
pharmacy_bills: { extractor: "pharmacy-bill", min: 0, max: null }, // plural role
},
rules: [{ id: "claimed_matches_bill", check: "abs(claim.claimed_total - bill.total) <= 1", message: "Claimed amount differs from the bill" }],
},
}); // or clone a starter: create("health-claim", { fromStarter: "health-claim" })
// 2. Submit three files as one packet (always 202) and wait for it
let packet;
try {
packet = await client.packets.create({
files: [
{ name: "claim-form.pdf", data: "claim-form.pdf" }, // File | Blob | { name, data }
{ name: "final-bill.pdf", data: await readFile("final-bill.pdf") }, // data: any extract() file input
{ name: "pharmacy-1.jpg", data: await readFile("pharmacy-1.jpg") },
],
packet: "health-claim",
assignments: { "claim-form.pdf": "health-claim-form" }, // skip routing for this file
wait: true, pollIntervalMs: 2000, pollTimeoutMs: 1_800_000,
});
} catch (e) {
if (e instanceof PacketTimeoutError) console.log("still", e.packet.status);
throw e;
}
// 3. Read it
console.log(packet.status); // "completed" | "flagged" | "failed" | "canceled"
console.log(packet.data?.bill, packet.data?.pharmacy_bills); // role -> data (an array for plural roles)
for (const doc of packet.documents) {
console.log(doc.file_name, doc.role, doc.extractor, doc.routing.assigned, doc.routing.confidence, doc.extraction?.status ?? doc.status);
}
for (const flag of packet.flags) console.log(flag.severity, flag.rule, flag.message, flag.fields);

wait: true polls GET /v1/packets/{id} every pollIntervalMs until the packet leaves queued / processing; pollTimeoutMs rejects with PacketTimeoutError carrying .packet. Without it the 202 packet is returned at once; pass webhookUrl (or subscribe an endpoint) and verifyWebhook hands you a packet.completed event whose data is the Packet without data (event.data as Packet; client.packets.get(event.data.id) fetches the full one).

Method Endpoint Resolves to
client.packets.create({ files, packet?, assignments?, webhookUrl?, wait?, pollIntervalMs?, pollTimeoutMs? }) POST /v1/packets Packet (final one with wait)
client.packets.list({ status?, limit?, startingAfter? }) GET /v1/packets PacketList (data without data, has_more, counts)
client.packets.iter({ status?, pageSize? }) paginated AsyncGenerator<Packet>
client.packets.get(packetId) GET /v1/packets/{id} Packet (with data)
client.packets.cancel(packetId) DELETE /v1/packets/{id} Packet
client.packets.wait(packetId, { pollIntervalMs?, pollTimeoutMs?, signal? }) polls get Packet; rejects with PacketTimeoutError
client.packets.definitions.list({ includeArchived? }) GET /v1/packet-definitions PacketDefinition[]
client.packets.definitions.create(name, { definition?, fromStarter? }) POST /v1/packet-definitions PacketDefinition
client.packets.definitions.get(name) GET /v1/packet-definitions/{name} PacketDefinition
client.packets.definitions.update(name, definition) PUT /v1/packet-definitions/{name} PacketUpdateResult (valid, problems, version)
client.packets.definitions.archive(name) DELETE /v1/packet-definitions/{name} PacketDefinition
client.packetStarters.list() / .get(id) GET /v1/packet-starters[/{id}] PacketStarter[] / PacketStarter (with definition)

The types Packet, PacketDocument, PacketDocumentExtraction, PacketRouting, PacketDefinitionRef, PacketList, PacketDefinition, PacketDefinitionBody, PacketRoleDef, PacketRuleDef, PacketUpdateResult, PacketStarter, PacketFileInput and the PacketStatus union are exported; packet flags reuse Flag. isPacketTerminal(packet) tells whether it has left queued / processing.

Queue the job with a per-request webhookUrl (or configure an endpoint in the dashboard), then verify each delivery with verifyWebhook. It checks the Deskew-Signature header (HMAC-SHA256 of "{t}.{body}", 5-minute tolerance, constant-time compare) and returns the typed event.

await client.extract({ url, mode: "async", webhookUrl: "https://hooks.example.com/deskew" });
import express from "express";
import { Deskew, SignatureVerificationError, verifyWebhook } from "@deskew/sdk";
const client = new Deskew();
const app = express();
// Keep the raw body: express.json() would re-serialise it and break the signature.
app.post("/webhooks/deskew", express.raw({ type: "application/json" }), (req, res) => {
let event;
try {
event = verifyWebhook(req.body, req.get("Deskew-Signature") ?? "", process.env.DESKEW_WEBHOOK_SECRET!);
} catch (e) {
if (e instanceof SignatureVerificationError) return res.status(400).end();
throw e;
}
res.status(204).end(); // respond first, work after
if (event.type === "job.completed") {
client.jobs.result(event.data.id).then(saveSomewhere);
}
});

Return 2xx within 10 seconds. Retries reuse the same X-Delivery-Id, so deduplicate on it. On runtimes without node:crypto, verifyWebhookAsync does the same check with WebCrypto. signWebhook(payload, secret) produces a valid header for your own tests.

Every non-2xx response rejects with a subclass of DeskewError carrying the envelope fields (status, type, code, message, docUrl, param) and the requestId from X-Request-Id.

import { DeskewError, DocumentError, QuotaExceededError, RateLimitError, JobFailedError } from "@deskew/sdk";
try {
const result = await client.extract({ file: "scan.pdf", wait: true });
} catch (e) {
if (e instanceof DocumentError) { // password_protected, corrupt_file, too_many_pages, ...
console.log(e.code, e.message);
} else if (e instanceof RateLimitError) { // rate_limited, test_daily_cap
await sleep((e.retryAfter ?? 5) * 1000);
} else if (e instanceof JobFailedError) { // the background job failed; e.job has the details
console.log(e.job.error);
} else if (e instanceof DeskewError) {
console.error(e.status, e.code, e.message, e.requestId);
} else throw e;
}
Class Status Notes
AuthenticationError 401 missing_api_key, invalid_api_key, key_revoked, key_expired
ForbiddenError 403 insufficient_scope, ip_not_allowed
QuotaExceededError 402 quota_exceeded
NotFoundError 404 job_not_found, extractor_not_found, extractor_version_not_found, test_document_not_found, list_not_found, packet_not_found, packet_definition_not_found
RateLimitError 429 .retryAfter in seconds
DocumentError 4xx type: "document_error"
InvalidRequestError other 4xx validation_error, unsupported_type, idempotency_conflict, result_not_ready, result_expired, extractor_unpublished, extractor_exists, extractor_invalid, …
ExtractorTestsFailingError 409 extractor_tests_failing from publish; .testSummary, .testRunId
APIError 5xx processing_failed, engine_error, engine_unavailable
APIConnectionError, APITimeoutError none no response
JobFailedError, JobTimeoutError none thrown by wait (also by suggest({ wait: true }))
TestRunTimeoutError none thrown by extractors.testRuns.wait
PacketTimeoutError none thrown by packets.wait (also by packets.create({ wait: true }))
SignatureVerificationError none thrown by verifyWebhook

Branch on e.code, never on message.

429, 5xx and connection errors are retried maxRetries times (default 2) with exponential backoff and jitter, waiting Retry-After when the server sends it. Other 4xx responses, including 409 idempotency_conflict, are never retried. extract() always sends an Idempotency-Key (a UUID when you do not pass one) and reuses it on every retry, so a retried upload replays the original response instead of creating a second job.

Constructor: new Deskew({ apiKey?, baseUrl? = "https://api.deskew.dev", timeoutMs? = 120000, maxRetries? = 2, fetch? }). Every method takes an optional trailing { signal?, timeoutMs? }.

Method Endpoint Resolves to
client.extract({ file?, filename?, url?, output?, tables?, bbox?, handwriting?, fields?, language?, extractor?, schema?, quality?, mode?, webhookUrl?, pdfPassword?, idempotencyKey?, wait?, pollIntervalMs?, pollTimeoutMs? }) POST /v1/extract ExtractResult | Job
client.jobs.get(jobId) GET /v1/jobs/{id} Job
client.jobs.list({ status?, limit?, startingAfter? }) GET /v1/jobs JobList (data, has_more)
client.jobs.iter({ status?, pageSize? }) GET /v1/jobs (paginated) AsyncGenerator<Job>
client.jobs.result(jobId) GET /v1/jobs/{id}/result ExtractResult
client.jobs.cancel(jobId) DELETE /v1/jobs/{id} Job
client.jobs.wait(jobId, { pollIntervalMs?, pollTimeoutMs?, signal? }) poll + result ExtractResult
client.usage() GET /v1/usage Usage
client.extractors.*, client.starters.*, client.lists.* /v1/extractors, /v1/starters, /v1/lists see Extractors
client.packets.*, client.packets.definitions.*, client.packetStarters.* /v1/packets, /v1/packet-definitions, /v1/packet-starters see Packets
client.schemas.list() (deprecated) GET /v1/schemas Schema[]
client.schemas.create(name, jsonSchema) (deprecated) POST /v1/schemas Schema
verifyWebhook(payload, signatureHeader, secret, { toleranceSec? = 300 }) WebhookEvent
verifyWebhookAsync(...) (WebCrypto) Promise<WebhookEvent>
signWebhook(payload, secret, timestamp?) header string
isJob(value), isTerminal(job), isPacketTerminal(packet) type guard / boolean / boolean

Types use the API’s field names unchanged, so the result object and job object pages apply directly: ExtractResult (with extraction?: Extraction), Table, Block, PageResult, ResultUsage (with extractor_credits?), Job (with extraction?: ExtractionSummary), JobList, Usage, Schema, WebhookEvent, ErrorDetail, the extractor types listed above, the packet types, and the string unions OutputFormat, Quality, Mode, JobStatus, PacketStatus, ExtractionStatus, FieldType.