Accounting

Automate Xero Invoice Entry — Extract PDF Invoice Data Directly into Xero

Import supplier invoices into Xero without manual data entry. One script, any invoice format.

By Othmane M., founder of DocuParse API · Last reviewed: 2026-10-20

The guide

  1. 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. 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. 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"]
    Need your API key first?
    20 free documents/month — no credit card
    Sign up — get a free API key
  4. 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. 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. 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. 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

python
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

FieldDescriptionDestination field
merchantThe vendor or store nameContact.Name
totalThe final charged amount including taxCalculated from lines
subtotalThe pre-tax amountLineItems[].UnitAmount
taxThe tax amount chargedTaxType on lines
dateInvoice or transaction date (ISO 8601)Date
due_datePayment due date, or null if not presentDueDate
invoice_idInvoice number or receipt ID from the documentInvoiceNumber
currencyISO 4217 currency code (USD, EUR, GBP, etc.)CurrencyCode
payment_methodCard type, cash, or other payment methodNot mapped
line_itemsArray of items with description, quantity, price, line_total, vat_rateLineItems[] array

Common errors and fixes

MISSING_API_KEYAuthorization header missingAdd header: Authorization: Bearer YOUR_KEY
INVALID_API_KEYKey not recognisedCheck key in dashboard — regenerate if needed
LIMIT_EXCEEDEDMonthly document limit reachedUpgrade at docuparseapi.com/pricing
UNSUPPORTED_FILE_TYPEFile format not supportedUse PDF, JPG, PNG or CSV
FILE_TOO_LARGE_AUTHENTICATEDThe file is too largeCompress the image or split the PDF
TOO_MANY_PAGESMore than 20 pagesSplit the PDF into parts of up to 20 pages
EXTRACTION_FAILEDDocument could not be parsedTry 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.

Sign up — get a free API key