Getting started overview

This guide outlines the process for integrating with Hirak OCR, focusing on initial setup and making a successful API call. Hirak OCR provides an API for converting images and PDFs into structured data through Optical Character Recognition (Hirak OCR documentation). The platform supports various document types, including invoices and receipts, and offers SDKs for common programming languages to simplify the integration process.

To begin, users typically create an account, generate API credentials, and then use these credentials to authenticate requests to the Hirak OCR API. The primary methods for interaction include direct HTTP requests or utilizing one of the provided Software Development Kits (SDKs). Hirak OCR offers SDKs for Python, Node.js, and Java (Hirak OCR SDK details).

The following table summarizes the initial steps:

Step What to do Where
1. Create Account Register on the Hirak OCR platform. Hirak OCR homepage
2. Get API Keys Locate and copy your API key from the dashboard. Hirak OCR dashboard (after login)
3. Install SDK (Optional) Install the relevant SDK for your preferred language (e.g., Python, Node.js). Hirak OCR SDK documentation
4. Make First Request Send an image or PDF to the OCR API endpoint using your API key. Hirak OCR API reference

Create an account and get keys

Access to the Hirak OCR API requires an account and associated API keys for authentication. Follow these steps to set up your account and retrieve your credentials:

  1. Visit the Hirak OCR Website: Navigate to the Hirak OCR homepage.
  2. Sign Up: Look for a "Sign Up" or "Get Started Free" button. Complete the registration form with your email address and a secure password. Hirak OCR offers a free tier that includes 500 pages per month (Hirak OCR pricing details), which allows for initial testing and development without immediate cost.
  3. Verify Email: You may receive an email verification link. Click the link to activate your account.
  4. Log In to Dashboard: Once your account is active, log in to the Hirak OCR developer dashboard.
  5. Locate API Keys: Within the dashboard, there is typically a section labeled "API Keys," "Credentials," or "Settings." Navigate to this section to find your unique API key. API keys are essential for authenticating requests and should be kept confidential to prevent unauthorized access to your account and usage (OAuth 2.0 security principles).
  6. Copy API Key: Copy your API key. This key will be included in the headers or body of your API requests to authenticate them.

The API key acts as a bearer token or a header value, depending on the specific endpoint and authentication method documented by Hirak OCR (Hirak OCR authentication guide).

Your first request

After obtaining your API key, you can make your first request to the Hirak OCR API. This example demonstrates how to perform a basic OCR operation using the Python SDK. Node.js is also a primary language for examples if Python is not preferred.

Prerequisites

  • Python installed: Ensure you have Python 3.x installed on your system.
  • Hirak OCR Python SDK: Install the SDK using pip: pip install hirak-ocr-sdk.
  • An image file: Have a sample image (e.g., document.png or invoice.jpg) ready for OCR.

Python Example

This Python code snippet demonstrates how to upload an image and retrieve its extracted text:


import os
from hirak_ocr_sdk import HirakOCRClient

# Replace with your actual API key
API_KEY = "YOUR_HIRAK_OCR_API_KEY"

# Initialize the client
client = HirakOCRClient(api_key=API_KEY)

# Path to your document image
document_path = "./path/to/your/document.png"

try:
    with open(document_path, "rb") as f:
        # Upload the document for OCR processing
        print(f"Uploading {document_path} for OCR...")
        response = client.process_document(file=f, document_type="general")

        # Check if the request was successful
        if response.get("status") == "success":
            extracted_text = response.get("data", {}).get("text_content")
            if extracted_text:
                print("OCR successful. Extracted text:")
                print(extracted_text)
            else:
                print("OCR successful, but no text content found.")
        else:
            error_message = response.get("message", "Unknown error")
            print(f"OCR failed: {error_message}")
            print(f"Full response: {response}")

except FileNotFoundError:
    print(f"Error: Document not found at {document_path}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")
    

Node.js Example

For Node.js developers, the process is similar. First, install the SDK:


npm install hirak-ocr-sdk
    

Then, use the following JavaScript code:


const fs = require('fs');
const { HirakOCRClient } = require('hirak-ocr-sdk');

// Replace with your actual API key
const API_KEY = "YOUR_HIRAK_OCR_API_KEY";

