Build an Invoice Line Item Parser with the Claude API
Why invoice parsing is harder than it looks
If you're searching for how to build a Claude API invoice line item parser, you've probably already discovered the obvious approach — "just ask the model to extract the fields" — breaks down fast. Invoices arrive as scanned PDFs, mixed-currency line items, multi-page tables, and vendor-specific layouts that have zero structural consistency. A regex or template-based parser dies the moment a new vendor sends their first invoice. What you actually need is a model that can read unstructured text or images and return structured, validated JSON every time, with a fallback path for when it can't.
This guide walks through a practical architecture for that: prompt design, structured output with tool schemas, handling multi-line and multi-page invoices, and the validation layer you need before the data touches your accounting system. We'll use Claude's API directly in the examples, and note where a gateway like SubToAPI simplifies the operational side (auth, streaming, usage tracking) so you can focus on the parsing logic itself.
The core architecture
A production invoice parser has four stages:
- Ingestion — convert the invoice (PDF, image, email attachment) into text or base64 image data.
- Extraction — send it to Claude with a strict schema asking for header fields and a line item array.
- Validation — check totals reconcile, currencies match, required fields are non-null.
- Fallback/review — flag low-confidence or failed extractions for human review instead of silently writing bad data.
Skipping stage 3 is the most common mistake. Models are good at pattern matching but will happily invent a plausible-looking tax rate if the source document is blurry or cropped. Never trust line-item math without checking it yourself.
Designing the extraction schema
Use Claude's tool-calling feature instead of asking for "JSON in a nice format" in plain prose. Tool use forces the model into a schema and makes parsing the response deterministic. Define a tool like this:
{
"name": "record_invoice",
"description": "Record parsed invoice header and line items",
"input_schema": {
"type": "object",
"properties": {
"vendor_name": { "type": "string" },
"invoice_number": { "type": "string" },
"invoice_date": { "type": "string" },
"currency": { "type": "string" },
"line_items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": { "type": "string" },
"quantity": { "type": "number" },
"unit_price": { "type": "number" },
"line_total": { "type": "number" },
"tax_rate": { "type": "number" }
},
"required": ["description", "quantity", "unit_price", "line_total"]
}
},
"subtotal": { "type": "number" },
"tax_total": { "type": "number" },
"grand_total": { "type": "number" }
},
"required": ["vendor_name", "line_items", "grand_total"]
}
}
Keep the schema flat and avoid deeply nested optional fields — the more structure you ask for, the more surface area there is for the model to get something wrong. If a field genuinely doesn't apply (no tax, no PO number), let it be omitted rather than forcing a default value that could be mistaken for real data.
Sending the request
If you're calling Claude directly, a request with the tool defined above and the invoice text (or image) in the user message will return a tool_use block containing the structured output. If you're routing through SubToAPI, the request shape is the same Messages-style payload, just pointed at https://api.subtoapi.app/v1/messages with your sub_live_ key:
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 2048,
"tools": [ /* record_invoice schema above */ ],
"tool_choice": {"type": "tool", "name": "record_invoice"},
"messages": [
{"role": "user", "content": "Extract the invoice data from this text:\n\n" + invoiceText}
]
}'
Forcing tool_choice to the specific tool is important here — without it, the model might respond with plain text for edge cases instead of calling the tool at all, which breaks your parsing pipeline. See /docs/tools for the full tool-use reference and /docs/messages for request/response shapes.
Handling multi-page and scanned invoices
For scanned PDFs, convert each page to an image and send them as separate content blocks in the same message rather than making one call per page — this lets Claude reconcile a line-item table that spans a page break. For very long invoices (50+ line items, common in logistics and SaaS billing), chunk by page but include the running subtotal from the previous page as context so the model doesn't double-count or drop rows at the boundary.
Validation before you trust the output
After extraction, run deterministic checks in your own code — don't ask the model to validate itself:
function validateInvoice(parsed) {
const computedSubtotal = parsed.line_items.reduce(
(sum, item) => sum + item.line_total, 0
);
const diff = Math.abs(computedSubtotal - parsed.subtotal);
if (diff > 0.02) {
return { valid: false, reason: "subtotal_mismatch" };
}
if (!parsed.line_items.length) {
return { valid: false, reason: "no_line_items" };
}
return { valid: true };
}
Route anything that fails validation to a manual review queue instead of auto-posting it to your ledger. This single guardrail prevents the majority of real-world accounting errors from reaching production.
Streaming and batch processing
For a single invoice in a UI flow, streaming the response lets you show the line items appearing incrementally — useful for a review screen where a user confirms extracted data before it's saved. See /docs/streaming for implementation details. For bulk backfills (thousands of historical invoices), batch the calls instead, process asynchronously, and store the raw model response alongside the parsed JSON so you can re-validate or re-parse later without re-sending the document.
Where SubToAPI fits
Building the parser itself is prompt and schema design — that part doesn't change regardless of how you call the model. What SubToAPI handles is the operational layer around it: issuing scoped sub_live_ API keys per internal service or environment, giving you usage metadata per key so you can see exactly how much an invoice-parsing job costs, and team seats if more than one engineer needs access to the dashboard. If you're already prototyping against the Claude API and want billing and key management handled without standing up your own proxy, start with /signup and check /docs/quickstart for a five-minute setup. Plans start at €9/month on the Solo tier — see /pricing for details.
questions
Can Claude read scanned invoice images directly, or do I need OCR first? Claude can process images directly via the Messages API, so a scanned PDF converted to PNG/JPEG works without a separate OCR step. For very low-resolution scans, a dedicated OCR pass first can still improve accuracy.
How do I stop the model from inventing totals on unclear invoices? Force tool use with a required schema, then validate computed line-item sums against the stated subtotal in your own code. Mismatches should route to human review rather than being trusted automatically.
What's the best way to handle invoices in different languages or currencies? Include the currency and language explicitly in your schema as required fields, and instruct the model to preserve the original currency code rather than converting — do currency conversion as a separate deterministic step downstream.