Saltar a contenido

Cliente y errores

AlegraClient es el punto de entrada recomendado. Los errores se describen en la página de Excepciones y en la guía de errores.

alegrapy.session.AlegraClient

The main client interface for interacting with the Alegra API.

Allows managing multiple API sessions with different credentials.

Thread safety

Safe: any number of threads may send requests through the same client, and several clients with different credentials may be used at the same time. Every request builds its own Authorization header from the client it was sent through, and the shared connection pool never stores credentials or cookies.

Not safe: changing a client's configuration (user, token, url, timeout, retry) while other threads are using it. Configure the client first, then share it.

Resource attributes (client.contacts, client.invoices, ...) may be accessed for the first time from any thread. A concurrent first access can build two equivalent, stateless resource objects bound to the same client; this is benign.

Not safe for multiple tenants: the legacy global session and the module-level resources keep process-wide credentials. Multi-tenant applications must create one AlegraClient per tenant.

contacts property

Access Contacts resource operations.

invoices property

Access Invoices resource operations.

credit_notes property

Access Credit Notes resource operations.

payments property

Access Payments resource operations.

items property

Access Items resource operations.

estimates property

Access Estimates resource operations.

purchase_orders property

Access Purchase Orders resource operations.

bank_accounts property

Access Bank Accounts resource operations.

taxes property

Access Taxes resource operations.

currencies property

Access Currencies resource operations.

retentions property

Access Retentions resource operations.

users property

Access Users resource operations.

number_templates property

Access NumberTemplates resource operations.

company property

Access Company singleton resource operations.

income_debit_notes property

Access IncomeDebitNotes resource operations.

webhooks property

Access Webhooks subscription resource operations.

bills property

Access Bills (supplier bills) resource operations.

debit_notes property

Access DebitNotes (supplier debit notes) resource operations.

remissions property

Access Remissions resource operations.

warehouses property

Access Warehouses resource operations.

price_lists property

Access PriceLists resource operations.

item_categories property

Access ItemCategories resource operations.

terms property

Access Terms resource operations.

inventory_adjustments property

Access InventoryAdjustments resource operations.

user property writable

Get the effective username/email (the client's own pair, else the global session's).

token property writable

Get the effective API token (the client's own pair, else the global session's).

url property writable

Get the base API URL (always with exactly one trailing slash).

timeout property writable

Get the request timeout in seconds.

retry property writable

Get the retry policy (the client's own, else the global session's).

__init__(user=None, token=None, url=None, timeout=None, retry=None)

Initialize the client.

Parameters:

Name Type Description Default
user str

Alegra username (email).

None
token str

Alegra API token.

None
url str

Custom base API URL. Must use https (http only for loopback hosts). Defaults to DEFAULT_BASE_URL ('https://api.alegra.com/api/v1/').

None
timeout float

Request timeout in seconds. Defaults to the global session timeout (30).

None
retry RetryPolicy

Retry policy. Defaults to the global session policy (RetryPolicy() when unset).

None

Raises:

Type Description
ValueError

If url is given and is not a valid https (or loopback http) URL.

get_auth_header()

Generate the Basic Authorization header string from credentials.

Returns:

Name Type Description
str str

Basic authorization header, or empty string if credentials are missing.

query(method, url, data=None, params=None, files=None)

Perform an HTTP request to the Alegra API and handle errors.

Parameters:

Name Type Description Default
method str

HTTP method (get, post, put, delete)

required
url str

Full endpoint URL

required
data dict

Request body payload. Defaults to None.

None
params dict

Query parameters. Defaults to None.

None
files dict

Files for multipart uploads. Defaults to None.

None

Returns:

Name Type Description
Any Any

Parsed JSON response from server (dict, list, or empty dict/value).

A DELETE that returns 404 on a retry is treated as success and returns {} only when any earlier attempt may have been processed (a timeout, an ambiguous connection error or a 5xx). After only 429s or provably unsent requests, the 404 is a genuine not-found and raises AlegraNotFoundError.

Raises:

Type Description
AlegraAPIError

If the server returns a non-2xx status code or a request error occurs (transport errors chain the original exception as __cause__). Typed subclasses are raised for known HTTP statuses and transport failures. Only requests.RequestException failures are wrapped: other exceptions, such as a payload that cannot be JSON-serialized, propagate unchanged. When retries are enabled, the error raised is the one from the last attempt.

ValueError

If the resolved base URL is not https (or loopback http); nothing is sent.

close()

Close the underlying HTTP session and release pooled connections.

Safe to call more than once. The client must not be reused after closing it; requests may silently reopen pools, which is unsupported behavior.

__enter__()

Return the client so it can be used in a with block.

__exit__(exc_type, exc, traceback)

Close the client when leaving a with block; never swallow exceptions.

Modo legacy

Clase de configuración global conservada por compatibilidad. Ver Migración desde el modo legacy.

alegrapy.session.session

Legacy compatibility class representing global session configurations.

create_auth() classmethod

Deprecated no-op retained for compatibility; never stores credentials.

query(method, url, data=None, params=None, files=None) classmethod

Perform a query using the legacy global credentials.

Delegates to the global default client.