Skip to main content

AlegraPy

Tests

Cliente de Python para la API de Alegra (facturación y contabilidad). Permite trabajar con varias empresas a la vez, maneja errores y reintentos de forma segura y evita facturas duplicadas por reintentos ciegos.

Proyecto no oficial. AlegraPy es una librería comunitaria, sin relación con Alegra. La referencia oficial de la API está en https://developer.alegra.com/.

Documentación completa: https://camilordz1.github.io/alegrapy/

Inicio rápido

  1. Instala el paquete desde PyPI (se importa como alegrapy):

    pip install AlegraPy
    

    Hasta la 1.0 se recomienda fijar la serie: pip install "AlegraPy>=0.1,<0.2".

  2. Obtén tus credenciales en Alegra: Configuración → API - Integraciones con otros sistemas (correo y token).

  3. Crea un cliente y consulta:

    import os
    from alegrapy import AlegraClient
    
    with AlegraClient(user=os.environ["ALEGRA_USER"], token=os.environ["ALEGRA_TOKEN"]) as client:
        contacto = client.contacts.read(126)
        print(contacto["name"])
    

Probado en Python 3.10, 3.11, 3.12 y 3.13.

Qué incluye

Necesidad Cómo se resuelve Guía
Varias empresas en el mismo proceso Un AlegraClient por empresa; se puede compartir entre hilos sin mezclar credenciales Concurrencia
Distinguir el tipo de error Excepciones tipadas: AlegraNotFoundError, AlegraAuthError, AlegraRateLimitError, AlegraServerError, AlegraTimeoutError... Todas heredan de AlegraAPIError Errores
Fallas transitorias Reintentos automáticos con backoff y Retry-After; un POST solo se reintenta si la petición seguro no salió Reintentos
Recorrer todos los registros iter_all() pagina sola, sin cargar todo en memoria Paginación
Buscar por NIT o SKU contacts.find_by_identification() e items.find_by_reference() con coincidencia exacta Búsquedas
Conexiones seguras HTTPS obligatorio, IDs validados y logs sin cuerpos ni tokens Seguridad

Ejemplos

Los ejemplos siguientes usan un cliente abierto. Créalo sin with (y llama a client.close() al terminar) o escribe el código dentro del bloque with del inicio rápido:

import os
from alegrapy import AlegraClient

client = AlegraClient(user=os.environ["ALEGRA_USER"], token=os.environ["ALEGRA_TOKEN"])

Recorrer todo el inventario activo:

for item in client.items.iter_all(status="active"):
    print(item["id"], item["name"])

Buscar un cliente por identificación (devuelve una lista: puede haber duplicados):

contactos = client.contacts.find_by_identification("900.559.088")

Manejar errores por tipo:

from alegrapy import AlegraNotFoundError, AlegraServerError

try:
    factura = client.invoices.read(11742)
except AlegraNotFoundError:
    factura = None
except AlegraServerError:
    ...  # Alegra no está disponible: reintenta más tarde

Antes de crear facturas o pagos

Un timeout o una conexión cortada al crear un registro es ambiguo: la factura pudo crearse en Alegra aunque recibas un error. El SDK nunca reintenta ese caso por su cuenta. Antes de volver a crear, revisa err.request_not_sent:

from alegrapy import AlegraAPIError

try:
    client.invoices.create(datos)
except AlegraAPIError as err:
    if err.request_not_sent:
        ...  # seguro: la petición nunca llegó a Alegra, puedes reintentar
    else:
        ...  # márcala como "pendiente de verificar"; no la crees otra vez a ciegas

Para facturas, client.invoices.create_once(datos, dedup_key=...) automatiza esa verificación y ofrece una cuarentena serializable; ver Facturas sin duplicados.

Recursos disponibles

Recurso Propiedad Operaciones extra
Facturas de venta client.invoices void, open, send_email, annul, get_pdf, download_pdf, get_xml, download_xml
Notas crédito client.credit_notes annul en client.invoices
Contactos client.contacts find_by_identification, add_attachment
Productos / ítems client.items find_by_reference, add_attachment
Pagos client.payments void, open
Cotizaciones client.estimates void, open, send_email
Órdenes de compra client.purchase_orders send_email, add_comment
Cuentas bancarias client.bank_accounts transfer
Impuestos, monedas, retenciones client.taxes, client.currencies, client.retentions —
Usuarios client.users self_info

Todos tienen list, read, create, update, delete e iter_all. El detalle está en la guía de recursos.

Modo legacy

El estilo antiguo con la sesión global (from alegrapy import session) sigue disponible, pero comparte credenciales en todo el proceso: no lo uses con varias empresas. Ver Migración desde el modo legacy.

Desarrollo

pip install -r requirements-dev.txt
python -m pytest tests/ -q

pip install -r requirements-docs.txt
mkdocs serve

Versiones y cambios

Consulta CHANGELOG.md y la guía de Versiones y cambios (política de Semantic Versioning y qué esperar antes de 1.0.0). Se recomienda fijar AlegraPy>=0.1,<0.2.

Licencia

MIT. Ver LICENSE.txt.

Metadata

Release files for AlegraPy 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for AlegraPy 0.1.0
File Size Uploaded Provenance Actions
alegrapy-0.1.0.tar.gz 38.7 kB With provenance Details for alegrapy-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for AlegraPy 0.1.0
File Interpreter ABI Platform Actions
alegrapy-0.1.0-py3-none-any.whl Python 3 none any Details for alegrapy-0.1.0-py3-none-any.whl

Total release size: 86.3 kB

Release files / alegrapy-0.1.0.tar.gz

Download URL alegrapy-0.1.0.tar.gz
Size 38.7 kB
Tags Source
SHA-256 checksum
How to use checksums
53c013d7ffdca0f023af887335a4242ac203faf5061c7f42e75ac7cb878dbcfb
BLAKE2b-256 checksum
How to use checksums
cc252b660cbb87362b28b6622205b3ee2eee98a1981c896c52422aefdf5a92a2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Release files / alegrapy-0.1.0-py3-none-any.whl

Download URL alegrapy-0.1.0-py3-none-any.whl
Size 47.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ba84f43bdf5a416450a1139a2dec575884cf72a3f60065147c5a0cd0235e89c7
BLAKE2b-256 checksum
How to use checksums
4cea26ef8f63e8e6f7aeab6c5412e22e0bd5372a6ba9a593bd7517a49cdebd4d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Security for AlegraPy 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for alegrapy-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page