Tutorial · invoice OCR

Invoice OCR API: extract line items to JSON

Generic OCR returns text. An invoice pipeline returns a validated record: vendor, invoice number, dates, line items, tax, total and currency — with arithmetic checks, duplicate detection and a human-review path when the numbers do not reconcile.

Short answer. Render each invoice page to an image, send it to plugsky-parse with a strict JSON schema, validate the arithmetic, and write the record only if it reconciles. Use a fingerprint to reject duplicates and send low-confidence invoices to review. Paid plans start at $8/month; Builder and Scale have no monthly token cap.

Why invoice OCR is not generic OCR

OCR answers “what text is on the page?” An invoice pipeline answers “what is the invoice number, who is the vendor, what are the line items, and does the total add up?” The difference is the schema, the validation and the exception handling. A perfect transcription with a wrong total is still a failed invoice.

The 12-field schema

FieldTypeValidation
vendor_namestringRequired; match against vendor master if available
vendor_tax_idstring / nullFormat check by country
invoice_numberstringRequired; unique per vendor
invoice_dateYYYY-MM-DDParseable; not in the future
due_dateYYYY-MM-DD / nullParseable; ≥ invoice date
currencyISO 4217Three-letter code; consistent with amounts
purchase_orderstring / nullOptional; match to PO if required
line_itemsarrayDescription, quantity, unit price, amount
subtotalnumberLine items sum to subtotal
taxnumberRate or amount; subtotal + tax = total
totalnumberRequired; arithmetic check
payment_termsstring / nullOptional; normalize to days

Pipeline

  1. Ingest: accept PDF, image or scan; store the original unchanged.
  2. Render: one image per page at a readable resolution; keep the page number.
  3. Parse: send the page and schema to plugsky-parse; request JSON only.
  4. Validate: required fields, types, dates, currency and arithmetic.
  5. Deduplicate: check the file hash and the invoice fingerprint.
  6. Review: route failures to a human with the page image and the failing check.
  7. Export: write to the ERP/accounting system with an idempotency key.

Extraction code

import json
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_PLUGSKY_KEY",
    base_url="https://api.plugsky.com/v1",
)

schema = {
    "vendor_name": "string",
    "vendor_tax_id": "string|null",
    "invoice_number": "string",
    "invoice_date": "YYYY-MM-DD",
    "due_date": "YYYY-MM-DD|null",
    "currency": "ISO 4217",
    "purchase_order": "string|null",
    "line_items": [{"description": "string", "quantity": "number", "unit_price": "number", "amount": "number"}],
    "subtotal": "number",
    "tax": "number",
    "total": "number",
    "payment_terms": "string|null",
}

response = client.chat.completions.create(
    model="plugsky-parse",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Extract the invoice. Use null for missing fields. Do not invent values. Return JSON only."},
        {"role": "user", "content": [
            {"type": "text", "text": json.dumps({"schema": schema})},
            {"type": "image_url", "image_url": {"url": "https://example.com/invoice-page-1.png"}},
        ]},
    ],
)

record = json.loads(response.choices[0].message.content)

Validation that catches real errors

from decimal import Decimal, ROUND_HALF_UP

def money(x):
    return Decimal(str(x)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

line_total = sum(money(i["amount"]) for i in record["line_items"])
assert line_total == money(record["subtotal"]), "line items do not sum to subtotal"
assert money(record["subtotal"]) + money(record["tax"]) == money(record["total"]), "subtotal + tax != total"
assert len(record["currency"]) == 3, "currency is not ISO 4217"

If an assertion fails, do not “fix” the total. Send the invoice to review with the failed check and the page image. Silent correction is how bad data enters the ERP.

Duplicate detection

Use two keys:

  • File hash: catches the same PDF uploaded twice.
  • Invoice fingerprint: a hash of vendor ID + invoice number + invoice date + currency + total. Store it with a unique constraint.

If the fingerprint matches an existing record, return the existing record and flag the upload instead of creating a second payable.

Benchmark on 50 real invoices

Do not trust a vendor demo. Build a 50-invoice set that includes scans, photos, multi-page invoices, credit notes, different currencies, tax-inclusive and tax-exclusive layouts, and at least one handwritten field. Measure:

  • Field-level accuracy for each of the 12 fields.
  • Line-item accuracy at the row level; a missing row is worse than a wrong description.
  • Arithmetic pass rate after validation.
  • Review rate — the share a human must touch.
  • End-to-end latency from upload to validated record.

A model with 95% field accuracy but a 30% review rate may cost more than a model with 90% accuracy and a 10% review rate. Measure the whole pipeline.

Cost per 1,000 invoices

Estimate tokens per invoice, not tokens per word. A one-page invoice at a readable resolution is typically a modest image-token count plus a JSON completion. Then add the review cost:

cost_per_1000 =
    1000 × (input_tokens × input_rate + output_tokens × output_rate)
    + 1000 × review_rate × minutes_per_review × reviewer_cost_per_minute

Plugsky Hobby is $8/month with 1,000 requests and 2M tokens/day; Starter is $20/month with 2,000 requests and 5M tokens/day. Builder ($60) and Scale ($120) have no monthly token cap, with fair-use concurrency and RPM. For high-volume invoice processing, the flat plan is usually easier to forecast than per-token billing.

Security and residency

Invoices contain bank details, addresses and tax IDs. Decide what must be redacted, how long the page is retained, and where it is processed. Plugsky offers cloud, private VPC, on-prem and air-gapped deployment; confirm retention and residency in the contract before sending regulated financial documents.

FAQ

What is an invoice OCR API?

An API that accepts an invoice image or PDF and returns structured fields such as vendor, invoice number, dates, line items, tax and total, with a schema and validation layer.

Which Plugsky model should I use?

plugsky-parse, with a 262,144-token context and up to 16,384 output tokens. Text-layer PDFs can use a text model after extraction.

How do I validate extracted totals?

Check line items vs subtotal, subtotal + tax vs total, currency consistency and date parsing. Route failures to review; do not correct them silently.

How do I stop duplicate invoices?

Use a file hash plus a fingerprint of vendor, invoice number, date, currency and total, with a unique constraint.

How much does it cost per 1,000 invoices?

It depends on pages, image size, output size and review rate. On Plugsky, paid plans start at $8/month; Builder and Scale have no monthly token cap.

Reviewed 20 November 2026. Model limits are checked against the Plugsky model catalogue. Invoice layouts vary; validate on your own corpus before production use. This page is editorial and does not rank providers by payment.