PyXero

0.9.5 · active · verified Thu Apr 16

PyXero is a community-maintained Python library for accessing the Xero accounting software's REST API. It provides a convenient object-oriented interface to interact with various Xero entities like contacts, invoices, and accounts. The library is actively maintained with irregular but consistent releases, primarily focusing on supporting Xero's evolving API and compatible Python versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the PyXero client and fetch data using a pre-obtained OAuth2 access token and tenant ID. For initial authentication and token management (obtaining the access token and handling refreshes), refer to the official PyXero GitHub documentation on OAuth2 setup, which typically involves a web application flow to get the initial tokens.

import os
from xero import Xero

# Set these environment variables with your Xero OAuth2 credentials:
# XERO_ACCESS_TOKEN: Your active Xero OAuth2 access token.
# XERO_TENANT_ID: The Xero organization (tenant) ID you want to connect to.
# To obtain these, you must first complete the Xero OAuth2 authorization flow
# (involving redirecting a user to Xero for consent and obtaining tokens).
access_token = os.environ.get('XERO_ACCESS_TOKEN', '')
tenant_id = os.environ.get('XERO_TENANT_ID', '')

if not access_token:
    print("Error: Please set the XERO_ACCESS_TOKEN environment variable.")
    print("Refer to pyxero documentation for OAuth2 authorization flow details.")
    exit(1)
if not tenant_id:
    print("Error: Please set the XERO_TENANT_ID environment variable.")
    print("You can find the tenant ID after completing the OAuth2 authorization.")
    exit(1)

try:
    xero = Xero(tenant_id, access_token)

    # Example: Fetch the first 5 contacts
    contacts = xero.contacts.all()
    print(f"Successfully fetched {len(contacts)} contacts. Displaying first 5:")
    for i, contact in enumerate(contacts):
        if i >= 5:
            break
        print(f"- {contact.Name} (ID: {contact.ContactID})")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure your XERO_ACCESS_TOKEN and XERO_TENANT_ID are valid and have the necessary permissions.")

view raw JSON →