OCR API in Python: Production Guide for Receipts, Invoices, IDs & PDFs

Move past raw pytesseract text dumps and brittle regexes. Extract schema-validated JSON and spreadsheet tables in Python with pip install structocr, FastAPI, concurrent batching, and pay-as-you-go pricing.

Why Local pytesseract, EasyOCR, and Regex Pipelines Stall in Production

When Python teams and software agencies prototype document automation for expense apps, ERP integrations, or KYC onboarding, local libraries like pytesseract, EasyOCR, and PyPDF2 look attractive on day one. In production, they break on three recurring bottlenecks. First, raw OCR returns flat text lines rather than typed JSON—meaning every new retail POS format, Indian GST bill layout, or multi-column supplier invoice breaks your regex parser. Second, real smartphone uploads arrive rotated, shadowed, crumpled, or in iPhone HEIC format, forcing you to maintain fragile OpenCV deskewing, thresholding, and Poppler/Tesseract binary layers across Docker containers. Third, running deep-learning OCR locally consumes high RAM or GPU instances while still requiring manual post-processing to separate tax bases from actual tax amounts, validate check digits, and normalize currencies.

One Structured OCR API Stack in Python (SDK + REST Multipart)

Instead of stitching together local binaries and layout-specific regexes, call StructOCR's specialized REST endpoints directly from Python. Install the official StructOCR Python SDK (pip install structocr) to access 19 dedicated document endpoints—including Receipt OCR (1 credit), Invoice OCR (3 credits, up to 5 PDF pages), Passport MRZ OCR (2 credits), and National ID OCR (2 credits)—without manual Base64 boilerplate. For custom-schema multi-page PDFs and tables, call zero-retention POST /v1/pdf-extract via standard Python requests. Every new account starts with 200 free permanent credits (no credit card required), and pay-as-you-go credit packs start at $5 for 500 credits with zero monthly subscription lock-in (see transparent pricing). You can also test a receipt live in the widget below or in our free OCR receipt scanner.

What Engineering & Agency Teams Ship with This Python OCR Stack

  • Expense Apps & Indian/APAC GST Receipt Automation: Call client.scan_receipt() (POST /v1/receipt, 1 credit standard / 2 credits ?accuracy=enhanced) to normalize INR (₹), SGD, MYR, PHP, IDR, USD, and EUR thermal POS bills into typed merchant, date, CGST/SGST/VAT tax, total, and line-item rows. See our dedicated Python receipt OCR guide for deeper receipt-specific recipes.
  • Accounts Payable & Multi-Page PDF Invoices: Send single- or multi-page B2B invoices (up to 5 pages per call) via client.scan_invoice() (POST /v1/invoice, 3 credits) to capture vendor details, tax IDs, line items, and totals for Tally, Zoho Books, SAP, Xero, or QuickBooks ingestion.
  • Global KYC & Identity Document Onboarding: Extract ICAO 9303 MRZ fields from passports (client.scan_passport()), national IDs (client.scan_national_id()), driver licenses (client.scan_driver_license()), or cross-check North American license fronts against back PDF417 barcodes via zero-retention POST /v1/driver-license-verify.
  • Multi-Page PDF Tables & Custom JSON Schemas: Pass a JSON Schema (up to 50 fields) and stitch_tables=true to zero-retention POST /v1/pdf-extract (2 credits per succeeded page, failed pages refunded automatically) for bank statements, purchase orders, and financial statements.
  • High-Throughput Batch ETL & Spreadsheet Exports: Combine Python's thread-safe SDK or requests.Session with concurrent.futures.ThreadPoolExecutor, retry transient 503 responses with exponential backoff, and export normalized line items straight into pandas.DataFrame, CSV, or Excel.
Need more testing? Create a free account to get 200 free credits (equals 200 Receipt scans).

Production Python OCR API Examples (SDK, requests, FastAPI & Batch Pandas)

Switch tabs below for four copy-paste production patterns: (1) multi-document extraction with pip install structocr, (2) raw requests for enhanced thermal receipts, zero-retention PDF schemas, and 503 backoff, (3) a FastAPI upload endpoint with size validation, and (4) concurrent folder batching to Pandas/Excel. Store your API key in STRUCTOCR_API_KEY and never hard-code credentials.

Prerequisite: Python 3.9+ (`pip install structocr requests`; optional `fastapi uvicorn python-multipart pandas openpyxl` for server and Excel examples)

import os
from structocr import StructOCR

# Get 200 free permanent credits at https://structocr.com/register
client = StructOCR(api_key=os.environ["STRUCTOCR_API_KEY"])


def extract_receipt(file_path: str) -> dict:
    """Extract a retail/GST receipt (1 credit standard) and check validation status."""
    result = client.scan_receipt(file_path)
    if not result.get("success"):
        raise RuntimeError(result.get("error") or "Receipt OCR request failed")

    data = result["data"]
    # Always inspect status & issues before auto-posting to accounting ledgers
    if data.get("status") != "complete":
        print("Needs review:", data.get("status"), data.get("issues"))
    return data


