> ## 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.

# API Overview

> REST API reference for document conversion, form filling, and file management.

Datalab provides REST APIs for document conversion, structured extraction, form filling, and file management. All APIs use the same authentication and follow similar patterns.

> [!NOTE]
>
> For the simplest integration, use the [Python SDK](https://documentation.datalab.to/docs/welcome/sdk.md). The SDK handles authentication, polling, and provides typed responses.

## Authentication

All requests require an API key in the `X-API-Key` header:

```bash theme={null}
curl -X POST https://www.datalab.to/api/v1/convert \
  -H "X-API-Key: YOUR_API_KEY" \
  -F "file=@document.pdf"
```

Get your API key from the [API Keys dashboard](https://www.datalab.to/app/keys).

## Request Pattern

All processing endpoints follow this pattern:

1. **Submit** a document for processing (returns immediately with a `request_id`)
2. **Poll** the status endpoint until processing completes
3. **Retrieve** results from the completed response

### Submit Request

```bash theme={null}
POST /api/v1/{endpoint}
```

Response:

```json theme={null}
{
  "success": true,
  "request_id": "abc123",
  "request_check_url": "https://www.datalab.to/api/v1/{endpoint}/abc123"
}
```

### Poll for Results

```bash theme={null}
GET /api/v1/{endpoint}/{request_id}
```

Response while processing:

```json theme={null}
{
  "status": "processing",
  "progress_percent": 37
}
```

Response when complete:

```json theme={null}
{
  "status": "complete",
  "success": true,
  "progress_percent": 100,
  ...results...
}
```

### Progress percentages

Hosted API polling responses can include `progress_percent`, an integer from 0 to 100 estimating overall work completed. Use it to display a progress bar.

* The percentage can pause or jump. It is not an estimate of time remaining.
* Treat a missing or `null` value as unavailable and show an indeterminate indicator.
* A successful result reports 100 when it is ready to retrieve. A failed request may retain its last percentage or have no percentage.
* Keep checking `status` and `success` to decide whether processing finished. A percentage is not a completion signal.

Polling about once per second is sufficient for progress displays. Consecutive polls may return the same percentage.

With Python SDK 0.8.0 or later, pass `on_progress` to document-processing helpers such as `convert()` and `extract()` to receive increasing integer percentages while they poll. Missing values and duplicates are skipped. Async clients also accept async callbacks. Callbacks run inline; keep them short. Callback exceptions stop local polling and propagate to your call, without cancelling the server request. Existing polling intervals and request counts are unchanged. Earlier SDK versions can use REST polling.

```python Python SDK (automatic polling) theme={null}
from datalab_sdk import DatalabClient

# Requires datalab-python-sdk >= 0.8.0.
client = DatalabClient()
result = client.convert(
    "document.pdf",
    on_progress=lambda percent: print(f"Processing: {percent}%"),
)
print(result.success)
```

```bash cURL theme={null}
# Set REQUEST_CHECK_URL to the URL returned when you submitted the document.
curl "$REQUEST_CHECK_URL" \
  -H "X-API-Key: $DATALAB_API_KEY"
```

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

# Use request_check_url from the submission response.
check_url = os.environ["REQUEST_CHECK_URL"]
headers = {"X-API-Key": os.environ["DATALAB_API_KEY"]}

delay = 0.3  # poll fast at first: most results are ready in seconds
while True:
    response = requests.get(check_url, headers=headers, timeout=30)
    response.raise_for_status()
    result = response.json()
    if result.get("success") is False or result["status"] == "failed":
        raise RuntimeError(result.get("error") or "Processing failed")
    if result["status"] == "complete":
        break
    percent = result.get("progress_percent")
    if percent is not None:
        print(f"{percent}%")
    time.sleep(delay)
    delay = min(delay * 1.15, 1)
```

> [!WARNING]
>
> Results are deleted from Datalab servers about one day after processing completes, or sooner if you delete them with `DELETE /api/v1/results/{request_id}`. Retrieve your results promptly.

## Document Conversion

Convert documents to Markdown, HTML, JSON, or chunks.

**Endpoint:** `POST /api/v1/convert`

### Request

```python theme={null}
import requests

url = "https://www.datalab.to/api/v1/convert"
headers = {"X-API-Key": "YOUR_API_KEY"}

with open("document.pdf", "rb") as f:
    response = requests.post(
        url,
        files={"file": ("document.pdf", f, "application/pdf")},
        data={
            "output_format": "markdown",
            "mode": "balanced",
        },
        headers=headers
    )

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

### Parameters

| Parameter | Type | Default | Description |
| - | - | - | - |
| `file` | file | - | Document file (multipart upload) |
| `file_url` | string | - | URL to document (alternative to file upload) |
| `output_format` | string | `markdown` | Output format: `markdown`, `html`, `json`, `chunks` |
| `mode` | string | `balanced` | Processing mode: `lite`, `fast`, `balanced`, `accurate`. SDK and CLI default to `fast`. |
| `max_pages` | int | - | Maximum pages to process |
| `page_range` | string | - | Specific pages (e.g., `"0-5,10"`, 0-indexed). For spreadsheets, filters by sheet index. |
| `paginate` | bool | `false` | Add page delimiters to output |
| `skip_cache` | bool | `false` | Skip cached results |
| `disable_image_extraction` | bool | `false` | Don't extract images |
| `disable_image_captions` | bool | `false` | Don't generate image captions |
| `save_checkpoint` | bool | `false` | Save checkpoint for reuse |
| `word_bboxes` | bool | `false` | Predict per-word bounding boxes. Each word is inlined as `<span data-bbox="..." data-confidence="...">` in HTML output. Billed at \$0.30/1K pages. |
| `extras` | string | - | Comma-separated: `track_changes`, `chart_understanding`, `extract_links`, `table_cell_bboxes`, `list_item_bboxes`, `infographic`, `new_block_types`. (`table_row_bboxes` is deprecated — use `table_cell_bboxes`.) |
| `add_block_ids` | bool | `false` | Add block IDs to HTML for citations |
| `include_markdown_in_chunks` | bool | `false` | Include markdown content in chunks output |
| `token_efficient_markdown` | bool | `false` | Optimize markdown for LLM token efficiency |
| `fence_synthetic_captions` | bool | `false` | Wrap synthetic image captions in HTML comments |
| `additional_config` | string | - | JSON with extra config options, such as `keep_pageheader_in_output` and `keep_pagefooter_in_output` (page headers and footers are left out of `markdown` and `html` by default, and always returned in `json` and `chunks`) |
| `webhook_url` | string | - | Override webhook URL for this request |

### Processing Modes

| Mode | Description |
| - | - |
| `fast` | Lowest latency, good for simple documents (default) |
| `balanced` | Balance of speed and accuracy |
| `accurate` | Highest accuracy, best for complex layouts |

### Response

Poll `request_check_url` until `status` is `complete`, checking `success` and `error` on each response. Completed responses can contain the output inline or a signed `result_url` for downloading the result JSON. Download signed URLs without an API key header. See the complete [Python requests example](https://documentation.datalab.to/docs/welcome/quickstart.md#convert-a-document) for bounded polling, HTTP error handling, and downloading results.

Response fields:

| Field | Type | Description |
| - | - | - |
| `status` | string | `processing`, `complete`, or `failed` |
| `success` | bool | Whether conversion succeeded |
| `result_url` | string | Signed download URL when results are not inline |
| `progress_percent` | int or null | Optional overall work estimate, 0–100. May be absent; not an ETA. See [progress percentages](#progress-percentages). |
| `markdown` | string | Markdown output (if format is markdown) |
| `html` | string | HTML output (if format is html) |
| `json` | object | JSON output (if format is json) |
| `chunks` | object | Chunked output (if format is chunks) |
| `images` | object | Extracted images as `{filename: base64}` |
| `metadata` | object | Document metadata |
| `page_count` | int | Number of pages processed |
| `parse_quality_score` | float | Quality score (0-5) |
| `cost_breakdown` | object | Cost in cents |
| `error` | string | Error message if failed |

> [!NOTE]
>
> For structured data extraction, see the [Extract endpoint](#structured-extraction). For document segmentation, see the [Segment endpoint](#document-segmentation).

## Structured Extraction

Extract structured data from documents using a JSON schema.

**Endpoint:** `POST /api/v1/extract`

### Request

```python theme={null}
import requests
import json

headers = {"X-API-Key": "YOUR_API_KEY"}

schema = {
    "invoice_number": {"type": "string", "description": "Invoice ID"},
    "total": {"type": "number", "description": "Total amount"},
    "line_items": {
        "type": "array",
        "items": {
            "type": "object",
            "properties": {
                "description": {"type": "string"},
                "amount": {"type": "number"}
            }
        }
    }
}

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

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

### Parameters

| Parameter | Type | Default | Description |
| - | - | - | - |
| `file` | file | - | Document file (multipart upload) |
| `file_url` | string | - | URL to document (alternative to file upload) |
| `page_schema` | string | - | JSON schema defining the data to extract. Required unless `schema_id` is provided. |
| `schema_id` | string | - | ID of a [saved extraction schema](https://documentation.datalab.to/docs/recipes/structured-extraction/saved-schemas.md) (e.g. `sch_k8Hx9mP2nQ4v`). Mutually exclusive with `page_schema`. |
| `schema_version` | int | - | Version of the saved schema to use. Only valid with `schema_id`; defaults to the latest version. |
| `checkpoint_id` | string | - | Checkpoint ID from a previous `/convert` call (with `save_checkpoint=true`). Skips re-parsing. |
| `mode` | string | `balanced` | Processing mode: `lite`, `fast`, `balanced`, `accurate`. SDK and CLI default to `fast`. |
| `output_format` | string | `markdown` | Output format: `markdown`, `html`, `json`, `chunks` |
| `max_pages` | int | - | Maximum pages to process |
| `page_range` | string | - | Specific pages (e.g., `"0-5,10"`, 0-indexed). For spreadsheets, filters by sheet index. |
| `save_checkpoint` | bool | `false` | Save a checkpoint after processing for reuse with subsequent calls |
| `webhook_url` | string | - | Override webhook URL for this request |

The extracted data is returned in `extraction_schema_json` in the poll response.

See [Structured Extraction](https://documentation.datalab.to/docs/recipes/structured-extraction/api-overview.md) for detailed examples.

## Document Segmentation

Segment documents into structured sections using a JSON schema.

**Endpoint:** `POST /api/v1/segment`

### Parameters

| Parameter | Type | Default | Description |
| - | - | - | - |
| `file` | file | - | Document file (multipart upload) |
| `file_url` | string | - | URL to document (alternative to file upload) |
| `segmentation_schema` | string | **required** | JSON schema defining the segments to extract |
| `checkpoint_id` | string | - | Checkpoint ID from a previous `/convert` call (with `save_checkpoint=true`). Skips re-parsing. |
| `mode` | string | `balanced` | Processing mode: `lite`, `fast`, `balanced`, `accurate`. SDK and CLI default to `fast`. |

See [Document Segmentation](https://documentation.datalab.to/docs/recipes/document-segmentation/auto-segmentation.md) for detailed examples.

## Track Changes

Extract tracked changes (insertions and deletions) from DOCX files, PDFs, and images.

**Endpoint:** `POST /api/v1/track-changes`

DOCX files use exact pandoc-based change extraction. PDFs and images are processed by a vision model.

```python theme={null}
response = requests.post(
    "https://www.datalab.to/api/v1/track-changes",
    files={"file": ("contract.pdf", open("contract.pdf", "rb"), "application/pdf")},
    headers=headers
)
```

See [Track Changes](https://documentation.datalab.to/docs/recipes/extract-redlines-and-comments/track-changes-from-word-documents.md) for detailed examples.

## Custom Processor (Agent, Beta)

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

Run an existing published processor on a document. The published processor determines the task and output format.

**Endpoint:** `POST /api/v1/agent`

> [!WARNING]
>
> `POST /api/v1/custom-processor` and `POST /api/v1/custom-pipeline` are deprecated. They keep working until a removal date we will announce ahead of time. Migrate to `POST /api/v1/agent`, passing `processor=cp_XXXXX` instead of `pipeline_id=cp_XXXXX`. See the [migration guide](https://documentation.datalab.to/platform/migration.md).

### Parameters

| Parameter | Type | Default | Description |
| - | - | - | - |
| `file` | file | - | Document file (multipart upload) |
| `file_url` | string | - | URL to document |
| `processor` | string | **required** | Published processor ID (`cp_XXXXX`); pin a version with `cp_XXXXX@2.0`, or omit it for the newest published version |
| `mode` | string | `balanced` | Run mode: `fast` returns sooner at a lower cost; `balanced` checks and corrects the output in more depth |
| `verification_effort` | string | `fast` | Verification effort: `fast`, `balanced`, `accurate` |
| `return_images` | bool | `false` | Return the run images inline |
| `skip_cache` | bool | `false` | Run again instead of using cached output |
| `processing_location` | string | - | Residency region, such as `us` or `eu`; use `file_url` when set |
| `webhook_url` | string | - | URL to POST when complete |

## Form Filling

Fill forms in PDFs and images.

**Endpoint:** `POST /api/v1/fill`

### Request

```python theme={null}
import json

field_data = {
    "full_name": {"value": "John Doe", "description": "Full legal name"},
    "date": {"value": "2024-01-15", "description": "Today's date"},
    "signature": {"value": "John Doe", "description": "Signature field"}
}

response = requests.post(
    "https://www.datalab.to/api/v1/fill",
    files={"file": ("form.pdf", open("form.pdf", "rb"), "application/pdf")},
    data={
        "field_data": json.dumps(field_data),
    },
    headers=headers
)
```

### Parameters

| Parameter | Type | Default | Description |
| - | - | - | - |
| `file` | file | - | Form file (PDF or image) |
| `file_url` | string | - | URL to form |
| `field_data` | string | - | JSON mapping field names to values |
| `context` | string | - | Additional context for field matching |
| `confidence_threshold` | float | `0.5` | No effect. The API accepts and ignores it, so existing requests keep working. |
| `page_range` | string | - | Specific pages to process |
| `skip_cache` | bool | `false` | Skip cached results |

### Field Data Format

```json theme={null}
{
  "field_key": {
    "value": "The value to fill",
    "description": "Description to help match the field"
  }
}
```

### Response

| Field | Type | Description |
| - | - | - |
| `status` | string | Processing status |
| `success` | bool | Whether filling succeeded |
| `output_format` | string | `pdf` or `png` |
| `output_base64` | string | Base64-encoded filled form |
| `fields_filled` | array | Successfully filled field names |
| `fields_not_found` | array | Unmatched field names |
| `page_count` | int | Pages processed |
| `cost_breakdown` | object | Cost details |

See [Form Filling](https://documentation.datalab.to/docs/recipes/form-filling/form-filling-api-overview.md) for more examples.

## File Management

Upload and manage files for use in pipelines.

### Upload File

**Step 1:** Request an upload URL

```bash theme={null}
POST /api/v1/files/upload
Content-Type: application/json

{
  "filename": "document.pdf",
  "content_type": "application/pdf"
}
```

Response:

```json theme={null}
{
  "file_id": 123,
  "upload_url": "https://...",
  "reference": "datalab://file-abc123"
}
```

**Step 2:** Upload directly to the presigned URL

```bash theme={null}
PUT {upload_url}
Content-Type: application/pdf

<file contents>
```

**Step 3:** Confirm upload

```bash theme={null}
GET /api/v1/files/{file_id}/confirm
```

### List Files

```bash theme={null}
GET /api/v1/files?limit=50&offset=0
```

### Get File Metadata

```bash theme={null}
GET /api/v1/files/{file_id}
```

### Get Download URL

```bash theme={null}
GET /api/v1/files/{file_id}/download?expires_in=3600
```

### Delete File

```bash theme={null}
DELETE /api/v1/files/{file_id}
```

See [File Management](https://documentation.datalab.to/docs/recipes/file-management/file-upload-api.md) for detailed examples.

## Create Document

Generate DOCX files from markdown with track changes support:

```bash theme={null}
POST /api/v1/create-document
Content-Type: application/json

{
  "markdown": "# Title\n\nThis is <ins data-revision-author=\"Editor\">newly added</ins> text.",
  "output_format": "docx"
}
```

See [Create Document](https://documentation.datalab.to/docs/recipes/create-document/create-document-api-overview.md) for detailed examples.

## Webhooks

Configure webhooks to receive notifications when processing completes instead of polling.

Set a default webhook URL in your [webhook settings](https://www.datalab.to/app/webhooks), or override per-request with the `webhook_url` parameter.

See [Webhooks](https://documentation.datalab.to/platform/webhooks.md) for configuration details.

## Rate Limits

Default rate limits apply per API key. If you exceed limits, you'll receive a `429` response.

See [Rate Limits](https://documentation.datalab.to/docs/common/limits.md) for details and how to request higher limits.

## Next Steps

> [card] [SDK Reference](https://documentation.datalab.to/docs/welcome/sdk.md)
>
> Use the Python SDK for a simpler integration with typed responses.

> [card] [Webhooks](https://documentation.datalab.to/platform/webhooks.md)
>
> Receive notifications when processing completes instead of polling.

> [card] [API Limits](https://documentation.datalab.to/docs/common/limits.md)
>
> Understand file size limits, page limits, and rate limiting.

> [card] [Document Conversion](https://documentation.datalab.to/docs/recipes/conversion/conversion-api-overview.md)
>
> Detailed guide to converting documents to Markdown, HTML, or JSON.


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