Invoice Generator API: Create Invoice PDFs from JSON with Python
01Introduction
Your application already knows what the customer bought. It has the seller, buyer, invoice number and line items. The remaining task is turning that record into a document the customer can download.
That step often becomes a second project: layout rules, page breaks, PDF generation and another set of formatting code to maintain. A document API gives the application a narrower job: supply the invoice data, check the returned file and store the finished copy.
This tutorial uses Generate Invoice Document from JSON on ApyHub, an invoice generator API that returns PDF, Word or HTML. We build this API at Callable Labs. We'll create a two-line invoice PDF and outline where the request belongs in a billing workflow.
02Map your record into the request
The invoice fields belong inside data. Output options such as format and page sit alongside it. An invoice requires a number, date, seller, buyer and at least one line item.
In this example, three hours of consultation at $85 and one $45 setup fee produce a $300 subtotal. A sample 10% tax rate produces a $330 total. The tax rate is illustrative; your application must supply the rates and invoice details appropriate to its business.
03Generate and save the PDF
Create an ApyHub API key, export it as APY_TOKEN and install requests with python -m pip install requests. Save this script as invoice.py:
import os
from pathlib import Path
import requests
URL = (
"https://api.eu.apyhub.com/callable-labs/"
"generate-invoice-document-from-json-api/v1/documents/preset/invoice"
)
payload = {
"data": {
"number": "INV-2026-0042",
"date": "2026-10-23",
"due_date": "2026-11-06",
"currency": "quot;,
"seller": {"name": "Example Studio", "email": "[email protected]"},
"buyer": {"name": "Example Customer"},
"items": [
{"description": "Consultation", "quantity": 3, "unit_price": 85, "tax_rate": 10},
{"description": "Project setup", "quantity": 1, "unit_price": 45, "tax_rate": 10},
],
"notes": "Please include the invoice number with your payment.",
},
"page": {"size": "A4", "margin_mm": 18},
"format": "pdf",
}
response = requests.post(
URL,
headers={"apy-token": os.environ["APY_TOKEN"]},
json=payload,
timeout=90,
)
response.raise_for_status()
media_type = response.headers.get("Content-Type", "").split(";")[0].lower()
if media_type != "application/pdf" or not response.content.startswith(b"%PDF-"):
raise ValueError("Expected PDF output")
output = Path("INV-2026-0042.pdf")
output.write_bytes(response.content)
print(f"Saved {output} ({len(response.content)} bytes)")Run python invoice.py and open the PDF. Compare the parties, line items and total with the source record before adding it to your workflow. The response checks guard against saving an obvious JSON error as a PDF; they do not replace opening and reviewing the document.
04Store the rendered invoice before delivering it
A useful application flow is: finalize the invoice record, queue generation, save the PDF, then make it available for download or delivery. Keep the invoice ID, a version of its source data and the storage location together.
On a successful retry, reuse the saved PDF rather than rendering the same invoice again. Keep customer delivery as a separate job so a temporary document-generation failure does not trigger duplicate emails. If a generation request times out, record that state before resubmitting; do not assume a client timeout means no work occurred or no atoms (ApyHub's usage unit) were consumed.
The invoice preset calculates totals from the line items you supply. Your billing system still owns invoice numbering, business rules and the authoritative transaction record. A PDF generator does not determine tax treatment, reconcile payments or deliver the invoice for you.
05Choose the output that fits the next step
Set format to docx for an editable Word document, html for markup or json for metadata and a PDF data URI. The example requests pdf explicitly because the default JSON response should not be written directly to a .pdf file.
For an existing branded Word layout, use Validate & Generate Documents from Templates. Receipts, certificates, letters and reports have separate preset listings. A general invoice PDF also differs from a structured e-invoice; use the dedicated e-invoice service when your workflow needs one of its supported formats.
Keep the ApyHub token on your server. Correct 422 input errors before retrying, and use a finite retry budget for temporary service failures. Save each completed output so a batch can resume without repeating successful requests.
06Generate invoices from an AI agent
The invoice generator is also available through ApyHub MCP, like every endpoint in the ApyHub catalog. An agent in Claude, ChatGPT, Cursor or any MCP client can find and call it directly, without a wrapper or tool definition. The agent calls a ready-made endpoint instead of writing its own PDF layout code, which gives consistent invoices and uses fewer tokens.
Connect ApyHub MCP to your agent →
07Conclusion
Try the invoice generator with a small synthetic invoice first. Once the PDF matches the record, connect the same request to your application's document job.
Try the Invoice Generator API for free →
08FAQ
What is an invoice generator API? It turns structured invoice data (seller, buyer, number, date and line items) into a finished document. Generate Invoice Document from JSON returns PDF, Word or HTML.
How do I generate an invoice PDF from JSON in Python? POST your invoice with "format": "pdf" and write the response bytes to a .pdf file. The invoice.py script in this post does exactly that.
Does the API calculate tax and totals? Yes, from the quantities, unit prices and per-line tax_rate you send. Your billing system decides which tax rate applies.
What is the difference between an invoice PDF and an e-invoice? A PDF is for people to read. An e-invoice is a structured file accounting systems read, such as XRechnung, ZUGFeRD or Peppol. For those, use the e-invoice API.
Can I use my own invoice design? Yes. Build it as a Word template and fill it with Validate & Generate Documents from Templates.
How do I test the invoice API before writing code? Use the "Try it" panel on the API page, run the request with curl, or save the request in Voiden, an open-source API client that stores requests as Markdown files next to your code.
Is there a free plan? Yes. The ApyHub Starter plan includes 5 API calls a day and 3,000 atoms a month, with no credit card. That is enough to test this tutorial end to end.
09About Callable Labs
Callable Labs builds APIs for machine-readable workflows, designed for automation and AI agents. Besides the invoice generator, their APIs on ApyHub include:
- Receipt, report and Word template generation
- E-invoice creation, validation and parsing
- OCR from images and PDFs to Markdown
- ECB exchange rates and business-day calculations
See all 20 on the Callable Labs provider page.
10About ApyHub
ApyHub is a curated API catalog and trusted operational layer for developers and AI agents. The catalog has over 1,500 endpoints and capabilities and keeps growing, all under one subscription billed in atoms. Every service carries machine-readable certification (GDPR, SOC 2, ISO 27001), is MCP-ready by default and runs in dedicated EU and US regions. More than 65,000 developer workspaces use ApyHub every month, and the free tier needs no credit card. Have an API of your own? Publish it on ApyHub.
