LeapOCR
Start Processing

#api #integration #developer #tutorial

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.

LeapOCR API Integration Guide

This comprehensive guide will walk you through integrating LeapOCR’s powerful API into your applications, from initial setup to production deployment.

Quick Start

1. Get Your API Key

First, obtain your API key from the LeapOCR dashboard:

# Your API key format
LEAPOCR_API_KEY=leap_sk_xxxxxxxxxxxxxxxxxx

2. Make Your First Request

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"

Authentication

LeapOCR uses Bearer token authentication:

// auth.js
const headers = {
  "Authorization": `Bearer ${process.env.LEAPOCR_API_KEY}`,
  "Content-Type": "application/json",
};

Core Endpoints

Document Processing

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();

Job Status

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()

Request Parameters

ParameterTypeDescription
fileFileDocument to process (PDF, PNG, JPG, TIFF)
languageStringLanguage code (e.g., ‘en’, ‘es’, ‘fr’)
output_formatStringResponse format: ‘json’, ‘text’, ‘xml’
confidence_thresholdNumberMinimum confidence score (0-100)
preserve_formattingBooleanMaintain original layout

Response Format

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
    }
  ]
}

Error Handling

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;
  }
};

Rate Limits

  • Free tier: 100 requests/hour
  • Pro tier: 1,000 requests/hour
  • Enterprise: Custom limits

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;
    }
  }
};

Best Practices

1. Async Processing for Large Files

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));
  }
};

2. Batch Processing

const processBatch = async (files) => {
  const promises = files.map(file => processDocument(file));
  return await Promise.allSettled(promises);
};

3. Caching Results

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;
};

SDK Libraries

We provide official SDKs for popular languages:

  • JavaScript/Node.js: npm install @leapocr/sdk
  • Python: pip install leapocr-python
  • PHP: composer require leapocr/php-sdk
  • Go: go get github.com/leapocr/go-sdk

Webhooks

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");
});

Testing

Use our sandbox environment for testing:

const SANDBOX_URL = "https://sandbox-api.leapocr.com";

Production Deployment

Before going live:

  1. Switch to production API key
  2. Implement proper error handling
  3. Set up monitoring and logging
  4. Configure rate limiting
  5. Test with real documents

Support

Need help with integration? Contact our developer support:


Ready to integrate LeapOCR into your application? Get your API key and start building today!

Ready to try LeapOCR for your documents?

Experience the power of AI-driven OCR technology with our free tier.

Get Started Free
Back to Blog
Share this article: