Python SDK
The deskew-sdk package (import name deskew_sdk) wraps the /v1 API for Python 3.9+. It depends on httpx only and ships a synchronous Deskew client and an AsyncDeskew twin with the same methods.
Install
Section titled “Install”pip install deskew-sdkexport DESKEW_API_KEY="deskew_test_sk_..."Current release: deskew-sdk 0.1.0 on PyPI. The import name is deskew_sdk (deskew on PyPI is an unrelated image-deskewing library). Source and issues: Metricall-AI-Lab/deskew-sdks.
Quickstart
Section titled “Quickstart”from deskew_sdk import Deskew
client = Deskew() # reads DESKEW_API_KEY; or Deskew(api_key="deskew_test_sk_...")
result = client.extract("invoice.pdf", output="json", fields=True, wait=True)
print(result.markdown)for table in result.tables or []: print(table.rows[0]) # header row print(table.csv)print(result.fields["total_amount"])print(result.usage.credits, "credits")file can be a path, bytes, an open binary file or a (filename, bytes) tuple. Pass url= instead of a file to have Deskew fetch the document. Every option of POST /v1/extract is a keyword argument with the same name and default: output, tables, bbox, handwriting, fields, language, extractor, quality, mode, webhook_url, pdf_password, plus idempotency_key. schema is still accepted as the deprecated alias for extractor.
Extract and wait
Section titled “Extract and wait”extract() returns 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).
from deskew_sdk import ExtractResult, Job
out = client.extract(url="https://example.com/annual-report.pdf", quality="accurate")
if isinstance(out, Job): print("queued", out.id, out.pages.total, "pages") result = client.jobs.wait(out.id, poll_timeout=900)else: result = outwait=True does the same in one call: a 200 is returned as is, a 202 is polled (GET /v1/jobs/{id} every poll_interval seconds, 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.
result = client.extract("big.pdf", mode="async", wait=True, poll_interval=2, poll_timeout=900)A job that ends failed or canceled raises JobFailed (with .job and the job’s error code); poll_timeout raises JobTimeout. Polling counts against your rate limit; for more than a handful of concurrent jobs, use webhooks.
import asynciofrom deskew_sdk import AsyncDeskew
async def main(): async with AsyncDeskew() as client: result = await client.extract("invoice.pdf", wait=True) async for job in client.jobs.iter(status="completed"): print(job.id, job.credits.used)
asyncio.run(main())Extractors
Section titled “Extractors”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.
from deskew_sdk import Deskew, ExtractorTestsFailing
client = Deskew()
# 1. Create a draft (or clone a starter: create("hospital-invoice", from_starter="hospital-invoice"))client.extractors.create("hospital-invoice", { "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 diffclient.extractors.test_documents.add("hospital-invoice", "samples/bill-0912.pdf", expected={"invoice_number": "INV-2026/0912", "total": 29800})run = client.extractors.test_runs.start("hospital-invoice") # target="draft"run = client.extractors.test_runs.wait("hospital-invoice", run.id) # polls until completedprint(run.summary.field_accuracy, run.summary.worst_fields)for r in run.results: print(r.file_name, r.passed, {k: v.status for k, v in (r.comparison.fields if r.comparison else {}).items()})
# 3. Publish; refused while the latest test run has failures unless force=Truetry: version = client.extractors.publish("hospital-invoice", notes="first version")except ExtractorTestsFailing as e: print(e.test_summary.failed, "of", e.test_summary.documents, "fail; run", e.test_run_id) raise
# 4. Extract with itresult = client.extract("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 tablesex = result.extractionprint(ex.status) # "ok", "flagged" or "rejected"print(ex.data["total"], ex.evidence["total"].page, ex.evidence["total"].source)for flag in ex.flags: print(flag.severity, flag.rule, flag.message, flag.fields)save_draft(name, definition) replaces the draft and returns valid plus problems (an invalid definition is not stored); validate(definition) checks one without storing anything. suggest("sample.pdf", 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():
proposal = client.extractors.suggest("sample-bill.pdf", wait=True)client.extractors.create("pharmacy-bill", proposal.definition)
client.lists.put("panel", open("panel.csv", "rb"), key="name") # text, bytes, a Path or a filefor job in client.extractors.iter_runs("hospital-invoice", status="flagged"): print(job.id, job.extraction.flags)| Method | Endpoint | Returns |
|---|---|---|
client.extractors.list(include_archived=False) |
GET /v1/extractors |
list[Extractor] |
client.extractors.create(name, definition=None, from_starter=None, include_test_set=True) |
POST /v1/extractors |
Extractor |
client.extractors.get(name, version=None, draft=False) |
GET /v1/extractors/{name} |
Extractor (with .definition, .json_schema) |
client.extractors.save_draft(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=False) |
POST /v1/extractors/{name}/publish |
ExtractorVersion; raises ExtractorTestsFailing on 409 |
client.extractors.versions(name) |
GET /v1/extractors/{name}/versions |
list[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=None, limit=20, starting_after=None) |
GET /v1/extractors/{name}/runs |
ExtractorRunList (.data, .has_more, .counts) |
client.extractors.iter_runs(name, status=None, page_size=100) |
paginated | iterator of Job |
client.extractors.suggest(file=None, url=None, job_id=None, wait=False, poll_interval=2, poll_timeout=600) |
POST /v1/extractors/suggest |
Suggestion (.status, .definition, .dropped) |
client.extractors.test_documents.list(name) |
GET .../test-documents |
list[TestDocument] |
client.extractors.test_documents.add(name, file=None, job_id=None, expected=None) |
POST .../test-documents |
TestDocument |
client.extractors.test_documents.set_expected(name, doc_id, expected) |
PUT .../test-documents/{id} |
TestDocument |
client.extractors.test_documents.remove(name, doc_id) |
DELETE .../test-documents/{id} |
None |
client.extractors.test_runs.start(name, target="draft", version=None, document_ids=None) |
POST .../test-runs |
TestRun |
client.extractors.test_runs.list(name, limit=10) |
GET .../test-runs |
list[TestRun] |
client.extractors.test_runs.get(name, run_id) |
GET .../test-runs/{id} |
TestRun (with .results) |
client.extractors.test_runs.wait(name, run_id, timeout=600, interval=2) |
polls get |
TestRun; raises TestRunTimeout |
client.starters.list() / .get(id) |
GET /v1/starters[/{id}] |
list[Starter] / Starter (with .definition) |
client.lists.list() |
GET /v1/lists |
list[LookupList] |
client.lists.put(name, csv, key=None) |
PUT /v1/lists/{name} (raw text/csv) |
LookupList |
client.lists.get(name) / .download(name) |
GET /v1/lists/{name}[?download=true] |
LookupList / bytes |
client.lists.remove(name) |
DELETE /v1/lists/{name} |
None |
Definitions are plain dicts; the ExtractorDefinition, FieldDef, RuleDef, DocumentSpec and OutputSpec TypedDicts are exported for editors and type checkers. client.schemas.list() / .create() still call the deprecated /v1/schemas compatibility endpoints; see Migrating from schemas.
Packets
Section titled “Packets”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.packet_starters the Deskew-maintained definitions to clone (top-level, like client.starters).
from deskew_sdk import Deskew, PacketTimeout
client = Deskew()
# 1. A definition: roles (each an extractor you have published) and cross-document rulesclient.packets.definitions.create("health-claim", { "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": None}, # 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", from_starter="health-claim")
# 2. Submit three files as one packet (always 202) and wait for ittry: packet = client.packets.create( ["claim-form.pdf", "final-bill.pdf", "pharmacy-1.jpg"], # paths, open files or (name, bytes) packet="health-claim", assignments={"claim-form.pdf": "health-claim-form"}, # skip routing for this file wait=True, poll_interval=2, poll_timeout=1800, )except PacketTimeout as e: print("still", e.packet.status) raise
# 3. Read itprint(packet.status) # "completed", "flagged", "failed" or "canceled"print(packet.data["bill"]["total"], packet.data["pharmacy_bills"]) # role -> data (a list for plural roles)for doc in packet.documents: print(doc.file_name, doc.role, doc.extractor, doc.routing.assigned, doc.routing.confidence, doc.extraction.status if doc.extraction else doc.status)for flag in packet.flags: print(flag.severity, flag.rule, flag.message, flag.fields)wait=True polls GET /v1/packets/{id} every poll_interval seconds until the packet leaves queued / processing; poll_timeout raises PacketTimeout with .packet. Without it the 202 packet is returned at once; pass webhook_url= (or subscribe an endpoint) and webhooks.verify hands you a packet.completed event whose data is the packet without data. Packet.from_dict(event["data"]) types it, client.packets.get(event["data"]["id"]) fetches the full one.
| Method | Endpoint | Returns |
|---|---|---|
client.packets.create(files, packet=None, assignments=None, webhook_url=None, *, wait=False, poll_interval=2, poll_timeout=1800) |
POST /v1/packets |
Packet (final one with wait=True) |
client.packets.list(status=None, limit=20, starting_after=None) |
GET /v1/packets |
PacketList (.data without data, .has_more, .counts) |
client.packets.iter(status=None, page_size=100) |
paginated | iterator of Packet |
client.packets.get(packet_id) |
GET /v1/packets/{id} |
Packet (with .data) |
client.packets.cancel(packet_id) |
DELETE /v1/packets/{id} |
Packet |
client.packets.wait(packet_id, timeout=1800, interval=2) |
polls get |
Packet; raises PacketTimeout |
client.packets.definitions.list(include_archived=False) |
GET /v1/packet-definitions |
list[PacketDefinition] |
client.packets.definitions.create(name, definition=None, from_starter=None) |
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.packet_starters.list() / .get(id) |
GET /v1/packet-starters[/{id}] |
list[PacketStarter] / PacketStarter (with .definition) |
Packet (id, status, env, definition as PacketDefinitionRef, documents as list[PacketDocument], data, flags as list[Flag], credits, created_at, finished_at, packet_url, plus .is_terminal, .is_completed, .errors), PacketDocument (id, job_id, position, file_name, role, extractor, version, routing as PacketRouting, status, extraction as ExtractionSummary, error), PacketDefinition, PacketUpdateResult and PacketStarter are dataclasses; the definition body is typed by the PacketDefinitionBody, PacketRoleDef and PacketRuleDef TypedDicts. Packet flags reuse Flag.
Background job + webhook
Section titled “Background job + webhook”Queue the job with a per-request webhook_url (or configure an endpoint in the dashboard), then verify each delivery with deskew_sdk.webhooks.verify. It checks the Deskew-Signature header (HMAC-SHA256 of "{t}.{body}", 5-minute tolerance, constant-time compare) and returns the parsed event.
client.extract(url=url, mode="async", webhook_url="https://hooks.example.com/deskew")import osfrom fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Requestfrom deskew_sdk import Deskew, SignatureVerificationError, webhooks
SECRET = os.environ["DESKEW_WEBHOOK_SECRET"]client = Deskew()app = FastAPI()
def download(job_id: str) -> None: result = client.jobs.result(job_id) ...
@app.post("/webhooks/deskew", status_code=204)async def deskew_webhook(request: Request, background: BackgroundTasks, signature: str = Header(default="", alias="Deskew-Signature")): body = await request.body() # raw bytes, not re-serialised JSON try: event = webhooks.verify(body, signature, SECRET) except SignatureVerificationError: raise HTTPException(400) if event["type"] == "job.completed": background.add_task(download, event["data"]["id"])Return 2xx within 10 seconds and do the work afterwards. Retries reuse the same X-Delivery-Id, so deduplicate on it. webhooks.sign(payload, secret) produces a valid header for your own tests.
Errors
Section titled “Errors”Every non-2xx response raises a subclass of DeskewError carrying the envelope fields (status, type, code, message, doc_url, param) and the request_id from X-Request-Id.
from deskew_sdk import (DeskewError, AuthenticationError, DocumentError, QuotaExceededError, RateLimitError, JobFailed)
try: result = client.extract("scan.pdf", wait=True)except DocumentError as e: # password_protected, corrupt_file, too_many_pages, ... print(e.code, e.message)except RateLimitError as e: # rate_limited, test_daily_cap time.sleep(e.retry_after or 5)except QuotaExceededError: ...except JobFailed as e: # the background job failed; e.job has the details print(e.job.error)except DeskewError as e: log.error("%s %s %s request_id=%s", e.status, e.code, e.message, e.request_id)| 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 | .retry_after 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, … |
ExtractorTestsFailing |
409 | extractor_tests_failing from publish; .test_summary, .test_run_id |
APIError |
5xx | processing_failed, engine_error, engine_unavailable |
APIConnectionError, APITimeoutError |
none | no response |
JobFailed, JobTimeout |
none | raised by wait (also by suggest(wait=True)) |
TestRunTimeout |
none | raised by extractors.test_runs.wait |
PacketTimeout |
none | raised by packets.wait (also by packets.create(wait=True)) |
SignatureVerificationError |
none | raised by webhooks.verify |
Branch on e.code, never on message.
Retries
Section titled “Retries”429, 5xx and connection errors are retried max_retries 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.
Reference
Section titled “Reference”Constructor: Deskew(api_key=None, *, base_url="https://api.deskew.dev", timeout=120, max_retries=2, http_client=None). AsyncDeskew takes the same arguments and every method below is await-able.
| Method | Endpoint | Returns |
|---|---|---|
client.extract(file=None, url=None, *, output="markdown", tables=True, bbox=False, handwriting=False, fields=False, language=None, extractor=None, schema=None, quality="auto", mode="auto", webhook_url=None, pdf_password=None, idempotency_key=None, filename=None, wait=False, poll_interval=1.5, poll_timeout=600) |
POST /v1/extract |
ExtractResult or Job |
client.jobs.get(job_id) |
GET /v1/jobs/{id} |
Job |
client.jobs.list(status=None, limit=20, starting_after=None) |
GET /v1/jobs |
JobList (.data, .has_more) |
client.jobs.iter(status=None, page_size=100) |
GET /v1/jobs (paginated) |
iterator of Job |
client.jobs.result(job_id) |
GET /v1/jobs/{id}/result |
ExtractResult |
client.jobs.cancel(job_id) |
DELETE /v1/jobs/{id} |
Job |
client.jobs.wait(job_id, poll_interval=1.5, poll_timeout=600) |
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.packet_starters.* |
/v1/packets, /v1/packet-definitions, /v1/packet-starters |
see Packets |
client.schemas.list() (deprecated) |
GET /v1/schemas |
list[Schema] |
client.schemas.create(name, json_schema) (deprecated) |
POST /v1/schemas |
Schema |
deskew_sdk.webhooks.verify(payload, signature_header, secret, tolerance=300) |
dict (the event) |
|
deskew_sdk.webhooks.sign(payload, secret, timestamp=None) |
header string |
Models are dataclasses with the API’s field names: ExtractResult (id, status, pages, markdown, text, blocks, tables, fields, extraction, page_results, usage, warnings), Extraction (extractor, version, status, document, data, evidence as dict[str, EvidenceEntry], flags as list[Flag], csv, plus .is_ok, .errors), ResultUsage (adds extractor_credits), Table (page, bbox, n_rows, n_cols, rows, csv, markdown, plus .header, .body, .to_dicts()), Block, PageResult, ResultUsage, Job (id, status, mode, pages.total/done/failed, eta_seconds, credits.estimated/used, engines, webhook_url, error, extraction as ExtractionSummary, created_at, started_at, finished_at, expires_at, result_url, poll_url, .is_terminal), Usage (plan, env, cycle_start, cycle_end, pages, credits, premium_credits, jobs, included_pages, .remaining_pages), Extractor, ExtractorVersion, DraftResult, ValidationResult, TestDocument, TestRun (summary as TestRunSummary, results as list[TestRunResult] with comparison.fields), Suggestion, Starter, LookupList, Packet, PacketDocument, PacketDefinition, PacketStarter, Schema. Timestamps are timezone-aware datetimes. Every model keeps the original JSON on .raw.