def extract_invoice(file_path: str) -> dict:
    """Extract a B2B invoice image or multi-page PDF (up to 5 pages, 3 credits)."""
    result = client.scan_invoice(file_path)
    if not result.get("success"):
        raise RuntimeError(result.get("error") or "Invoice OCR request failed")
    return result["data"]


def extract_passport(file_path: str) -> dict:
    """Extract ICAO 9303 MRZ and visual identity fields (2 credits)."""
    result = client.scan_passport(file_path)
    if not result.get("success"):
        raise RuntimeError(result.get("error") or "Passport OCR request failed")
    return result["data"]


if __name__ == "__main__":
    receipt = extract_receipt("./samples/gst_receipt.jpg")
    print(
        f"{receipt.get('merchant_name')} | "
        f"{receipt.get('total_amount')} {receipt.get('currency')} | "
        f"tax={receipt.get('tax_amount')} | items={len(receipt.get('items', []))}"
    )

Technical Specs

  • •Official SDK: `pip install structocr` (Python 3.7+, covers 19 endpoints; raw HTTP `requests` covers all 23 public endpoints including `/v1/pdf-extract`, `/v1/image-to-excel`, and `/v1/driver-license-verify`)
  • •Authentication: Single `x-api-key` header (created automatically on free signup)
  • •Input Formats & Limits: JPG, PNG, WebP, HEIC (iPhone photos), and PDF; up to 4.5 MB on Base64 image endpoints and up to 10 MB / 20 pages on `POST /v1/pdf-extract`
  • •Pricing & Credits: 1 credit (receipt, VIN, container, plate), 2 credits (passport, ID, driver license, PDF page, enhanced receipt), 3 credits (invoice, BOL), 4 credits (front+back driver license verify). 200 free permanent credits on signup; top-ups from $5 (500 credits), never expire
  • •Zero Data Retention Endpoints: Strict in-memory zero retention (`raw_response: null`) enforced on `/v1/pdf-extract`, `/v1/image-to-excel`, `/v1/driver-license-pdf417`, `/v1/driver-license-verify`, `/v1/health-card`, `/v1/visa`, and `/v1/proof-of-address`
  • •Failure Refunds: Server/processing errors (5xx) and unreadable PDF417/failed PDF pages do not charge credits or refund automatically

Key Features

  • •Schema-validated JSON out of the box: No regex maintenance when a vendor or POS terminal changes receipt or invoice formatting.
  • •Zero system-binary bloat: Drop Tesseract language packs, Poppler, OpenCV deskew scripts, and multi-GB Docker images from your Python backend.
  • •Explicit null & review signaling: Endpoints like `/v1/receipt` return `status` (`complete` / `partial` / `invalid`), `issues[]`, and `null` for unreadable values instead of fabricating numbers.
  • •Agency-friendly pay-as-you-go unit economics: Start at $0 with 200 free credits and scale with non-expiring packs from $5—ideal for client prototypes and multi-tenant SaaS apps without $500/mo minimums.

Sample Python Dictionary / JSON Output (Synthetic Indian GST Receipt Specimen)

Synthetic `POST /v1/receipt` (`response_version: 2`) JSON response showing ISO 4217 `INR` normalization, combined CGST/SGST `tax_amount`, structured `items[]`, and validation metadata ready for Pandas or database insertion.

{
  "success": true,
  "data": {
    "response_version": 2,
    "merchant_name": "Deccan Fresh Mart Pvt. Ltd.",
    "date": "2026-11-24",
    "time": "19:42",
    "currency": "INR",
    "total_amount": 1475,
    "tax_amount": 225,
    "items": [
      {
        "name": "Arabica Filter Coffee 500g",
        "quantity": 2,
        "price": "840.00"
      },
      {
        "name": "Cold Pressed Groundnut Oil 1L",
        "quantity": 1,
        "price": "410.00"
      }
    ],
    "status": "complete",
    "issues": [],
    "confidence": "high",
    "is_valid": true,
    "validation_error": null
  }
}

Frequently Asked Questions

How is a structured OCR API in Python different from pytesseract or EasyOCR?

Libraries like pytesseract and EasyOCR return unstructured text strings or bounding boxes, leaving your Python code to write brittle regexes for totals, dates, tax tables, and line items. A structured OCR API returns normalized, typed JSON directly (such as merchant_name, ISO 4217 currency, tax_amount, total_amount, and items[]) with validation flags, without deploying Tesseract binaries or GPU instances.

Should I use pip install structocr or Python requests directly?

