### Get Employee Opening Balances using Xero Python SDK Source: https://github.com/xeroapi/xero-python/blob/master/xero_python/payrolluk/docs/PayrollUkApi.md This code example demonstrates how to fetch opening balances for a specific employee via the Xero Python SDK. It outlines the necessary setup for the API client using OAuth2 and includes a try-except block for robust error handling. The required parameters are the Xero tenant ID and the employee ID. ```python from xero_python.api_client import Configuration, ApiClient from xero_python.api_client.oauth2 import OAuth2Token from xero_python.exceptions import ApiException from xero_python.payrolluk import PayrollUkApi from pprint import pprint # Configure OAuth2 access token for authorization: OAuth2 # simplified version, `xero_oauth2_token` represents permanent global token storage xero_oauth2_token = {} # set to valid xero oauth2 token dictionary # create client configuration with client id and client secret for automatic token refresh api_config = Configuration(oauth2_token=OAuth2Token( client_id="YOUR_API_CLIENT_ID", client_secret="YOUR_API_CLIENT_SECRET" )) # configure xero-python sdk client api_client = ApiClient( api_config, oauth2_token_saver=lambda x: xero_oauth2_token.update(x), oauth2_token_getter=lambda : xero_oauth2_token ) # create an instance of the API class api_instance = PayrollUkApi(api_client) xero_tenant_id = 'xero_tenant_id_example' # str | Xero identifier for Tenant employee_id = '4ff1e5cc-9835-40d5-bb18-09fdb118db9c' # str | Employee id for single object try: # Retrieves a specific employee's openingbalances using a unique employee ID api_response = api_instance.get_employee_opening_balances(xero_tenant_id, employee_id) pprint(api_response) except ApiException as e: print("Exception when calling PayrollUkApi->get_employee_opening_balances: %s\n" % e) ``` -------------------------------- ### GET /Folders Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/files/index.html Retrieves a list of folders, with options for sorting. ```APIDOC ## GET /Folders ### Description Retrieves a list of folders from the Xero API. Supports sorting based on creation date. ### Method GET ### Endpoint /Folders ### Parameters #### Header Parameters - **xero-tenant-id** (String) - Required - Xero identifier for Tenant. #### Query Parameters - **sort** (String) - Optional - Values to sort by (e.g., 'CreatedDateUTC DESC'). ### Request Example ```python # configure api_client for use with xero-python sdk client api_client = ApiClient( Configuration( debug=false, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_get_folders(): api_instance = FilesApi(api_client) xero_tenant_id = 'YOUR_XERO_TENANT_ID' sort = 'CreatedDateUTC DESC' try: api_response = api_instance.get_folders(xero_tenant_id, sort) print(api_response) except AccountingBadRequestException as e: print("Exception when calling FilesApi->getFolders: %s\n" % e) ``` ### Response #### Success Response (200) - **Folders** (Array) - A list of folder objects. - **Id** (UUID) - The unique identifier for the folder. - **Name** (String) - The name of the folder. - **CreatedDateUTC** (DateTime) - The date and time the folder was created (UTC). - **UpdatedDateUTC** (DateTime) - The date and time the folder was last updated (UTC). #### Response Example ```json { "Folders": [ { "Id": "bf924975-7097-46f2-a143-1ecfbab3c8c3", "Name": "Invoices", "CreatedDateUTC": "2023-10-27T10:00:00", "UpdatedDateUTC": "2023-10-27T10:00:00" } ] } ``` ### Scopes - files - files.read ``` -------------------------------- ### Configure Xero Python SDK Client and Get Reimbursement Source: https://github.com/xeroapi/xero-python/blob/master/xero_python/payrolluk/docs/PayrollUkApi.md This example demonstrates configuring the Xero Python SDK client with OAuth2 and then retrieving a specific reimbursement using its unique ID. It includes basic error handling. ```python from xero_python.api_client import Configuration, ApiClient from xero_python.api_client.oauth2 import OAuth2Token from xero_python.exceptions import ApiException from xero_python.payrolluk import PayrollUkApi from pprint import pprint # Configure OAuth2 access token for authorization: OAuth2 xero_oauth2_token = {} # set to valid xero oauth2 token dictionary api_config = Configuration(oauth2_token=OAuth2Token( client_id="YOUR_API_CLIENT_ID", client_secret="YOUR_API_CLIENT_SECRET" )) api_client = ApiClient( api_config, oauth2_token_saver=lambda x: xero_oauth2_token.update(x), oauth2_token_getter=lambda : xero_oauth2_token ) # create an instance of the API class api_instance = PayrollUkApi(api_client) xero_tenant_id = 'xero_tenant_id_example' # str | Xero identifier for Tenant reimbursement_id = 'reimbursement_id_example' # str | The Store ID try: api_response = api_instance.get_reimbursement(xero_tenant_id, reimbursement_id) pprint(api_response) except ApiException as e: print("Exception when calling PayrollUkApi->get_reimbursement: %s\n" % e) ``` -------------------------------- ### Folders API - Get Folders Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/files/index.html Retrieves a list of available folders. ```APIDOC ## GET /Folders ### Description Retrieves a list of all available folders within the Xero account. ### Method GET ### Endpoint /Folders ### Parameters #### Header Parameters - **xero-tenant-id** (String) - Required - The Xero identifier for the Tenant. ### Request Example ```python # configure api_client for use with xero-python sdk client api_client = ApiClient( Configuration( debug=false, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_get_folders(): api_instance = FilesApi(api_client) xero_tenant_id = 'YOUR_XERO_TENANT_ID' try: api_response = api_instance.get_folders(xero_tenant_id) print(api_response) except AccountingBadRequestException as e: print("Exception when calling FilesApi->getFolders: %s\n" % e) ``` ### Response #### Success Response (200) - A list of folders. #### Response Example ```json { "example": "[\n {\n \"id\": \"4ff1e5cc-9835-40d5-bb18-09fdb118db9c\",\n \"name\": \"Invoices\",\n \"createdDateUtc\": \"2023-10-27T10:00:00\",\n \"updatedDateUtc\": \"2023-10-27T10:00:00\",\n \"parentFolderId\": \"00000000-0000-0000-0000-000000000000\"\n },\n {\n \"id\": \"a1b2c3d4-e5f6-7890-1234-567890abcdef\",\n \"name\": \"Receipts\",\n \"createdDateUtc\": \"2023-10-26T09:00:00\",\n \"updatedDateUtc\": \"2023-10-26T09:00:00\",\n \"parentFolderId\": \"00000000-0000-0000-0000-000000000000\"\n }\n]" } ``` ``` -------------------------------- ### Files API - Get Files Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/files/index.html Retrieves a list of files, with options for pagination and sorting. ```APIDOC ## GET /Files ### Description Retrieves a list of files. Supports pagination and sorting options. ### Method GET ### Endpoint /Files ### Parameters #### Query Parameters - **pagesize** (Integer) - Optional - The number of records to return per page. - **page** (Integer) - Optional - The page number to retrieve. - **sort** (String) - Optional - The field to sort the results by (e.g., 'CreatedDateUTC'). - **direction** (String) - Optional - The direction of sorting ('ASC' or 'DESC'). #### Header Parameters - **xero-tenant-id** (String) - Required - The Xero identifier for the Tenant. ### Request Example ```python # configure api_client for use with xero-python sdk client api_client = ApiClient( Configuration( debug=false, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_get_files(): api_instance = FilesApi(api_client) xero_tenant_id = 'YOUR_XERO_TENANT_ID' sort = 'CreatedDateUTC' direction = 'ASC' try: api_response = api_instance.get_files(xero_tenant_id, pagesize, page, sort, direction) print(api_response) except AccountingBadRequestException as e: print("Exception when calling FilesApi->getFiles: %s\n" % e) ``` ### Response #### Success Response (200) - A list of files matching the query criteria. #### Response Example ```json { "example": "[\n {\n \"fileId\": \"4ff1e5cc-9835-40d5-bb18-09fdb118db9c\",\n \"name\": \"invoice.pdf\",\n \"id\": \"4ff1e5cc-9835-40d5-bb18-09fdb118db9c\",\n \"size\": 102400,\n \"mimeType\": \"application/pdf\",\n \"createdDateUtc\": \"2023-10-27T10:00:00\",\n \"updatedDateUtc\": \"2023-10-27T10:00:00\",\n \"folderId\": \"00000000-0000-0000-0000-000000000000\"\n }\n]" } ``` ``` -------------------------------- ### Configure API Client and Get Files List (Python) Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/files/index.html Shows how to set up the Xero API client and retrieve a list of files. It allows for sorting and pagination parameters to filter the results. The function requires the xero-tenant-id and can accept optional pagesize, page, sort, and direction parameters. ```python # configure api_client for use with xero-python sdk client api_client = ApiClient( Configuration( debug=false, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_get_files(): api_instance = FilesApi(api_client) xero_tenant_id = 'YOUR_XERO_TENANT_ID' sort = 'CreatedDateUTC' direction = 'ASC' try: api_response = api_instance.get_files(xero_tenant_id, pagesize, page, sort, direction) print(api_response) except AccountingBadRequestException as e: print("Exception when calling FilesApi->getFiles: %s\n" % e) ``` -------------------------------- ### Create Employee with Xero Python SDK Source: https://github.com/xeroapi/xero-python/blob/master/xero_python/payrolluk/docs/PayrollUkApi.md Shows how to create a new employee record in Xero using the Python SDK. It covers API client setup, instantiation, and the function call to create an employee, including an example of how to handle potential API exceptions. Requires `xero_python` library. ```python from xero_python.api_client import Configuration, ApiClient from xero_python.api_client.oauth2 import OAuth2Token from xero_python.exceptions import ApiException from xero_python.payrolluk import PayrollUkApi from pprint import pprint # Configure OAuth2 access token for authorization: OAuth2 # simplified version, `xero_oauth2_token` represents permanent global token storage xero_oauth2_token = {} # set to valid xero oauth2 token dictionary # create client configuration with client id and client secret for automatic token refresh api_config = Configuration(oauth2_token=OAuth2Token( client_id="YOUR_API_CLIENT_ID", client_secret="YOUR_API_CLIENT_SECRET" )) # configure xero-python sdk client api_client = ApiClient( api_config, oauth2_token_saver=lambda x: xero_oauth2_token.update(x), oauth2_token_getter=lambda : xero_oauth2_token ) # create an instance of the API class api_instance = PayrollUkApi(api_client) xero_tenant_id = 'xero_tenant_id_example' # str | Xero identifier for Tenant employee = {"title":"Mr","firstName":"Mike","lastName":"Fancy","dateOfBirth":"1999-01-01T00:00:00Z","gender":"M","email":"mike@starkindustries.com","isOffPayrollWorker":false,"address":{"addressLine1":"171 Midsummer","city":"Milton Keyness","postCode":"MK9 1EB"}} # Employee | idempotency_key = 'KEY_VALUE' # str | This allows you to safely retry requests without the risk of duplicate processing. 128 character max. (optional) try: # Creates employees api_response = api_instance.create_employee(xero_tenant_id, employee, idempotency_key=idempotency_key) pprint(api_response) except ApiException as e: print("Exception when calling PayrollUkApi->create_employee: %s\n" % e) ``` -------------------------------- ### Configure API Client and Get Folder Details (Python) Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/files/index.html Illustrates the process of configuring the Xero API client and retrieving details for a specific folder using its unique ID. The function requires the xero-tenant-id and folder_id and includes error handling for bad requests. ```python # configure api_client for use with xero-python sdk client api_client = ApiClient( Configuration( debug=false, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_get_folder(): api_instance = FilesApi(api_client) xero_tenant_id = 'YOUR_XERO_TENANT_ID' folder_id = '4ff1e5cc-9835-40d5-bb18-09fdb118db9c' try: api_response = api_instance.get_folder(xero_tenant_id, folder_id) print(api_response) except AccountingBadRequestException as e: print("Exception when calling FilesApi->getFolder: %s\n" % e) ``` -------------------------------- ### Configure API Client and Get File Content (Python) Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/files/index.html Demonstrates how to configure the ApiClient for the xero-python SDK and retrieve the content of a specific file using its ID. This function requires the xero-tenant-id and file_id as input and handles potential AccountingBadRequestException errors. ```python # configure api_client for use with xero-python sdk client api_client = ApiClient( Configuration( debug=false, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_get_file_content(): api_instance = FilesApi(api_client) xero_tenant_id = 'YOUR_XERO_TENANT_ID' file_id = '4ff1e5cc-9835-40d5-bb18-09fdb118db9c' try: api_response = api_instance.get_file_content(xero_tenant_id, file_id) print(api_response) except AccountingBadRequestException as e: print("Exception when calling FilesApi->getFileContent: %s\n" % e) ``` -------------------------------- ### Configure API Client and Get Pay Runs (Python) Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/payroll-au/index.html This example illustrates how to set up the ApiClient and retrieve a list of pay runs using the PayrollAuApi. It demonstrates authentication configuration and calling the 'get_pay_runs' method with optional filtering and sorting parameters. Error handling for bad requests is included. ```python # configure api_client for use with xero-python sdk client from xero_python.accounting import PayrollAuApi from xero_python.api_client import ApiClient, Configuration from xero_python.api_client.oauth2 import OAuth2Token import dateutil.parser api_client = ApiClient( Configuration( debug=False, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_get_pay_runs(): api_instance = PayrollAuApi(api_client) xero_tenant_id = 'xeroTenantId_example' if_modified_since = dateutil.parser.parse("2020-02-06T12:17:43.202-08:00") where = 'Status=="ACTIVE"' order = 'EmailAddress%20DESC' page = 1 # Example page number try: api_response = api_instance.get_pay_runs(xero_tenant_id, if_modified_since, where, order, page) print(api_response) except Exception as e: # Catching a broader exception for demonstration print(f"Exception when calling PayrollAuApi->getPayRuns: {e} ") ``` -------------------------------- ### Accessing Xero API Sets with Python SDK Source: https://github.com/xeroapi/xero-python/blob/master/README.md This example shows how to instantiate specific API clients (e.g., AccountingApi, AssetApi) using a configured ApiClient instance. It demonstrates the pattern for accessing different Xero services and making initial read calls. Dependencies include the ApiClient and relevant API classes. ```python from xero_python_sdk.api_client import ApiClient from xero_python_sdk.api.accounting import AccountingApi from xero_python_sdk.api.assets import AssetApi # Assume 'api_client' is an already configured ApiClient instance # and 'xero_tenant_id' is available # Mock ApiClient and xero_tenant_id for demonstration class MockApiClient: def __init__(self): pass api_client = MockApiClient() xero_tenant_id = "mock_tenant_id" # --- Example Usage --- accounting_api = AccountingApi(api_client) # Example call to get accounts, assuming api_client is properly initialized and authenticated # In a real scenario, this would be: # read_accounts = accounting_api.get_accounts(xero_tenant_id) # print(read_accounts) asset_api = AssetApi(api_client) # Example call to get assets, assuming api_client is properly initialized and authenticated # In a real scenario, this would be: # read_assets = asset_api.get_assets(xero_tenant_id) # print(read_assets) # ... all the API sets follow the same pattern # Example for another API set: # from xero_python_sdk.api.bankfeeds import BankFeedsApi # bankfeeds_api = BankFeedsApi(api_client) # read_bankfeeds = bankfeeds_api.get_bank_feeds(xero_tenant_id) # print(read_bankfeeds) ``` -------------------------------- ### Get Deduction using Xero Python SDK Source: https://github.com/xeroapi/xero-python/blob/master/xero_python/payrollnz/docs/PayrollNZApi.md Illustrates how to retrieve a single deduction by its ID using the Xero Python SDK. This example includes the necessary OAuth2 setup and API client configuration. ```python from xero_python.api_client import Configuration, ApiClient from xero_python.api_client.oauth2 import OAuth2Token from xero_python.exceptions import ApiException from xero_python.payrollnz import PayrollNzApi from pprint import pprint # Configure OAuth2 access token for authorization: OAuth2 # simplified version, `xero_oauth2_token` represents permanent global token storage xero_oauth2_token = {} # set to valid xero oauth2 token dictionary # create client configuration with client id and client secret for automatic token refresh api_config = Configuration(oauth2_token=OAuth2Token( client_id="YOUR_API_CLIENT_ID", client_secret="YOUR_API_CLIENT_SECRET" )) # configure xero-python sdk client api_client = ApiClient( api_config, oauth2_token_saver=lambda x: xero_oauth2_token.update(x), oauth2_token_getter=lambda : xero_oauth2_token ) # create an instance of the API class api_instance = PayrollNzApi(api_client) xero_tenant_id = 'xero_tenant_id_example' # str | Xero identifier for Tenant deduction_id = 'deduction_id_example' # str | The Xero identifier for the Deduction try: # Retrieves a single deduction by using a unique deduction ID api_response = api_instance.get_deduction(xero_tenant_id, deduction_id) pprint(api_response) except ApiException as e: print("Exception when calling PayrollNzApi->get_deduction: %s\n" % e) ``` -------------------------------- ### GET /Inbox Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/files/index.html Retrieves the inbox folder for the user. ```APIDOC ## GET /Inbox ### Description Retrieves the inbox folder for the authenticated user. This is a system-defined folder. ### Method GET ### Endpoint /Inbox ### Parameters #### Header Parameters - **xero-tenant-id** (String) - Required - Xero identifier for Tenant. ### Request Example ```python # configure api_client for use with xero-python sdk client api_client = ApiClient( Configuration( debug=false, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_get_inbox(): api_instance = FilesApi(api_client) xero_tenant_id = 'YOUR_XERO_TENANT_ID' try: api_response = api_instance.get_inbox(xero_tenant_id) print(api_response) except AccountingBadRequestException as e: print("Exception when calling FilesApi->getInbox: %s\n" % e) ``` ### Response #### Success Response (200) - **Id** (UUID) - The unique identifier for the inbox folder. - **Name** (String) - The name of the folder (typically 'Inbox'). - **CreatedDateUTC** (DateTime) - The date and time the inbox was created (UTC). - **UpdatedDateUTC** (DateTime) - The date and time the inbox was last updated (UTC). #### Response Example ```json { "Id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "Name": "Inbox", "CreatedDateUTC": "2023-10-27T10:00:00", "UpdatedDateUTC": "2023-10-27T10:00:00" } ``` ### Scopes - files - files.read ``` -------------------------------- ### Xero Custom Connections Setup Source: https://github.com/xeroapi/xero-python/blob/master/README.md Demonstrates the setup for using Xero's Custom Connections with the Python SDK. This method uses the `client_credentials` grant type, suitable for M2M integrations, and bypasses the user authorization step. ```python # -*- coding: utf-8 -*- import os from functools import wraps from io import BytesIO from logging.config import dictConfig from flask import Flask, url_for, render_template, session, redirect, json, send_file from flask_session import Session from xero_python.accounting import AccountingApi, ContactPerson, Contact, Contacts from xero_python.api_client import ApiClient, serialize from xero_python.api_client.configuration import Configuration from xero_python.api_client.oauth2 import OAuth2Token from xero_python.exceptions import AccountingBadRequestException from xero_python.identity import IdentityApi from xero_python.utils import getvalue import logging_settings from utils import jsonify, serialize_model dictConfig(logging_settings.default_settings) # Example initialization for Custom Connections (client_credentials grant) # Replace with your actual client ID and client secret xero_client = ApiClient( client_id=os.environ.get("XERO_CLIENT_ID"), client_secret=os.environ.get("XERO_CLIENT_SECRET"), # For custom connections, you might not need a redirect_uri or authorize endpoint # but the ApiClient initialization might still require these parameters depending on SDK version redirect_uri="YOUR_REDIRECT_URI", # This might be a dummy URI for client_credentials # The token endpoint is crucial for client_credentials flow token_endpoint="https://identity.xero.com/connect/token" ) # You would then use xero_client to make API calls without user interaction # For example, to get a token using client_credentials: # token = xero_client.get_token_by_credentials() # xero_client.set_token(token) # Subsequent API calls would be similar to the standard OAuth2 flow, but using the token obtained via client_credentials ``` -------------------------------- ### Configure Xero Python SDK and Upload File Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/files/index.html This example demonstrates configuring the Xero Python SDK client and uploading a file. It requires setting up the `ApiClient` with OAuth2 credentials, then calling the `upload_file` method with necessary parameters like tenant ID, file content, name, filename, idempotency key, and MIME type. Error handling for `AccountingBadRequestException` is included. ```python from xero_python_sdk.api import FilesApi from xero_python_sdk.configuration import Configuration from xero_python_sdk.api_client import ApiClient from xero_python_sdk.models.oauth2 import OAuth2Token from xero_python_sdk.exceptions import AccountingBadRequestException # configure api_client for use with xero-python sdk client api_client = ApiClient( Configuration( debug=False, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_upload_file(): api_instance = FilesApi(api_client) xero_tenant_id = 'YOUR_XERO_TENANT_ID' name = 'name_example' filename = 'filename_example' idempotency_key = 'KEY_VALUE' mimeType = 'mimeType_example' # Assume 'body' is the byte content of the file body = b'file content' try: api_response = api_instance.upload_file(xero_tenant_id, body, name, filename, idempotency_key, mimeType) print(api_response) except AccountingBadRequestException as e: print("Exception when calling FilesApi->uploadFile: %s\n" % e) ``` -------------------------------- ### GET /Associations/{ObjectId} Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/files/index.html Retrieves association objects linked to a specific object ID. ```APIDOC ## GET /Associations/{ObjectId} ### Description Retrieves association objects linked to a specific object ID. ### Method GET ### Endpoint /Associations/{ObjectId} ### Parameters #### Path Parameters - **ObjectId** (uuid) - Required - Object id for single object #### Query Parameters - **pagesize** (integer) - Optional - Pass an optional page size value - **page** (integer) - Optional - Number of records to skip for pagination - **sort** (string) - Optional - Values to sort by (e.g., 'CreatedDateUtc') - **direction** (string) - Optional - Direction to sort by (e.g., 'DESC') #### Header Parameters - **xero-tenant-id** (string) - Required - Xero identifier for Tenant ### Request Example ```python # configure api_client for use with xero-python sdk client api_client = ApiClient( Configuration( debug=false, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_get_associations_by_object(): api_instance = FilesApi(api_client) xero_tenant_id = 'YOUR_XERO_TENANT_ID' object_id = '4ff1e5cc-9835-40d5-bb18-09fdb118db9c' sort = 'CreatedDateUtc' direction = 'DESC' pagesize = 10 page = 1 try: api_response = api_instance.get_associations_by_object(xero_tenant_id, object_id, pagesize, page, sort, direction) print(api_response) except AccountingBadRequestException as e: print("Exception when calling FilesApi->getAssociationsByObject: %s\n" % e) ``` ### Response #### Success Response (200) - **Associations** (array) - A list of association objects. - **Object** (object) - Details of the associated object. - **Id** (uuid) - The unique identifier of the object. - **Type** (string) - The type of the object (e.g., 'Contact', 'Invoice'). - **File** (object) - Details of the associated file. - **Id** (uuid) - The unique identifier of the file. - **Name** (string) - The name of the file. - **CreatedDateUtc** (string) - The UTC date and time the file was created. - **MimeType** (string) - The MIME type of the file. - **Size** (integer) - The size of the file in bytes. #### Response Example ```json { "Associations": [ { "Object": { "Id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "Type": "Contact" }, "File": { "Id": "4ff1e5cc-9835-40d5-bb18-09fdb118db9c", "Name": "document.pdf", "CreatedDateUtc": "2023-10-27T10:00:00", "MimeType": "application/pdf", "Size": 102400 } } ] } ``` ``` -------------------------------- ### Configure Xero Python SDK Client and Fetch App Store Subscription Source: https://github.com/xeroapi/xero-python/blob/master/README.md This snippet demonstrates how to initialize the Xero API client with OAuth2 token details and then fetch subscription information from the App Store API. It includes error handling for token retrieval. The input includes application configuration for client ID and secret, and the output is a subscription object. ```python from xero_python_sdk.api_client import ApiClient from xero_python_sdk.configuration import Configuration from xero_python_sdk.oauth2 import OAuth2Token from xero_python_sdk.api.app_store import AppStoreApi # Assuming 'app' is a Flask or similar application object # and 'session' is available for token storage # Placeholder for Flask app configuration and session class MockAppConfig: def __init__(self): self.DEBUG = True self.CLIENT_ID = "YOUR_CLIENT_ID" self.CLIENT_SECRET = "YOUR_CLIENT_SECRET" class MockSession: def __init__(self): self._data = {} self.modified = False def get(self, key): return self._data.get(key) def __setitem__(self, key, value): self._data[key] = value self.modified = True app = type('obj', (object,), {"config": MockAppConfig()})() session = MockSession() # configure xero-python sdk client api_client = ApiClient( Configuration( debug=app.config["DEBUG"], oauth2_token=OAuth2Token( client_id=app.config["CLIENT_ID"], client_secret=app.config["CLIENT_SECRET"] ), ), pool_threads=1, ) # Mock function to simulate token storage/retrieval def get_token_set_from_database(user_id): # In a real app, this would fetch from a database return session.get("token") def store_xero_oauth2_token(token): session["token"] = token session.modified = True @api_client.oauth2_token_getter def obtain_xero_oauth2_token(): return session.get("token") @api_client.oauth2_token_saver def store_xero_oauth2_token_callback(token): session["token"] = token session.modified = True # --- Example Usage --- # This part assumes you have a valid token set already stored or obtained # For demonstration, let's simulate storing a token first initial_token = { "access_token": "mock_access_token", "expires_in": 3600, "token_type": "Bearer", "refresh_token": "mock_refresh_token", "id_token": "mock_id_token" } store_xero_oauth2_token(initial_token) try: # pass True for app_store_billing - defaults to False if no value provided # In a real scenario, subscription_id would be obtained from context or webhook subscription_id = 'a-valid-subscription-id' xero_token = api_client.get_client_credentials_token(True) # This might not be the correct method for app store, review SDK docs # Assuming get_client_credentials_token returns something usable or is a placeholder # For actual app store subscription, you'd likely use AppStoreApi directly after token refresh # Refresh token if necessary (often done automatically by SDK or explicitly) # api_client.refresh_oauth2_token() # Example of explicit refresh if needed app_store_api = AppStoreApi(api_client) subscription = app_store_api.get_subscription(subscription_id) print(subscription) except Exception as e: print(f"An error occurred: {e}") # In a real application, you'd handle specific exceptions and potentially re-authenticate raise # Example of how the subscription data might look (as provided in the text) # Note: This is a representation, the actual output is a Python object. # { # 'current_period_end': datetime.datetime(2021, 9, 2, 14, 8, 58, 772536, tzinfo=tzutc()), # 'end_date': None, # 'id': '03bc74f2-1237-4477-b782-2dfb1a6d8b21', # 'organisation_id': '79e8b2e5-c63d-4dce-888f-e0f3e9eac647', # 'plans':[ # { # 'id': '6abc26f3-9390-4194-8b25-ce8b9942fda9', # 'name': 'Small', # 'status': 'ACTIVE', # 'subscription_items': [ # { # 'end_date': None, # 'id': '834cff4c-b753-4de2-9e7a-3451e14fa17a', # 'price': { # 'amount': Decimal('0.1000'), # 'currency': 'NZD', # 'id': '2310de92-c7c0-4bcb-b972-fb7612177bc7' # }, # 'product': { # 'id': '9586421f-7325-4493-bac9-d93be06a6a38', # 'name': '', # 'type': 'FIXED', # 'seat_unit': None # }, # 'start_date': datetime.datetime(2021, 8, 2, 14, 8, 58, 772536, tzinfo=tzutc()), # 'test_mode': True # } # ] # } # ], # 'start_date': datetime.datetime(2021, 8, 2, 14, 8, 58, 772536, tzinfo=tzutc()), # 'status': 'ACTIVE', # 'test_mode': True # } ``` -------------------------------- ### Files API - Get File Content Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/files/index.html Retrieves the content of a specific file using its file ID. ```APIDOC ## GET /Files/{FileId} ### Description Retrieves the content of a specific file by its unique File ID. ### Method GET ### Endpoint /Files/{FileId} ### Parameters #### Path Parameters - **FileId** (uuid) - Required - The unique identifier for the file. #### Header Parameters - **xero-tenant-id** (String) - Required - The Xero identifier for the Tenant. ### Request Example ```python # configure api_client for use with xero-python sdk client api_client = ApiClient( Configuration( debug=false, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_get_file_content(): api_instance = FilesApi(api_client) xero_tenant_id = 'YOUR_XERO_TENANT_ID' file_id = '4ff1e5cc-9835-40d5-bb18-09fdb118db9c' try: api_response = api_instance.get_file_content(xero_tenant_id, file_id) print(api_response) except AccountingBadRequestException as e: print("Exception when calling FilesApi->getFileContent: %s\n" % e) ``` ### Response #### Success Response (200) - The content of the file. #### Response Example (Binary content of the file) ``` -------------------------------- ### Create Earnings Rate with Xero Python SDK Source: https://github.com/xeroapi/xero-python/blob/master/xero_python/payrolluk/docs/PayrollUkApi.md Demonstrates how to create a new earnings rate in Xero using the Python SDK. It includes client configuration, API instantiation, and the call to create the earnings rate, along with basic error handling. Requires `xero_python` library. ```python from xero_python.api_client import Configuration, ApiClient from xero_python.api_client.oauth2 import OAuth2Token from xero_python.exceptions import ApiException from xero_python.payrolluk import PayrollUkApi from pprint import pprint # Configure OAuth2 access token for authorization: OAuth2 # simplified version, `xero_oauth2_token` represents permanent global token storage xero_oauth2_token = {} # set to valid xero oauth2 token dictionary # create client configuration with client id and client secret for automatic token refresh api_config = Configuration(oauth2_token=OAuth2Token( client_id="YOUR_API_CLIENT_ID", client_secret="YOUR_API_CLIENT_SECRET" )) # configure xero-python sdk client api_client = ApiClient( api_config, oauth2_token_saver=lambda x: xero_oauth2_token.update(x), oauth2_token_getter=lambda : xero_oauth2_token ) # create an instance of the API class api_instance = PayrollUkApi(api_client) xero_tenant_id = 'xero_tenant_id_example' # str | Xero identifier for Tenant earnings_rate = {"name":"My Earnings Rate","earningsType":"RegularEarnings","rateType":"RatePerUnit","typeOfUnits":"hours","expenseAccountID":"4b03500d-32fd-4616-8d70-e1e56e0519c6"} # EarningsRate | idempotency_key = 'KEY_VALUE' # str | This allows you to safely retry requests without the risk of duplicate processing. 128 character max. (optional) try: # Creates a new earnings rate api_response = api_instance.create_earnings_rate(xero_tenant_id, earnings_rate, idempotency_key=idempotency_key) pprint(api_response) except ApiException as e: print("Exception when calling PayrollUkApi->create_earnings_rate: %s\n" % e) ``` -------------------------------- ### Files API - Get File Associations Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/files/index.html Retrieves specific file associations by providing the file ID. ```APIDOC ## GET /Files/{FileId}/Associations ### Description Retrieves specific file associations by providing the file ID. This endpoint is part of the Files API. ### Method GET ### Endpoint /Files/{FileId}/Associations ### Parameters #### Path Parameters - **FileId** (UUID) - Required - The unique ID of the file for which to retrieve associations. #### Header Parameters - **xero-tenant-id** (String) - Required - Xero identifier for Tenant ### Request Example ```python # configure api_client for use with xero-python sdk client api_client = ApiClient( Configuration( debug=false, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_get_file_associations(): api_instance = FilesApi(api_client) xero_tenant_id = 'YOUR_XERO_TENANT_ID' file_id = '4ff1e5cc-9835-40d5-bb18-09fdb118db9c' try: api_response = api_instance.get_file_associations(xero_tenant_id, file_id) print(api_response) except AccountingBadRequestException as e: print("Exception when calling FilesApi->getFileAssociations: %s\n" % e) ``` ### Response #### Success Response (200) - **associations** (array) - A list of associations for the file. - Each association object may contain properties like `type`, `id`, `name`. #### Response Example ```json { "associations": [ { "type": "INVOICE", "id": "f1a2b3c4-d5e6-7f8f-8a9b-0c1d2e3f4a5b", "name": "INV-0001" } ] } ``` ``` -------------------------------- ### Create Pay Run - Python Source: https://github.com/xeroapi/xero-python/blob/master/xero_python/payrollnz/docs/PayrollNZApi.md This snippet demonstrates how to create a new pay run using the Xero Python SDK. It requires the tenant ID and pay run details, including calendar information, period dates, and payment date. An optional idempotency key can be provided for safe retries. ```python from xero_python.api_client import Configuration, ApiClient from xero_python.api_client.oauth2 import OAuth2Token from xero_python.exceptions import ApiException from xero_python.payrollnz import PayrollNzApi from pprint import pprint # Configure OAuth2 access token for authorization: OAuth2 # simplified version, `xero_oauth2_token` represents permanent global token storage xero_oauth2_token = {} # set to valid xero oauth2 token dictionary # create client configuration with client id and client secret for automatic token refresh api_config = Configuration(oauth2_token=OAuth2Token( client_id="YOUR_API_CLIENT_ID", client_secret="YOUR_API_CLIENT_SECRET" )) # configure xero-python sdk client api_client = ApiClient( api_config, oauth2_token_saver=lambda x: xero_oauth2_token.update(x), oauth2_token_getter=lambda : xero_oauth2_token ) # create an instance of the API class api_instance = PayrollNzApi(api_client) xero_tenant_id = 'xero_tenant_id_example' # str | Xero identifier for Tenant pay_run = {"payrollCalendarID":"9aa56064-990f-4ad3-a189-d966d8f6a030","periodStartDate":"2020-09-08","periodEndDate":"2020-09-15","paymentDate":"2020-09-20","payRunStatus":"Draft","payRunType":"Scheduled","calendarType":"Weekly"} # PayRun | idempotency_key = 'KEY_VALUE' # str | This allows you to safely retry requests without the risk of duplicate processing. 128 character max. (optional) try: # Creates a pay run api_response = api_instance.create_pay_run(xero_tenant_id, pay_run, idempotency_key=idempotency_key) pprint(api_response) except ApiException as e: print("Exception when calling PayrollNzApi->create_pay_run: %s\n" % e) ``` -------------------------------- ### Files API - Get Associations Count Source: https://github.com/xeroapi/xero-python/blob/master/docs/v1/files/index.html Retrieves the number of associations for a given set of file object IDs. ```APIDOC ## GET /Files/Associations/Count ### Description Retrieves the number of associations for a given set of file object IDs. This endpoint is part of the Files API. ### Method GET ### Endpoint /Files/Associations/Count ### Parameters #### Header Parameters - **xero-tenant-id** (String) - Required - Xero identifier for Tenant #### Query Parameters - **objectIds** (array[UUID]) - Required - A comma-separated list of object IDs. ### Request Example ```python # configure api_client for use with xero-python sdk client api_client = ApiClient( Configuration( debug=false, oauth2_token=OAuth2Token( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET" ), ), pool_threads=1, ) api_client.set_oauth2_token("YOUR_ACCESS_TOKEN") def accounting_get_associations_count(): api_instance = FilesApi(api_client) xero_tenant_id = 'YOUR_XERO_TENANT_ID' objectIds = [] try: api_response = api_instance.get_associations_count(xero_tenant_id, objectIds) print(api_response) except AccountingBadRequestException as e: print("Exception when calling FilesApi->getAssociationsCount: %s\n" % e) ``` ### Response #### Success Response (200) - **status** (String) - The status of the operation. - **total** (Integer) - The total number of associations found. #### Response Example ```json { "status": "OK", "total": 5 } ``` ```