> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.datalab.to/llms.txt
> Use this file to discover all available pages before exploring further.

# Structured Extraction

> Extract structured data from documents using JSON schemas.

Extract specific fields from documents by providing a JSON schema. Marker parses the document and fills in your schema with extracted values.

**Before you begin**, make sure you have:

1. A [Datalab account](https://www.datalab.to/auth/sign_up) with an [API key](https://www.datalab.to/app/keys)
2. Python 3.11+ installed
3. The Datalab SDK: `pip install datalab-python-sdk`
4. Your `DATALAB_API_KEY` environment variable set

> [!NOTE]
>
> EU requests return a signed `result_url`; the REST examples below download it before reading the output. See [Regional Result Downloads](https://documentation.datalab.to/docs/recipes/conversion/conversion-api-overview.md#regional-result-downloads), including the Python SDK 0.5.0 limitation.

> [!NOTE]
>
> **Building for production?** Use [Pipelines](https://documentation.datalab.to/docs/recipes/pipelines/pipeline-overview.md) to chain processors, version your configuration, and deploy with a single API call.

## Quick Start

```python Python SDK theme={null}
import json
from datalab_sdk import DatalabClient, ExtractOptions

client = DatalabClient()

schema = {
    "type": "object",
    "properties": {
        "invoice_number": {"type": "string", "description": "Invoice ID or number"},
        "total_amount": {"type": "number", "description": "Total amount due"},
        "vendor_name": {"type": "string", "description": "Company or vendor name"}
    },
    "required": ["invoice_number", "total_amount"]
}

options = ExtractOptions(
    page_schema=json.dumps(schema),
    mode="balanced"
)

result = client.extract("invoice.pdf", options=options)
extracted = json.loads(result.extraction_schema_json)
print(f"Invoice: {extracted['invoice_number']}")
print(f"Total: ${extracted['total_amount']}")
```

```bash cURL theme={null}
curl -X POST https://www.datalab.to/api/v1/extract \
  -H "X-API-Key: $DATALAB_API_KEY" \
  -F "file=@invoice.pdf" \
  -F "mode=balanced" \
  -F 'page_schema={"type":"object","properties":{"invoice_number":{"type":"string","description":"Invoice ID"},"total_amount":{"type":"number","description":"Total due"}}}'

# Poll request_check_url from response until status is "complete"
```

```python Python (requests) theme={null}
import requests, json, time, os

headers = {"X-API-Key": os.getenv("DATALAB_API_KEY")}

schema = {
    "type": "object",
    "properties": {
        "invoice_number": {"type": "string", "description": "Invoice ID"},
        "total_amount": {"type": "number", "description": "Total due"}
    }
}

with open("invoice.pdf", "rb") as f:
    response = requests.post(
        "https://www.datalab.to/api/v1/extract",
        files={"file": ("invoice.pdf", f, "application/pdf")},
        data={"page_schema": json.dumps(schema), "mode": "balanced"},
        headers=headers
    )

check_url = response.json()["request_check_url"]

delay = 0.3  # poll fast at first: most results are ready in seconds
while True:
    result = requests.get(check_url, headers=headers).json()
    if result.get("success") is False or result.get("status") == "failed":
        raise RuntimeError(result.get("error") or "Document processing failed")
    if result["status"] == "complete":
        if result.get("result_url"):
            download = requests.get(result["result_url"], timeout=60)
            download.raise_for_status()
            result = {**download.json(), **{k: v for k, v in result.items() if v is not None}}
        if result.get("success") is False:
            raise RuntimeError(result.get("error") or "Document processing failed")
        extracted = result["extraction_schema_json"]
        if isinstance(extracted, str):
            extracted = json.loads(extracted)
        print(extracted)
        break
    time.sleep(delay)
    delay = min(delay * 1.15, 1)
```

## Extraction Modes

The `extraction_mode` form parameter controls how extraction runs. This is separate from `mode`, which controls document parsing quality.

| Mode | Description | Base extraction rate | Latency |
| - | - | - | - |
| **turbo** | Image-only extraction without OCR, citations, verification, or confidence scores. Returns extracted JSON without parsed document output. | \$6 / 1K pages | Lowest |
| **fast** | Extraction with per-field citations | \$6 / 1K pages | Lowest |
| **balanced** (default) | Extraction with independent verification, per-field reasoning, and citations | \$15 / 1K pages | Moderate |
| **accurate** | Balanced extraction plus deeper completeness auditing and a stronger model for hard cases | \$20 / 1K pages | Slower |

Fast, balanced, and accurate modes return per-field citations. Balanced and accurate modes also return `_meta` fields with `extraction_status`, `reasoning`, and `verification` results. Turbo requires the source file and cannot reuse a checkpoint.

These are base extraction rates. Parsing is billed separately when it runs, and complex balanced or accurate requests can incur usage-based charges. See [Billing](https://documentation.datalab.to/platform/billing.md) and [pricing](https://www.datalab.to/pricing) for your applicable rates.

When `mode` is omitted from a REST request, balanced and accurate extraction use accurate parsing; fast uses fast parsing. An explicit `mode` overrides this choice. Turbo skips parsing.

> [!NOTE]
>
> `balanced` is the default. Teams that made an extraction request in the 30 days before June 4, 2026 default to `fast` instead. Pass `extraction_mode` explicitly to override the default in either case.

```python Python SDK theme={null}
import json
from datalab_sdk import DatalabClient, ExtractOptions

client = DatalabClient()
schema = {"type": "object", "properties": {"invoice_number": {"type": "string"}}}
options = ExtractOptions(page_schema=json.dumps(schema), extraction_mode="accurate", mode="accurate")
result = client.extract("invoice.pdf", options=options)
print(result.extraction_schema_json)
```

```bash cURL theme={null}
curl -X POST https://www.datalab.to/api/v1/extract \
  -H "X-API-Key: $DATALAB_API_KEY" \
  -F "file=@invoice.pdf" \
  -F 'page_schema={"type":"object","properties":{"invoice_number":{"type":"string"}}}' \
  -F "extraction_mode=accurate" \
  -F "mode=accurate"

# Poll request_check_url from the response until status is complete or failed.
```

```python Python (requests) theme={null}
import json
import os
import time
import requests

headers = {"X-API-Key": os.environ["DATALAB_API_KEY"]}
schema = {"type": "object", "properties": {"invoice_number": {"type": "string"}}}
with open("invoice.pdf", "rb") as file:
    response = requests.post(
        "https://www.datalab.to/api/v1/extract",
        headers=headers,
        files={"file": ("invoice.pdf", file, "application/pdf")},
        data={"page_schema": json.dumps(schema), "extraction_mode": "accurate", "mode": "accurate"},
    )
response.raise_for_status()
check_url = response.json()["request_check_url"]
delay = 0.3  # poll fast at first: most results are ready in seconds
while True:
    response = requests.get(check_url, headers=headers)
    response.raise_for_status()
    result = response.json()
    if result.get("success") is False or result.get("status") == "failed":
        raise RuntimeError(result.get("error", "Extraction failed"))
    if result.get("status") == "complete":
        if result.get("result_url"):
            download = requests.get(result["result_url"], timeout=60)
            download.raise_for_status()
            result = {**download.json(), **{k: v for k, v in result.items() if v is not None}}
        if result.get("success") is False:
            raise RuntimeError(result.get("error") or "Document processing failed")
        print(result["extraction_schema_json"])
        break
    time.sleep(delay)
    delay = min(delay * 1.15, 1)
```

See [Balanced and Accurate Extraction Modes](https://documentation.datalab.to/docs/recipes/structured-extraction/balanced-mode.md) for verification metadata and examples.

## Schema Format

Use JSON Schema format to define what you want to extract:

```json theme={null}
{
  "type": "object",
  "properties": {
    "field_name": {
      "type": "string",
      "description": "Describe what this field contains"
    },
    "numeric_field": {
      "type": "number",
      "description": "A numeric value"
    },
    "list_field": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "nested_field": {"type": "string"}
        }
      }
    }
  },
  "required": ["field_name"]
}
```

### Tips for Better Extraction

1. **Use descriptive field names** - `invoice_number` is clearer than `id`
2. **Add descriptions** - The `description` field helps the model understand context
3. **Specify types correctly** - Use `number` for numeric values, `string` for text
4. **Use arrays for repeating data** - Line items, table rows, etc.

> [!WARNING]
>
> **Common schema pitfalls:**
>
> * Using vague field names like `data` or `info` — be specific (e.g., `invoice_number`, `total_amount`)
> * Forgetting `description` fields — these help the model understand what to extract
> * Setting `type: "string"` for numeric values — use `type: "number"` for amounts, quantities, etc.
> * Deeply nested schemas — keep schemas as flat as possible for better extraction accuracy

## Response

The extracted data is returned in `extraction_schema_json`:

```json theme={null}
{
  "status": "complete",
  "success": true,
  "json": {...},
  "extraction_schema_json": "{\"invoice_number\": \"INV-2024-001\", \"total_amount\": 1500.00, ...}",
  "page_count": 2
}
```

### Citation Tracking

Each extracted field includes citations to the source blocks:

```json theme={null}
{
  "invoice_number": "INV-2024-001",
  "invoice_number_citations": ["block_123", "block_124"],
  "total_amount": 1500.00,
  "total_amount_citations": ["block_456"]
}
```

Use these block IDs with the `json` output to trace extracted values back to the source document.

### Phrase-level citations

> [!NOTE]
>
> This feature is currently in open beta. The API may change.

Set `citation_granularity` to `"phrase"` to locate each value inside its block. Each citation then becomes an object with the exact words the value came from:

```python Python SDK theme={null}
import json
from datalab_sdk import DatalabClient, ExtractOptions

client = DatalabClient()
schema = {"type": "object", "properties": {"invoice_number": {"type": "string"}}}
options = ExtractOptions(page_schema=json.dumps(schema), citation_granularity="phrase")
result = client.extract("invoice.pdf", options=options)
print(json.loads(result.extraction_schema_json)["invoice_number_citations"])
```

```bash cURL theme={null}
curl -X POST https://www.datalab.to/api/v1/extract \
  -H "X-API-Key: $DATALAB_API_KEY" \
  -F "file=@invoice.pdf" \
  -F 'page_schema={"type":"object","properties":{"invoice_number":{"type":"string"}}}' \
  -F "citation_granularity=phrase"

# Poll request_check_url from the response until status is complete or failed.
```

```python Python (requests) theme={null}
import json
import os
import time
import requests

headers = {"X-API-Key": os.environ["DATALAB_API_KEY"]}
schema = {"type": "object", "properties": {"invoice_number": {"type": "string"}}}
with open("invoice.pdf", "rb") as file:
    response = requests.post(
        "https://www.datalab.to/api/v1/extract",
        headers=headers,
        files={"file": ("invoice.pdf", file, "application/pdf")},
        data={"page_schema": json.dumps(schema), "citation_granularity": "phrase"},
    )
response.raise_for_status()
check_url = response.json()["request_check_url"]
delay = 0.3  # poll fast at first: most results are ready in seconds
while True:
    response = requests.get(check_url, headers=headers)
    response.raise_for_status()
    result = response.json()
    if result.get("success") is False or result.get("status") == "failed":
        raise RuntimeError(result.get("error", "Extraction failed"))
    if result.get("status") == "complete":
        if result.get("result_url"):
            download = requests.get(result["result_url"], timeout=60)
            download.raise_for_status()
            result = {**download.json(), **{k: v for k, v in result.items() if v is not None}}
        if result.get("success") is False:
            raise RuntimeError(result.get("error") or "Document processing failed")
        print(json.loads(result["extraction_schema_json"])["invoice_number_citations"])
        break
    time.sleep(delay)
    delay = min(delay * 1.15, 1)
```

```json theme={null}
{
  "invoice_number": "INV-2024-001",
  "invoice_number_citations": [
    {
      "block": "/page/0/Text/3",
      "page": 0,
      "text": "INV-2024-001",
      "offset": 16,
      "length": 12,
      "score": 1.0,
      "bbox": [612.0, 141.0, 798.0, 168.0]
    }
  ]
}
```

| Field | Description |
| - | - |
| `block` | The block that contains the value |
| `page` | Page index, starting at 0 |
| `text` | The words the value came from, quoted from the block |
| `offset`, `length` | Position of `text` within the block's text |
| `score` | `1.0` when the text matches up to case, spacing, number format, or date format. Lower for a close match. |
| `bbox` | Box around the words, in page pixels (the same coordinates as block `bbox` values in the `json` output). Present only when the phrase has its own box. |
| `bboxes` | One box per line, when the words span a line break |
| `value_index` | For an array of strings or numbers, the element this citation backs |

A value that cannot be located inside its block, such as a computed total or a `true`/`false` field, keeps a citation with only `block` and `page`. Phrase citations cost nothing extra. Turbo mode returns no citations.

## Schema Examples

### Financial Document

```python theme={null}
schema = {
    "type": "object",
    "properties": {
        "company_name": {"type": "string", "description": "Company name"},
        "fiscal_year": {"type": "string", "description": "Fiscal year"},
        "total_revenue": {"type": "number", "description": "Total revenue in dollars"},
        "net_income": {"type": "number", "description": "Net income in dollars"},
        "eps": {"type": "number", "description": "Earnings per share"}
    }
}
```

### Scientific Paper

```python theme={null}
schema = {
    "type": "object",
    "properties": {
        "title": {"type": "string", "description": "Paper title"},
        "authors": {
            "type": "array",
            "items": {"type": "string"},
            "description": "List of author names"
        },
        "abstract": {"type": "string", "description": "Paper abstract"},
        "keywords": {
            "type": "array",
            "items": {"type": "string"},
            "description": "Keywords or tags"
        }
    }
}
```

### Contract

```python theme={null}
schema = {
    "type": "object",
    "properties": {
        "parties": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "role": {"type": "string"}
                }
            }
        },
        "effective_date": {"type": "string", "description": "Contract start date"},
        "termination_date": {"type": "string", "description": "Contract end date"},
        "total_value": {"type": "number", "description": "Total contract value"}
    }
}
```

## Using Checkpoints

If you already converted a document with `save_checkpoint=True` using the [Convert API](https://documentation.datalab.to/docs/recipes/conversion/conversion-api-overview.md), pass the `checkpoint_id` to `ExtractOptions` to skip re-parsing. Send the checkpoint without a file or file URL. Turbo extraction requires source images and cannot reuse checkpoints.

```python theme={null}
from datalab_sdk import DatalabClient, ConvertOptions, ExtractOptions
import json

client = DatalabClient()

# Step 1: Convert and save checkpoint
convert_result = client.convert("invoice.pdf", options=ConvertOptions(save_checkpoint=True))
checkpoint_id = convert_result.checkpoint_id

# Step 2: Extract using checkpoint (no re-parsing needed)
schema = {
    "type": "object",
    "properties": {
        "invoice_number": {"type": "string", "description": "Invoice ID"},
        "total_amount": {"type": "number", "description": "Total due"}
    }
}

options = ExtractOptions(
    page_schema=json.dumps(schema),
    checkpoint_id=checkpoint_id
)
result = client.extract(options=options)
extracted = json.loads(result.extraction_schema_json)
```

The extract endpoint accepts the following parameters: `file` or `file_url`, `page_schema` or `schema_id` (one is required), `schema_version`, `extraction_mode`, `citation_granularity`, `mode`, `output_format`, `skip_cache`, `max_pages`, `page_range`, `save_checkpoint`, `checkpoint_id`, `webhook_url`, and `processing_location` (e.g. `"eu"` — routes processing and storage to EU infrastructure; requires `file_url` or a pre-uploaded `datalab://` reference instead of a multipart upload).

### Using Saved Schemas

Instead of passing `page_schema` inline, you can save schemas to Datalab and reference them by ID. This avoids repeating the schema in every request and enables versioning.

```bash theme={null}
curl -X POST https://www.datalab.to/api/v1/extract \
  -H "X-API-Key: $DATALAB_API_KEY" \
  -F "file=@invoice.pdf" \
  -F "schema_id=sch_k8Hx9mP2nQ4v"
```

Pass `schema_version` to pin to a specific schema version; omit it to always use the latest. See [Saved Schemas](https://documentation.datalab.to/docs/recipes/structured-extraction/saved-schemas.md) for full CRUD API reference.

## Confidence Scoring

> [!NOTE]
>
> **Extraction scoring is in beta.**
>
> We'd love your feedback — reach out at [support@datalab.to](mailto:support@datalab.to).
>
> Scoring is free.

Scoring runs asynchronously after cloud extraction in `fast` mode. After scoring succeeds, later polls of `request_check_url` include `_score` fields and a non-null `extraction_score_average`. Scoring can fail independently of extraction; use a bounded polling window and handle missing or null scores. Turbo, balanced, and accurate modes do not produce numeric confidence scores. No extra parameters or endpoints are needed.

Each `_score` field is a `{"score": int, "reasoning": str}` object explaining what evidence was found or missing.

### Score response format

Without scoring complete, `extraction_schema_json` contains fields and citations:

```json theme={null}
{
  "invoice_number": "INV-2024-001",
  "invoice_number_citations": ["block_123"],
  "total_amount": 1500.00,
  "total_amount_citations": ["block_456"]
}
```

Once scoring finishes, each field also gets a `_score` object, and the top-level response includes an `extraction_score_average`:

```json theme={null}
{
  "invoice_number": "INV-2024-001",
  "invoice_number_citations": ["block_123"],
  "invoice_number_score": {
    "score": 5,
    "reasoning": "Value found verbatim in the document header with a matching citation."
  },
  "total_amount": 1500.00,
  "total_amount_citations": ["block_456"],
  "total_amount_score": {
    "score": 4,
    "reasoning": "Amount found in the totals row; minor ambiguity due to a subtotal nearby."
  }
}
```

The top-level response also includes `extraction_score_average` (4.5 in this case), averaging all field scores.

**Score rubric:**

| Score | Meaning |
| - | - |
| 5 | High confidence — clear match with strong citation support |
| 4 | Good confidence — match found with minor ambiguity |
| 3 | Moderate confidence — partial match or uncertain citation |
| 2 | Low confidence — match is inferred or weakly supported |
| 1 | Very low confidence — no clear evidence found |

See [Confidence Scoring](https://documentation.datalab.to/docs/recipes/structured-extraction/confidence-scoring.md) for a full walkthrough with code examples.

## Using Forge

Create and test schemas visually in [Forge](https://www.datalab.to/app/playground):

1. Upload a sample document
2. Define fields in the visual editor
3. Switch to JSON Editor to copy the schema
4. Test extraction before deploying

## Next Steps

> [card] [Balanced and Accurate Extraction Modes](https://documentation.datalab.to/docs/recipes/structured-extraction/balanced-mode.md)
>
> Per-field verification, reasoning, and extraction status for compliance workflows

> [card] [Saved Schemas](https://documentation.datalab.to/docs/recipes/structured-extraction/saved-schemas.md)
>
> Create reusable schemas and reference them by ID — no need to repeat the schema in each request

> [card] [Confidence Scoring](https://documentation.datalab.to/docs/recipes/structured-extraction/confidence-scoring.md)
>
> Score extraction results with per-field confidence ratings

> [card] [Handling Long Documents](https://documentation.datalab.to/docs/recipes/structured-extraction/handling-long-documents.md)
>
> Strategies for extracting from 100+ page documents


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.