Use the official pip install structocr SDK for the 19 single-image/document endpoints (receipts, invoices, passports, national IDs, driver licenses, health cards, auto insurance, bills of lading, VINs) because it accepts local file paths or raw bytes and handles Base64 framing automatically. Use Python requests with multipart/form-data for POST /v1/pdf-extract, POST /v1/image-to-excel, POST /v1/driver-license-verify, or when passing query parameters such as /v1/receipt?accuracy=enhanced.

How do I process thousands of receipts or PDFs concurrently in Python?

Both StructOCR client calls and requests.Session are thread-safe. Wrap your extraction function in concurrent.futures.ThreadPoolExecutor (for example, 5–10 workers), retry HTTP 503 SYSTEM_BUSY with exponential backoff, fail fast on 400/402/413/415, and route rows where status != "complete" to a manual review queue before writing to your ERP or database.

How much does it cost to integrate StructOCR into a Python client project?

Every new account receives 200 free permanent credits (up to 200 standard receipt scans or 100 ID/passport/PDF page extractions) with no credit card required. Paid top-up packs start at $5 for 500 credits ($0.01 per standard receipt), scale down to $0.0047/credit on larger packs, and never expire—so agencies and SaaS builders never pay idle monthly subscriptions. See the full breakdown on our pricing page.

Does the Python OCR API handle Indian GST bills (INR / ₹) and faded thermal receipts?

Yes. POST /v1/receipt extracts Indian retail and restaurant receipts in INR (recognizing ₹ and Rs.), sums explicit CGST/SGST/IGST lines into tax_amount, and parses Southeast Asian and global currencies (SGD, MYR, PHP, IDR, USD, EUR, GBP). For long or faded thermal paper, pass ?accuracy=enhanced (2 credits). For multi-page A4 B2B GST tax invoices, use POST /v1/invoice.

Which endpoints enforce strict Zero Data Retention for sensitive client documents?

POST /v1/pdf-extract, POST /v1/image-to-excel, POST /v1/driver-license-pdf417, POST /v1/driver-license-verify, POST /v1/health-card, POST /v1/visa, and POST /v1/proof-of-address enforce strict in-memory Zero Data Retention (no stored files, raw_response: null in usage logs, zero model training). Standard receipt and invoice API calls are encrypted with TLS in transit and auto-deleted within 24 hours.

You May Also Like

Related tutorials, platform guides, and comparisons

Tutorial

How to Choose a Receipt OCR API in 2026

A practical checklist for evaluating receipt OCR APIs: coverage, accuracy on real photos, error handling, privacy, and cost per successful result.

Receipt
Country Tutorial

Indonesia Receipt OCR: Formats, Items and Totals

Convert indonesia receipt ocr: formats, items and totals into structured merchant, date, item, tax and total fields, with checks for ambiguous amounts.

Python · Receipt
Tutorial

Taggun Alternative: Receipt OCR API

Taggun compared with the StructOCR REST API for receipt extraction: deployment, pricing model, and when each fits.

Receipt
Tutorial

Node.js Receipt OCR API SDK

Tutorial: Integrate the StructOCR Node.js SDK to extract structured data from retail receipts. Upload an image for a free test! Parse merchants, totals, and line items in your Javascript backends.

Node.js · Receipt
Tutorial

C# Receipt OCR API

Upload an image for a free test! Integrate a robust Receipt OCR API into your C# .NET app. Accurately extract merchants, line items, taxes, and totals from crumpled thermal receipts.

C# · Receipt
Country Tutorial

Australia Receipt OCR: Formats, Items and Totals

Convert australia receipt ocr: formats, items and totals into structured merchant, date, item, tax and total fields, with checks for ambiguous amounts.

Python · Receipt
Tutorial

Java Receipt OCR API

Tutorial: Integrate StructOCR's Receipt API into your Java enterprise applications. Upload an image for a free test! Extract line items, merchants, and taxes from POS receipts into structured JSON.

Java · Receipt
Tutorial

Python Receipt OCR API SDK

Tutorial: Extract merchants, line items, and totals from receipts using the StructOCR Python SDK. Upload an image for a free test! Ideal for fintech ETL pipelines, AI accounting, and Pandas dataframes.

Python · Receipt
Tutorial

PHP Receipt OCR API

Tutorial: Integrate the StructOCR Receipt API into your PHP web applications. Upload an image for a free test! Extract merchants, totals, and line items from POS receipts using raw cURL or Guzzle.

PHP · Receipt
Country Tutorial

Extract Argentina Driver License Fields with Node.js

Extract licence number, names, dates, and vehicle class from the Argentina Licencia Nacional de Conducir with the StructOCR Node.js SDK.

Node.js · Driver License

Technical Comparisons & Integrations

Explore platform integrations and competitive analysis

From tutorial to production in 5 minutes.

You've seen the code. Now get your API key, grab your 200 free credits, and see it work with your own images. No credit card required.

Instant Access Cancel Anytime No Credit Card