Developer Docs

Developer OCR Integration Guide: Getting Started with OCR API

OCR API integration tutorial for developers, including multi-language examples, error handling, performance optimization, and best practices.

14 min read

Why Developers Need OCR

As a developer, you may need to integrate OCR functionality in these scenarios:

  • Building document management systems that need full-text search of scanned files
  • Creating financial applications that automatically recognize invoice information
  • Developing mobile apps with photo recognition features
  • Building RPA workflows to automate paper document processing
  • Creating data collection systems to extract structured data from images

EasyOCR API Overview

API Endpoint

POST https://api.easyocr.org/ocr

Request Format

Upload image files using multipart/form-data format.

Supported Image Formats

  • JPEG / JPG
  • PNG
  • BMP
  • WebP

Response Format

{
  "success": true,
  "text": "Recognized text content",
  "confidence": 0.98
}

Multi-Language Code Examples

JavaScript / Node.js

// Using fetch API (Browser or Node.js 18+)
async function recognizeText(imageFile) {
  const formData = new FormData();
  formData.append('file', imageFile);

  const response = await fetch('https://api.easyocr.org/ocr', {
    method: 'POST',
    body: formData
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return await response.json();
}

// Node.js using axios
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

async function recognizeFile(filePath) {
  const form = new FormData();
  form.append('file', fs.createReadStream(filePath));

  const response = await axios.post('https://api.easyocr.org/ocr', form, {
    headers: form.getHeaders()
  });

  return response.data;
}

Python

import requests

def recognize_text(image_path):
    """Recognize text in image"""
    url = 'https://api.easyocr.org/ocr'
    
    with open(image_path, 'rb') as f:
        files = {'file': (image_path, f, 'image/jpeg')}
        response = requests.post(url, files=files)
    
    response.raise_for_status()
    return response.json()

# Usage example
result = recognize_text('document.jpg')
print(f"Recognition result: {result['text']}")

Go

package main

import (
    "bytes"
    "io"
    "mime/multipart"
    "net/http"
    "os"
    "path/filepath"
)

func recognizeText(imagePath string) (string, error) {
    file, err := os.Open(imagePath)
    if err != nil {
        return "", err
    }
    defer file.Close()

    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)
    
    part, err := writer.CreateFormFile("file", filepath.Base(imagePath))
    if err != nil {
        return "", err
    }
    
    _, err = io.Copy(part, file)
    if err != nil {
        return "", err
    }
    
    writer.Close()

    req, err := http.NewRequest("POST", "https://api.easyocr.org/ocr", body)
    if err != nil {
        return "", err
    }
    req.Header.Set("Content-Type", writer.FormDataContentType())

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    respBody, err := io.ReadAll(resp.Body)
    return string(respBody), err
}

PHP

<?php
function recognizeText($imagePath) {
    $url = 'https://api.easyocr.org/ocr';
    
    $curl = curl_init();
    
    $postFields = [
        'file' => new CURLFile($imagePath)
    ];
    
    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postFields
    ]);
    
    $response = curl_exec($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    
    if ($httpCode !== 200) {
        throw new Exception("HTTP Error: $httpCode");
    }
    
    return json_decode($response, true);
}

// Usage example
$result = recognizeText('document.jpg');
echo "Recognition result: " . $result['text'];
?>

Error Handling

Common Error Codes

Status CodeMeaningHandling
400Bad request formatCheck if file was uploaded correctly
413File too largeCompress image and retry
415Unsupported formatConvert to supported image format
429Too many requestsAdd delay and retry
500Server errorRetry later

Error Handling Example

async function recognizeWithRetry(imageFile, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const result = await recognizeText(imageFile);
      return result;
    } catch (error) {
      if (error.status === 429) {
        // Too many requests, wait and retry
        await new Promise(r => setTimeout(r, 1000 * (i + 1)));
        continue;
      }
      if (error.status >= 500) {
        // Server error, wait and retry
        await new Promise(r => setTimeout(r, 2000));
        continue;
      }
      // Other errors, throw directly
      throw error;
    }
  }
  throw new Error('Max retries exceeded');
}

Performance Optimization Tips

1. Image Preprocessing

  • Compress large images, recommended width not exceeding 2000px
  • Use JPEG format with quality set to 80-90%
  • Crop out areas that don't need recognition

2. Concurrency Control

  • Control concurrent request count (recommended 3-5)
  • Use request queues to manage large batch tasks
  • Add appropriate request intervals

3. Caching Strategy

  • Cache recognition results for identical images
  • Use image hash as cache key

Security Considerations

  • Don't expose sensitive API keys in frontend code
  • Validate format and size of user-uploaded images
  • Clean up temporary files promptly after processing sensitive documents
  • Consider using HTTPS to ensure transmission security

Was this article helpful?

Visit ourHelp Center

Share: