Document Intelligence

Three GPU-backed endpoints for turning unstructured documents (scans, photos, faxes, PDFs) into data. They accept a public URL, not an upload — host the file somewhere reachable first.

Method Endpoint Purpose
GET /v1/document/ocr Full-page OCR with optional layout analysis
GET /v1/document/extract Structured key/value fields (invoices, receipts, IDs)
GET /v1/document/classify Document type classification with alternatives

All three are synchronous: the request blocks until the GPU worker finishes. Expect seconds, not milliseconds.

These endpoints need the GPU task API to be online. If it is disabled or unreachable you get 503; a slow job returns 504. See Error cases.

1. OCR with layout analysis

GET /v1/document/ocr?url=...

Parameters

Name In Type Default Notes
url query string — Public URL of a PDF or image. Max 2048 characters.
language query string eng OCR language code (Tesseract-style, e.g. eng, deu, fra)
include_layout query boolean true Include per-page structural/bounding-box data
curl "https://pdf.toolkitapi.io/v1/document/ocr?url=https://example.com/scan.pdf" \
  -H "X-API-Key: YOUR_KEY"
import requests

r = requests.get(
    "https://pdf.toolkitapi.io/v1/document/ocr",
    headers={"X-API-Key": "YOUR_KEY"},
    params={
        "url": "https://example.com/scan.pdf",
        "language": "eng",
        "include_layout": False,  # smaller payload if you only need text
    },
    timeout=180,
)
r.raise_for_status()
doc = r.json()
print(f"{doc['page_count']} pages, lang={doc['language']}")
print(doc["text"][:500])
const params = new URLSearchParams({
  url: "https://example.com/scan.pdf",
  language: "eng",
  include_layout: "false",
});
const resp = await fetch(`https://pdf.toolkitapi.io/v1/document/ocr?${params}`, {
  headers: { "X-API-Key": "YOUR_KEY" },
});
if (!resp.ok) throw new Error(`OCR failed: ${resp.status}`);
const { text, page_count } = await resp.json();
console.log(`${page_count} pages, ${text.length} chars`);
Response
{
  "status": "ok",
  "text": "INVOICE\nAcme Corp\nInvoice No: INV-2241\n...",
  "pages": [
    { "page": 1, "text": "INVOICE\nAcme Corp...", "blocks": [] }
  ],
  "language": "eng",
  "page_count": 2,
  "task_id": "gpu-8f3c1a92"
}
The exact shape of each entry in `pages` comes from the GPU worker's layout analyser. When `include_layout=false`, `pages` may be `null` — always guard for it.

Field reference

Field Type Description
status string "ok" on success
text string Full extracted text, reading order preserved
pages array | null Per-page results (layout blocks, bounding boxes)
language string Language actually used
page_count integer | null Pages detected in the source
task_id string GPU task identifier — useful when contacting support

2. Structured field extraction

GET /v1/document/extract?url=...

Parameters

Name In Type Default Notes
url query string — Public URL of the document (PDF or image)
document_type query string auto Hint: invoice, receipt, id, or auto

Passing an explicit document_type improves accuracy and latency versus auto.

curl "https://pdf.toolkitapi.io/v1/document/extract?url=https://example.com/invoice.pdf&document_type=invoice" \
  -H "X-API-Key: YOUR_KEY"
import requests

r = requests.get(
    "https://pdf.toolkitapi.io/v1/document/extract",
    headers={"X-API-Key": "YOUR_KEY"},
    params={"url": "https://example.com/invoice.pdf", "document_type": "invoice"},
    timeout=180,
)
r.raise_for_status()
data = r.json()

fields = data["fields"]
if data["confidence"] is not None and data["confidence"] < 0.6:
    print("Low confidence — route to human review")
print(fields.get("invoice_number"), fields.get("total"))
const params = new URLSearchParams({
  url: "https://example.com/invoice.pdf",
  document_type: "invoice",
});
const resp = await fetch(`https://pdf.toolkitapi.io/v1/document/extract?${params}`, {
  headers: { "X-API-Key": "YOUR_KEY" },
});
const { fields, document_type, confidence } = await resp.json();

// Fields are free-form key/value — normalise keys before storing
const normalised = Object.fromEntries(
  Object.entries(fields).map(([k, v]) => [k.toLowerCase().replace(/\s+/g, "_"), v]),
);
console.log(document_type, confidence, normalised);
Response
{
  "status": "ok",
  "fields": {
    "invoice_number": "INV-2241",
    "date": "2026-03-14",
    "vendor": "Acme Corp",
    "total": "1482.00",
    "currency": "USD",
    "line_items": [
      { "description": "Consulting", "quantity": 12, "unit_price": "120.00" }
    ]
  },
  "document_type": "invoice",
  "confidence": 0.91,
  "task_id": "gpu-2b7d9e10"
}

Field reference

Field Type Description
status string "ok" on success
fields object Extracted key/value pairs. Keys and value types are not guaranteed — numbers may arrive as strings.
document_type string | null Detected type
confidence number | null 0.0–1.0 overall confidence, when the worker reports one
task_id string GPU task identifier

3. Document classification

GET /v1/document/classify?url=...

curl "https://pdf.toolkitapi.io/v1/document/classify?url=https://example.com/scan.pdf" \
  -H "X-API-Key: YOUR_KEY"
import requests

doc_type = requests.get(
    "https://pdf.toolkitapi.io/v1/document/classify",
    headers={"X-API-Key": "YOUR_KEY"},
    params={"url": "https://example.com/scan.pdf"},
    timeout=120,
).json()

print(doc_type["document_type"], doc_type["confidence"])
for alt in doc_type["alternatives"] or []:
    print("  also:", alt)
const resp = await fetch(
  "https://pdf.toolkitapi.io/v1/document/classify?url=https://example.com/scan.pdf",
  { headers: { "X-API-Key": "YOUR_KEY" } },
);
const { document_type, confidence, alternatives } = await resp.json();
const route = confidence >= 0.8 ? document_type : "manual_review";
console.log(route, alternatives);
Response
{
  "status": "ok",
  "document_type": "invoice",
  "confidence": 0.94,
  "alternatives": [
    { "document_type": "receipt", "confidence": 0.04 },
    { "document_type": "statement", "confidence": 0.01 }
  ],
  "task_id": "gpu-71aa03fd"
}
Field Type Description
status string "ok" on success
document_type string Predicted class (unknown when the model has no answer)
confidence number 0.0–1.0
alternatives array | null Runner-up classes with scores
task_id string GPU task identifier

classify → extract with the detected type → ocr only when you need raw text.

import requests

HEADERS = {"X-API-Key": "YOUR_KEY"}
BASE = "https://pdf.toolkitapi.io/v1"

def process(url: str) -> dict:
    cls = requests.get(f"{BASE}/document/classify", headers=HEADERS,
                       params={"url": url}, timeout=120).json()

    if cls["confidence"] < 0.7 or cls["document_type"] not in {"invoice", "receipt", "id"}:
        return {"route": "review", "reason": cls["document_type"]}

    ext = requests.get(f"{BASE}/document/extract", headers=HEADERS,
                       params={"url": url, "document_type": cls["document_type"]},
                       timeout=180).json()
    return {"route": "auto", "fields": ext["fields"], "confidence": ext["confidence"]}

Error cases

Status Endpoint Condition detail
503 all GPU processing disabled for this deployment GPU image processing is disabled (image toolkit) / GPU task API is currently unavailable
504 all Worker exceeded its time budget Task timed out (<reason>)
500 all Worker failed or returned no output Worker error message, or Task failed
422 all Missing url or url longer than 2048 chars FastAPI validation error
401/403 all Missing or invalid API key auth error

Common causes of 500 on otherwise valid URLs:

  • The URL is not publicly reachable (private IP, auth wall, signed URL expired).
  • The content is not a PDF/image (HTML error page from a redirect).
  • A scanned PDF with no text layer passed to a text-only path — use OCR instead.

Tips

  • Host the file publicly first. These endpoints fetch server-side; localhost, file://, and signed URLs that expire in minutes will fail. Use presigned URLs with at least a 10-minute TTL.
  • Right-size timeouts. Client timeouts below ~120 s will cut off legitimate multi-page jobs. Set 180 s for OCR/extract on documents over 10 pages.
  • include_layout=false is the single biggest payload saver. Bounding boxes roughly triple response size.
  • Never trust fields types. Parse with a permissive schema and keep the raw string alongside the parsed value so you can reprocess.
  • Log task_id. It's the only handle support has into the GPU queue.
  • Run classification before extraction. Auto-detection inside extract is more expensive than a hint from classify.
  • Retry 503/504, never 422. 503 is transient capacity; 504 may succeed on a shorter document or with layout disabled.
  • For born-digital PDFs, skip the GPU. Use text extraction instead — it's faster and deterministic; reserve OCR for image-only scans.