// Initialize the client
const client = new HirakOCRClient(API_KEY);

// Path to your document image
const documentPath = "./path/to/your/document.png";

async function processDocument() {
  try {
    const fileStream = fs.createReadStream(documentPath);

    // Upload the document for OCR processing
    console.log(`Uploading ${documentPath} for OCR...`);
    const response = await client.processDocument({
      file: fileStream,
      documentType: "general",
    });

    // Check if the request was successful
    if (response.status === "success") {
      const extractedText = response.data?.text_content;
      if (extractedText) {
        console.log("OCR successful. Extracted text:");
        console.log(extractedText);
      } else {
        console.log("OCR successful, but no text content found.");
      }
    } else {
      const errorMessage = response.message || "Unknown error";
      console.error(`OCR failed: ${errorMessage}`);
      console.error(`Full response:`, response);
    }
  } catch (error) {
    if (error.code === 'ENOENT') {
      console.error(`Error: Document not found at ${documentPath}`);
    } else {
      console.error(`An unexpected error occurred:`, error);
    }
  }
}

processDocument();
    

Ensure that YOUR_HIRAK_OCR_API_KEY is replaced with the key obtained from your Hirak OCR dashboard. The document_type parameter can be adjusted based on the specific type of document you are processing, such as invoice or receipt, to leverage specialized parsing models (Hirak OCR document types).

Common next steps

After successfully making your first OCR request, consider these common next steps to further integrate Hirak OCR into your application:

  • Explore Document Types: Experiment with different document_type parameters (e.g., invoice, receipt, passport) to see how Hirak OCR's specialized models improve extraction accuracy for specific document categories (Hirak OCR specialized document processing).
  • Handle Structured Data: Beyond raw text, Hirak OCR often returns structured data in JSON format for certain document types. Parse this JSON to extract specific fields like invoice numbers, dates, or line items (Hirak OCR response structure).
  • Error Handling and Retries: Implement robust error handling, including retries for transient network issues or API rate limits. Refer to best practices for API integration and error management (AWS EC2 error handling guide).
  • Secure API Key Management: Avoid hardcoding API keys in your application code. Use environment variables or a secure secrets management solution to protect your credentials.
  • Webhooks for Asynchronous Processing: For larger documents or batch processing, consider using Hirak OCR's webhook functionality for asynchronous results. This prevents your application from waiting for long-running OCR tasks to complete (Hirak OCR webhook integration).
  • Monitor Usage: Regularly check your usage statistics in the Hirak OCR dashboard to stay within your free tier limits or monitor your paid plan consumption.
  • Explore Advanced Features: Investigate features like custom extraction models or pre-processing options if your use case requires them.

Troubleshooting the first call

Encountering issues during your first API call is common. Here are some troubleshooting steps:

  • Verify API Key: Double-check that the API key in your code exactly matches the one from your Hirak OCR dashboard. Ensure there are no leading or trailing spaces.
  • Check Document Path: Confirm that the document_path variable points to the correct location of your image or PDF file and that the file exists and is readable.
  • Internet Connectivity: Ensure your development environment has an active internet connection to reach the Hirak OCR API endpoints.
  • SDK Installation: For Python, verify the SDK is correctly installed by running pip show hirak-ocr-sdk. For Node.js, check npm list hirak-ocr-sdk. Reinstall if necessary.
  • Error Messages: Carefully read the error messages returned by the API. They often provide specific clues, such as "Invalid API Key," "File too large," or "Unsupported file format." Refer to the Hirak OCR API error codes for detailed explanations.
  • File Format and Size: Ensure your document adheres to the supported file formats (e.g., JPG, PNG, PDF) and size limits specified in the Hirak OCR API reference.
  • Rate Limiting: If you are making many requests in a short period, you might hit rate limits. The API response will typically indicate a rate limit error. Implement a delay or exponential backoff for retries.
  • SDK Version: Ensure you are using a recent version of the SDK. Outdated SDKs might not support the latest API features or could have bugs.
  • Consult Documentation: The Hirak OCR official documentation is the primary resource for detailed information on endpoints, parameters, and error codes.
  • Contact Support: If you've exhausted other options, contact Hirak OCR support for assistance, providing details of your request, code snippet, and any error messages received.