Extract Data from Invoices, Emails and Forms into JSON with AI

Turn invoices, receipts, emails and forms into clean JSON with an AI model and a JSON schema. Code, model choice, images of documents, checks and cost per thousand.

3 min read

use casesextractionjsonstructured output

Crumpled invoices and envelopes going into a glowing machine and coming out as neat rows of blocks

A lot of business data arrives as text or pictures: invoices, receipts, order emails, CVs, forms. An AI model can read them and hand back the fields you need as JSON, ready for your database. This guide shows how to get output you can trust, with any of the chat models on API Store.

Describe what you want as a JSON schema

The most reliable way to get JSON back is to send a schema with response_format. The model's answer then follows it: the right field names, the right types, nothing extra.

python
import json
from openai import OpenAI

client = OpenAI(base_url="https://api.apistore.cloud/v1", api_key="sk-...")

schema = {
    "type": "object",
    "properties": {
        "supplier": {"type": "string"},
        "invoice_number": {"type": "string"},
        "date": {"type": "string", "description": "YYYY-MM-DD"},
        "currency": {"type": "string", "description": "ISO code, e.g. USD"},
        "total": {"type": "number"},
        "lines": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "description": {"type": "string"},
                    "quantity": {"type": "number"},
                    "amount": {"type": "number"},
                },
                "required": ["description", "quantity", "amount"],
                "additionalProperties": False,
            },
        },
    },
    "required": ["supplier", "invoice_number", "date", "currency", "total", "lines"],
    "additionalProperties": False,
}

reply = client.chat.completions.create(
    model="gpt-6.1-terra",
    messages=[
        {"role": "system", "content": "Extract the invoice. If a field is missing, use an empty string or 0."},
        {"role": "user", "content": invoice_text},
    ],
    response_format={"type": "json_schema", "json_schema": {"name": "invoice", "schema": schema, "strict": True}},
)
invoice = json.loads(reply.choices[0].message.content)

The same request works with Claude and Gemini models: the gateway passes the schema to each maker in the form it expects.

From a picture or a scan

If the document is a photo or a scanned PDF page, send it as an image in the same request. Models that read images (Claude, GPT and Gemini all do) extract the fields from the picture directly:

python
import base64

image = base64.b64encode(open("receipt.jpg", "rb").read()).decode()
messages = [{
    "role": "user",
    "content": [
        {"type": "text", "text": "Extract this receipt."},
        {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image}"}},
    ],
}]

Send one page per image, at a resolution where you can read the small print yourself.

Which model

Volume and difficultyTry first
Thousands of simple, similar documentsgemini-3.1-flash-lite or gpt-6-luna
Mixed layouts, everyday volumegpt-6.1-terra or gemini-3.8-flash
Messy scans, handwriting, documents in many languagesclaude-sonnet-5-5 or gpt-6.2-sol

Build a test set of 30–50 real documents with the right answers, and run each candidate model over it. Field-by-field accuracy on your own documents is the only number that matters.

Checks that catch mistakes

A schema guarantees the shape of the answer, not that the values are right. Add checks in your code:

  • Arithmetic. Do the line amounts add up to the total? If not, flag the document.
  • Formats. Is the date a real date? Is the currency a known code?
  • Known values. Does the supplier match one in your list? Fuzzy-match and flag the rest.
  • Second opinion. For high-value documents, extract with two different models and send only the ones where they disagree to a person.

Most teams end with a simple rule: if every check passes, the record goes straight in; if not, it goes to a review queue.

What it costs

An invoice of one page is roughly 800–1,500 input tokens as text, and the JSON answer 200–400 output tokens. An image costs input tokens too; the response's usage shows how many.

cost per document ≈ input tokens × input price + output tokens × output price

On GPT-6 Luna, at $0.07 per million input tokens and $0.35 per million output tokens, a thousand text invoices of that size cost about 1.5 million input tokens and 0.4 million output tokens in total. On a stronger model, multiply by its prices instead. Run a hundred real documents first and read the actual totals on the Usage page.

Keep the system prompt and the schema the same for every request, and put the document last. The fixed start of the request can then be read from cache at the lower cached price.

Also in Tiếng Việt, Español, Português, Bahasa Indonesia