The guide
- 1
Get your credentials
You need: DocuParse API key, Xero OAuth 2.0 access token, and your Xero Tenant ID. Create a Xero app at developer.xero.com. Use the Xero OAuth 2.0 Playground to get an initial access token for testing. Xero access tokens expire after 30 minutes; refresh them with your refresh token before each run.
- 2
Extract the invoice
Submit the PDF and fetch the result with parse_document (see the Python guide). The fetched data maps directly to Xero fields:
merchant → Contact.Name date → Date due_date → DueDate invoice_id → InvoiceNumber currency → CurrencyCode line_items → LineItems[] array (UnitAmount = price)
- 3
Find or create the Xero Contact
Search Xero Contacts for the merchant name. Create if not found:
def get_or_create_contact(name, base, headers): r = requests.get(f"{base}/Contacts", headers=headers, params={"searchTerm": name}) contacts = r.json().get("Contacts", []) if contacts: return contacts[0]["ContactID"] r = requests.post(f"{base}/Contacts", headers=headers, json={"Contacts": [{"Name": name}]}) return r.json()["Contacts"][0]["ContactID"]Sign up — get a free API keyNeed your API key first?20 free documents/month — no credit card - 4
ACCPAY or ACCREC?
Use Type "ACCPAY" for bills you receive from suppliers (what this guide creates). ACCREC is for sales invoices you send to customers.
- 5
Create a Draft Bill (ACCPAY)
POST to Xero /Invoices with Type: ACCPAY and Status: DRAFT so a human can approve before payment:
bill = { "Type": "ACCPAY", "Contact": {"ContactID": contact_id}, "Date": invoice["date"], "DueDate": invoice["due_date"], "InvoiceNumber": invoice["invoice_id"], "CurrencyCode": invoice.get("currency") or "USD", "Status": "DRAFT", "LineItems": [{ "Description": item["description"], "Quantity": item.get("quantity") or 1, "UnitAmount": float(item.get("price") or 0), "AccountCode": "429" } for item in invoice.get("line_items", [])] } - 6
Check for validation errors
Xero returns HasValidationErrors: true if the bill is invalid. Always check this before proceeding:
result = r.json()["Invoices"][0] if result.get("HasValidationErrors"): raise RuntimeError(f"Xero error: {result['ValidationErrors']}") print(f"Bill created: {result['InvoiceID']}") - 7
Attach the original PDF to the bill
Yes, you can import the PDF into Xero through the API: upload it as an attachment on the bill you just created. Call this with the InvoiceID returned by the create step.
def attach_pdf_to_bill(invoice_id, pdf_path): file_name = os.path.basename(pdf_path) with open(pdf_path, "rb") as f: r = requests.put( f"{XERO_BASE}/Invoices/{invoice_id}/Attachments/{file_name}", headers={ "Authorization": XERO_HEADERS["Authorization"], "Xero-tenant-id": XERO_HEADERS["Xero-tenant-id"], "Content-Type": "application/pdf", "Accept": "application/json", }, data=f.read(), ) r.raise_for_status() return r.json()
Full working example
import os, time, requests
XERO_BASE = "https://api.xero.com/api.xro/2.0"
XERO_HEADERS = {"Authorization": f"Bearer {os.environ['XERO_ACCESS_TOKEN']}",
"Xero-tenant-id": os.environ['XERO_TENANT_ID'],
"Content-Type": "application/json", "Accept": "application/json"}
ACCOUNT_CODE = os.environ.get("XERO_EXPENSE_ACCOUNT_CODE", "429")
API = "https://docuparseapi.com/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['DOCUPARSE_API_KEY']}"}
def parse_document(path: str) -> dict:
# 1. Submit
with open(path, "rb") as f:
submit = requests.post(f"{API}/extract", headers=HEADERS,
files={"file": (os.path.basename(path), f)}, timeout=30).json()
if not submit.get("success"):
raise RuntimeError(f"[{submit['error']['code']}] {submit['error']['message']}")
# 2. Fetch the result
for _ in range(40):
doc = requests.get(f"{API}/documents/{submit['document_id']}",
headers=HEADERS, timeout=30).json()
if doc["status"] == "completed":
return doc["data"]
if doc["status"] == "failed":
raise RuntimeError(f"Extraction failed: {submit['document_id']}")
time.sleep(1.5)
raise TimeoutError(submit["document_id"])
def get_or_create_contact(name):
r = requests.get(f"{XERO_BASE}/Contacts", headers=XERO_HEADERS, params={"searchTerm": name})
contacts = r.json().get("Contacts", [])
if contacts: return contacts[0]["ContactID"]
r = requests.post(f"{XERO_BASE}/Contacts", headers=XERO_HEADERS,
json={"Contacts": [{"Name": name}]})
return r.json()["Contacts"][0]["ContactID"]
def attach_pdf_to_bill(invoice_id, pdf_path):
file_name = os.path.basename(pdf_path)
with open(pdf_path, "rb") as f:
r = requests.put(
f"{XERO_BASE}/Invoices/{invoice_id}/Attachments/{file_name}",
headers={
"Authorization": XERO_HEADERS["Authorization"],
"Xero-tenant-id": XERO_HEADERS["Xero-tenant-id"],
"Content-Type": "application/pdf",
"Accept": "application/json",
},
data=f.read(),
)
r.raise_for_status()
return r.json()
def process(file_path):
inv = parse_document(file_path)
contact_id = get_or_create_contact(inv.get("merchant") or "Unknown")
r = requests.post(f"{XERO_BASE}/Invoices", headers=XERO_HEADERS,
json={"Invoices": [{
"Type": "ACCPAY", "Contact": {"ContactID": contact_id},
"Date": inv.get("date"), "DueDate": inv.get("due_date"),
"InvoiceNumber": inv.get("invoice_id"),
"CurrencyCode": inv.get("currency") or "USD", "Status": "DRAFT",
"LineItems": [{"Description": item.get("description") or "",
"Quantity": item.get("quantity") or 1,
"UnitAmount": float(item.get("price") or 0),
"AccountCode": ACCOUNT_CODE}
for item in inv.get("line_items",[])]}
]})
result = r.json()["Invoices"][0]
if result.get("HasValidationErrors"):
raise RuntimeError(result["ValidationErrors"])
attach_pdf_to_bill(result["InvoiceID"], file_path)
print(f"Xero Bill created: {result['InvoiceID']}")
process("invoice.pdf")What gets extracted
| Field | Description | Destination field |
|---|---|---|
merchant | The vendor or store name | Contact.Name |
total | The final charged amount including tax | Calculated from lines |
subtotal | The pre-tax amount | LineItems[].UnitAmount |
tax | The tax amount charged | TaxType on lines |
date | Invoice or transaction date (ISO 8601) | Date |
due_date | Payment due date, or null if not present | DueDate |
invoice_id | Invoice number or receipt ID from the document | InvoiceNumber |
currency | ISO 4217 currency code (USD, EUR, GBP, etc.) | CurrencyCode |
payment_method | Card type, cash, or other payment method | Not mapped |
line_items | Array of items with description, quantity, price, line_total, vat_rate | LineItems[] array |
Common errors and fixes
MISSING_API_KEY | Authorization header missing | Add header: Authorization: Bearer YOUR_KEY |
INVALID_API_KEY | Key not recognised | Check key in dashboard — regenerate if needed |
LIMIT_EXCEEDED | Monthly document limit reached | Upgrade at docuparseapi.com/pricing |
UNSUPPORTED_FILE_TYPE | File format not supported | Use PDF, JPG, PNG or CSV |
FILE_TOO_LARGE_AUTHENTICATED | The file is too large | Compress the image or split the PDF |
TOO_MANY_PAGES | More than 20 pages | Split the PDF into parts of up to 20 pages |
EXTRACTION_FAILED | Document could not be parsed | Try a cleaner scan or different file |
Ready to start?
20 documents a month free, with full API access. No credit card. Webhooks on Starter and Pro.