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

# Quickstart

> Get started with Datalab to convert PDFs, images, and documents into Markdown, HTML, or JSON in minutes.

## Get Your API Key

Sign up at [datalab.to/auth/sign\_up](https://www.datalab.to/auth/sign_up) — new accounts include **free credit** (no credit card required) to try the API on your own documents.

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

> [!TIP]
>
> **Want to try before writing code?** Upload a document to [Forge](https://www.datalab.to/app/playground) to see results instantly — no API key required.

## Installation

Install the Datalab SDK:

```bash theme={null}
pip install datalab-python-sdk
```

Set your API key as an environment variable:

```bash theme={null}
export DATALAB_API_KEY=your_api_key_here
```

## Convert a Document

The SDK provides a simple interface to convert documents to Markdown, HTML, JSON, or chunks.

```python Python SDK theme={null}
from pathlib import Path

from datalab_sdk import DatalabClient

client = DatalabClient()  # Uses DATALAB_API_KEY env var

# Convert PDF to markdown
result = client.convert("document.pdf")
print(result.markdown)

# Save output and images. The path is a file stem, not a folder: this writes
# output/document.md and output/document.metadata.json, with the images in output/.
Path("output").mkdir(exist_ok=True)
result.save_output("output/document")
```

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

# Poll for results (use request_check_url from response)
curl -X GET "https://www.datalab.to/api/v1/convert/{request_id}" \
  -H "X-API-Key: YOUR_API_KEY"
```

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

headers = {"X-API-Key": os.environ["DATALAB_API_KEY"]}
with requests.Session() as session:
    with open("document.pdf", "rb") as file:
        response = session.post(
            "https://www.datalab.to/api/v1/convert",
            files={"file": ("document.pdf", file, "application/pdf")},
            data={"output_format": "markdown"},
            headers=headers,
            timeout=60,
        )
    response.raise_for_status()
    check_url = response.json()["request_check_url"]

    delay = 0.3  # poll fast at first: most results are ready in seconds
    for _ in range(300):
        response = session.get(check_url, headers=headers, timeout=30)
        response.raise_for_status()
        result = response.json()
        if result.get("success") is False or result.get("status") == "failed":
            raise RuntimeError(result.get("error") or "Conversion failed")
        if result["status"] == "complete":
            if result.get("result_url"):
                # Download signed URLs without the API key header.
                download = session.get(result["result_url"], timeout=60)
                download.raise_for_status()
                result = download.json()
            if result.get("success") is False:
                raise RuntimeError(result.get("error") or "Conversion failed")
            print(result["markdown"])
            break
        time.sleep(delay)
        delay = min(delay * 1.15, 1)
    else:
        raise TimeoutError("Conversion is still running; keep the request ID")
```

> [!WARNING]
>
> **Common mistakes:**
>
> * Forgetting to set the `DATALAB_API_KEY` environment variable
> * Using `file_url` with a private/authenticated URL (must be publicly accessible)
> * Not polling for results — the initial response only contains a `request_id`, not the actual output

## Conversion Options

Control the conversion with options:

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

client = DatalabClient()

options = ConvertOptions(
    output_format="markdown",  # "markdown", "html", "json", "chunks"
    mode="balanced",           # "fast", "balanced", "accurate"
    paginate=True,             # Add page delimiters
    page_range="0-10",         # Process specific pages (0-indexed)
)

result = client.convert("document.pdf", options=options)
```

### Processing Modes

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

## Fill PDF Forms

Fill forms in PDFs or images with structured data:

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

client = DatalabClient()

options = FormFillingOptions(
    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"},
    }
)

result = client.fill("form.pdf", options=options)
result.save_output("filled_form.pdf")
```

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

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

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

with open("form.pdf", "rb") as f:
    response = requests.post(
        url,
        files={"file": ("form.pdf", f, "application/pdf")},
        data={"field_data": json.dumps(field_data)},
        headers=headers
    )
# Poll for completion using request_check_url
```

## Upload and Manage Files

Upload files to Datalab for use in pipelines:

```python theme={null}
from datalab_sdk import DatalabClient

client = DatalabClient()

# Upload files
uploaded = client.upload_files(["doc1.pdf", "doc2.pdf"])
for file in uploaded:
    print(f"{file.original_filename}: {file.reference}")
    # Output: doc1.pdf: datalab://file-abc123

# List your files
files = client.list_files(limit=50)
print(f"Total files: {files['total']}")
```

## CLI

The SDK includes a command-line interface:

```bash theme={null}
# Convert a single document
datalab convert document.pdf --format markdown

# Convert with options
datalab convert document.pdf --mode accurate --paginate

# Convert a directory
datalab convert ./documents/ --output_dir ./output/
```

## Run a Pipeline

Pipelines chain processors (convert, extract, segment) into a single reusable call. Create them in [Forge](https://www.datalab.to/app/playground) or via the SDK:

```python theme={null}
from datalab_sdk import DatalabClient

client = DatalabClient()

# Run an existing pipeline
execution = client.run_pipeline(
    "pl_abc123",              # Your pipeline ID
    file_path="document.pdf"
)

# Poll until complete
execution = client.get_pipeline_execution(
    execution.execution_id,
    max_polls=300
)

# Stop if the run didn't finish
if execution.status != "completed":
    raise RuntimeError(f"Pipeline run ended as {execution.status}")

# The extract step's fields. step_index counts from 0: convert is 0, extract is 1.
# The step result also holds the full markdown and block tree, so print only the fields.
result = client.get_step_result(execution.execution_id, step_index=1)
print(result["extraction_schema_json"])
```

See [Pipelines](https://docs.datalab.to/docs/recipes/pipelines/pipeline-overview.md) for creating, versioning, and running pipelines.

## Async Support

For high-throughput applications, use the async client:

```python theme={null}
import asyncio
from datalab_sdk import AsyncDatalabClient

async def convert_documents():
    async with AsyncDatalabClient() as client:
        result = await client.convert("document.pdf")
        print(result.markdown)

asyncio.run(convert_documents())
```

## Next Steps

> [card] [SDK Reference](https://docs.datalab.to/docs/welcome/sdk.md)
>
> Full Python SDK documentation with typed clients and async support.

> [card] [API Reference](https://docs.datalab.to/docs/welcome/api.md)
>
> REST API reference for document conversion, form filling, and file management.

> [card] [Pipelines](https://docs.datalab.to/docs/recipes/pipelines/pipeline-overview.md)
>
> Chain processors into versioned, reusable pipelines.

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


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