Convert Documents
Convert documents to structured JSON with Docutray's AI-powered OCR — pass a file and a document-type code, with multi-language SDK and REST examples.
The Convert operation extracts structured data from documents using AI-powered OCR. You provide a document (image or PDF) and a document type code, and DocuTray returns the extracted fields as JSON according to the document type's schema.
Quick Start
from pathlib import Path
from docutray import Client
client = Client(api_key="YOUR_API_KEY")
result = client.convert.run(
file=Path("invoice.pdf"),
document_type_code="invoice"
)
print(result.data)Response
# result is a ConversionResult
print(result.data)
# {
# "invoice_number": "F-2024-001",
# "issue_date": "2024-01-15",
# "vendor_name": "Acme Corporation",
# "subtotal": 1000,
# "tax": 160,
# "total": 1160
# }Validation Results
The response includes validation: the result of checking the extracted data
against the document type's JSON Schema and validation rules.
The same field appears in the async status once the
conversion reaches SUCCESS, and in the
CONVERSION_COMPLETED webhook.
Validation is informational: a conversion with invalid data still succeeds and
returns its data. validation takes one of three forms:
// Validation ran: errors and warnings are lists of issues
{
"valid": false,
"errors": [
{
"field": "total",
"value": 1260,
"rule": "equalsWithPrecision",
"message": "El campo 'total' debe ser igual a '1160' con 2 decimales de precisión, pero es '1260'",
"code": "VALIDATION_ERROR",
"severity": "error",
"source": "rule"
}
],
"warnings": []
}
// Validation was skipped: the document type has no JSON Schema and no rules
null
// Validation could not be completed, or no validation record exists;
// no internal details are exposed
{ "status": "error" }See reading the results for every issue property and code.
Async Conversion
For large documents or batch processing, use async conversion. The document is processed in the background and you can poll for the result.
# Start async conversion
status = client.convert.run_async(
file=Path("large_document.pdf"),
document_type_code="invoice"
)
print(f"Conversion ID: {status.conversion_id}")
print(f"Status: {status.status}") # ENQUEUED
# Wait for completion (polls automatically)
result = status.wait()
if result.is_success():
print(result.data)
elif result.is_error():
print(f"Error: {result.error}")Checking Status Manually
You can also check the status of an async conversion by its ID:
status = client.convert.get_status("cm5vm9hx30001m5cgh0p9v8qa")
if status.is_success():
print(status.data)A successful conversion returns its data and its validation result:
{
"conversion_id": "cm5vm9hx30001m5cgh0p9v8qa",
"status": "SUCCESS",
"request_timestamp": "2024-01-15T10:30:00.000Z",
"response_timestamp": "2024-01-15T10:30:15.000Z",
"document_type_code": "invoice",
"original_filename": "large_document.pdf",
"document_metadata": null,
"validation": {
"valid": true,
"errors": [],
"warnings": []
},
"data": {
"invoice_number": "F-2024-001",
"total": 1160
}
}validation is only present when the status is SUCCESS.
Input Methods
DocuTray supports three methods for providing documents.
File Upload
Upload a file directly from disk or memory.
from pathlib import Path
# From a file path
result = client.convert.run(
file=Path("invoice.pdf"),
document_type_code="invoice"
)
# From bytes
with open("invoice.pdf", "rb") as f:
result = client.convert.run(
file=f.read(),
document_type_code="invoice",
content_type="application/pdf"
)
# From a file object
with open("invoice.pdf", "rb") as f:
result = client.convert.run(
file=f,
document_type_code="invoice"
)URL
Provide a publicly accessible URL to the document. DocuTray will download and process it.
result = client.convert.run(
url="https://example.com/invoice.pdf",
document_type_code="invoice"
)Base64
Send a base64-encoded document in the request body.
import base64
with open("invoice.pdf", "rb") as f:
encoded = base64.b64encode(f.read()).decode()
result = client.convert.run(
file_base64=encoded,
document_type_code="invoice",
content_type="application/pdf"
)Document Metadata
You can attach custom metadata to any conversion. This metadata is returned in status responses and webhooks, useful for tracking your internal references.
result = client.convert.run(
file=Path("invoice.pdf"),
document_type_code="invoice",
document_metadata={"customer_id": "cust_123", "batch": "2024-Q1"}
)Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
document_type_code | string | Yes | Code identifying the document type schema to use |
file | File | No | File to process (path, bytes, or file object) |
url | string | No | Public URL of the document to download and process |
file_base64 / base64 | string | No | Base64-encoded document content |
content_type | string | No | MIME type of the document (auto-detected if not provided) |
document_metadata | object | No | Custom metadata to attach to the conversion |
You must provide exactly one of file, url, or file_base64/base64.
Supported file formats: JPEG, PNG, GIF, BMP, WebP, PDF (up to 100MB)
Error Handling
from docutray import (
AuthenticationError,
BadRequestError,
RateLimitError,
NotFoundError,
DocuTrayError,
)
try:
result = client.convert.run(
file=Path("invoice.pdf"),
document_type_code="invoice"
)
except AuthenticationError:
print("Invalid API key")
except BadRequestError as e:
print(f"Invalid request: {e.message}")
except RateLimitError as e:
print(f"Rate limited. Retry after {e.retry_after}s")
except NotFoundError:
print("Document type not found")
except DocuTrayError as e:
print(f"Error: {e.message}")Complete Code
End-to-end example that converts a document with error handling and result processing.
from pathlib import Path
from docutray import Client, AuthenticationError, RateLimitError, DocuTrayError
client = Client(api_key="YOUR_API_KEY")
try:
# Sync conversion for small documents
result = client.convert.run(
file=Path("invoice.pdf"),
document_type_code="invoice",
document_metadata={"source": "email", "batch": "2024-Q1"}
)
# Access extracted data
data = result.data
print(f"Invoice: {data.get('invoice_number')}")
print(f"Total: ${data.get('total')}")
except AuthenticationError:
print("Check your API key")
except RateLimitError as e:
print(f"Rate limited. Retry after {e.retry_after} seconds")
except DocuTrayError as e:
print(f"Conversion failed: {e.message}")
finally:
client.close()SDK Reference
For detailed class and method documentation:
Operations
Docutray operations reference — convert, identify, knowledge bases, and steps: the core document-processing building blocks with multi-language examples.
Identify Documents
Auto-detect a document's type with Docutray AI classification — pass a file and candidate types to get the best match, with SDK and REST examples.