LeapOCR API Integration Guide: From Setup to Production
Complete guide to integrating LeapOCR API into your applications. Learn authentication, endpoints, error handling, and best practices for production deployment.
Complete guide to integrating LeapOCR API into your applications. Learn authentication, endpoints, error handling, and best practices for production deployment.
This comprehensive guide will walk you through integrating LeapOCR’s powerful API into your applications, from initial setup to production deployment.
First, obtain your API key from the LeapOCR dashboard:
# Your API key format
LEAPOCR_API_KEY=leap_sk_xxxxxxxxxxxxxxxxxx
Here’s a simple example using cURL:
# example-request.sh
curl -X POST https://api.leapocr.com/v1/process \
-H "Authorization: Bearer $LEAPOCR_API_KEY" \
-H "Content-Type: multipart/form-data" \
-F "file=@document.pdf" \
-F "output_format=json"
LeapOCR uses Bearer token authentication:
// auth.js
const headers = {
"Authorization": `Bearer ${process.env.LEAPOCR_API_KEY}`,
"Content-Type": "application/json",
};
POST / v1 / process;
Process a document and extract text:
// process-document.js
const formData = new FormData();
formData.append("file", fileInput.files[0]);
formData.append("language", "en");
formData.append("output_format", "json");
const response = await fetch("https://api.leapocr.com/v1/process", {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
},
body: formData,
});
const result = await response.json();
GET / v1 / jobs / { job_id };
Check processing status for async operations:
// status-checker.js
const checkStatus = async (jobId) => {
const response = await fetch(`https://api.leapocr.com/v1/jobs/${jobId}`, {
headers: {
"Authorization": `Bearer ${apiKey}`,
},
});
return await response.json();
};
Here’s a Python implementation:
# leapocr_client.py
import requests
import os
class LeapOCRClient:
def __init__(self, api_key=None):
self.api_key = api_key or os.getenv('LEAPOCR_API_KEY')
self.base_url = 'https://api.leapocr.com/v1'
def process_document(self, file_path, language='en'):
with open(file_path, 'rb') as f:
files = {'file': f}
data = {
'language': language,
'output_format': 'json'
}
headers = {'Authorization': f'Bearer {self.api_key}'}
response = requests.post(
f'{self.base_url}/process',
files=files,
data=data,
headers=headers
)
return response.json()
Parameter | Type | Description |
---|---|---|
file | File | Document to process (PDF, PNG, JPG, TIFF) |
language | String | Language code (e.g., ‘en’, ‘es’, ‘fr’) |
output_format | String | Response format: ‘json’, ‘text’, ‘xml’ |
confidence_threshold | Number | Minimum confidence score (0-100) |
preserve_formatting | Boolean | Maintain original layout |
Successful responses return:
{
"id": "job_abc123",
"status": "completed",
"confidence": 0.95,
"text": "Extracted text content...",
"metadata": {
"pages": 1,
"language": "en",
"processing_time": 1.23
},
"bounding_boxes": [
{
"text": "Hello World",
"x": 100,
"y": 200,
"width": 150,
"height": 30,
"confidence": 0.98
}
]
}
Handle common error scenarios:
const processDocument = async (file) => {
try {
const response = await fetch("https://api.leapocr.com/v1/process", {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`,
},
body: formData,
});
if (!response.ok) {
const error = await response.json();
throw new Error(`API Error: ${error.message}`);
}
return await response.json();
} catch (error) {
console.error("Processing failed:", error);
throw error;
}
};
Include rate limit handling:
const withRetry = async (fn, maxRetries = 3) => {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (error.status === 429 && i < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
continue;
}
throw error;
}
}
};
const processLargeFile = async (file) => {
// Submit for async processing
const submitResponse = await fetch("/v1/process/async", {
method: "POST",
headers: { "Authorization": `Bearer ${apiKey}` },
body: formData,
});
const { job_id } = await submitResponse.json();
// Poll for completion
while (true) {
const status = await checkStatus(job_id);
if (status.status === "completed") {
return status.result;
} else if (status.status === "failed") {
throw new Error(status.error);
}
await new Promise(resolve => setTimeout(resolve, 2000));
}
};
const processBatch = async (files) => {
const promises = files.map(file => processDocument(file));
return await Promise.allSettled(promises);
};
const cache = new Map();
const processWithCache = async (fileHash, file) => {
if (cache.has(fileHash)) {
return cache.get(fileHash);
}
const result = await processDocument(file);
cache.set(fileHash, result);
return result;
};
We provide official SDKs for popular languages:
npm install @leapocr/sdk
pip install leapocr-python
composer require leapocr/php-sdk
go get github.com/leapocr/go-sdk
Configure webhooks for real-time notifications:
app.post("/webhooks/leapocr", (req, res) => {
const { job_id, status, result } = req.body;
if (status === "completed") {
// Handle successful processing
console.log("Job completed:", job_id);
processResult(result);
}
res.status(200).send("OK");
});
Use our sandbox environment for testing:
const SANDBOX_URL = "https://sandbox-api.leapocr.com";
Before going live:
Need help with integration? Contact our developer support:
Ready to integrate LeapOCR into your application? Get your API key and start building today!
Experience the power of AI-driven OCR technology with our free tier.
Get Started Free