Skip to main content

intifact-sdk (Python)

SDK Python para la API de Facturación Electrónica SUNAT de Intifact (Perú), generado con OpenAPI Generator desde el spec que la API expone en /docs/json. Facturas, boletas, notas de crédito/débito, guías de remisión (remitente y transportista), resúmenes diarios y comunicaciones de baja.

Requisitos

Python 3.10+

Instalación

pip install intifact

Autenticación

La API no está modelada con un securityScheme de OpenAPI (el chequeo de API key vive en un plugin de Fastify), así que el header se agrega a mano — el cliente lo manda en cada request a partir de ahí:

import intifact_sdk
from intifact_sdk import ApiClient, Configuration

config = Configuration(host="https://api-facturacion.intifact.com")
client = ApiClient(config)
client.set_default_header("Authorization", f"Bearer {os.environ['FACTURACION_API_KEY']}")

Uso básico — enviar una factura

import os
from intifact_sdk import ApiClient, Configuration, ApiException
from intifact_sdk.api.invoice_api import InvoiceApi
from intifact_sdk.models.api_v1_invoice_send_post_request import ApiV1InvoiceSendPostRequest
from intifact_sdk.models.api_v1_invoice_send_post_request_detalle_inner import (
    ApiV1InvoiceSendPostRequestDetalleInner,
)

config = Configuration(host="https://api-facturacion.intifact.com")
with ApiClient(config) as client:
    client.set_default_header("Authorization", f"Bearer {os.environ['FACTURACION_API_KEY']}")
    invoice_api = InvoiceApi(client)

    item = ApiV1InvoiceSendPostRequestDetalleInner(
        unidad="NIU",
        cantidad=2,
        cod_producto="PROD001",
        descripcion="Laptop HP 15",
        monto_valor_unitario=2500.00,
        monto_base_igv=5000.00,
        porcentaje_igv=18,
        igv=900.00,
        tip_afe_igv="10",
        total_impuestos=900.00,
        monto_precio_unitario=2950.00,
        monto_valor_venta=5000.00,
        # Código de Producto SUNAT (UNSPSC) — SUNAT lo exige desde 2027-01-01
        # para determinados bienes (error 3496 si falta o es inválido).
        cod_prod_sunat="43211508",
    )

    body = ApiV1InvoiceSendPostRequest(
        empresa_ruc="20553510661",
        tipo_doc="01",
        serie="F001",
        correlativo="100",
        tipo_moneda="PEN",
        fecha_emision="2026-01-15",
        tipo_operacion="0101",
        cliente_tipo_doc="6",
        cliente_num_doc="20000000001",
        cliente_razon_social="EMPRESA CLIENTE SAC",
        detalle=[item],
        monto_oper_gravadas=5000.00,
        monto_oper_exoneradas=0,
        monto_igv=900.00,
        total_impuestos=900.00,
        valor_venta=5000.00,
        sub_total=5900.00,
        monto_imp_venta=5900.00,
        forma_pago=[{"tipo": "Contado", "monto": 5900.00, "fechaPago": "2026-01-15"}],
        leyendas=[{"legendCode": "1000", "legendValue": "CINCO MIL NOVECIENTOS CON 00/100 SOLES"}],
    )

    try:
        resp = invoice_api.api_v1_invoice_send_post(body)
        # 202 — el documento queda ENCOLADO, SUNAT lo procesa en background
        print("Encolado:", resp.data.id)
    except ApiException as e:
        # El body real del error (400/401/409/...) viene en e.body
        print(f"Error {e.status}: {e.body}")

Notas:

  • Los campos usan snake_case en Python (cod_producto) aunque el JSON que viaja por HTTP sigue siendo camelCase (codProducto) — Pydantic hace la conversión con alias automáticamente.
  • Pydantic valida los modelos al construirlos, antes de cualquier llamada de red: si falta un campo requerido (ej. forma_pago, leyendas), obtienes un ValidationError local en vez de esperar un 400 del servidor. Es una ventaja real del SDK Python frente a mandar un dict suelto.

Manejo de errores

Toda respuesta fuera de 2xx llega como ApiException (no como excepción genérica de red): e.status trae el código HTTP y e.body el JSON crudo { success: false, message, errors? } que devuelve la API.

try:
    invoice_api.api_v1_invoice_send_post(body)
except ApiException as e:
    if e.status == 409:
        # Comprobante ya en proceso — NO reintentar con otro correlativo,
        # esperar el resultado. Ver /documents/{id} para el estado final.
        pass

APIs disponibles

Clase Para qué
InvoiceApi Facturas/boletas: enviar, PDF, XML, CDR
NoteApi Notas de crédito/débito
DespatchApi Guías de remisión (remitente y transportista)
SummaryApi Resumen diario y comunicación de baja; get_summary(id) da el estado del envío
DocumentsApi Listar/consultar documentos, reintentar fallidos
QueuesApi Estado de las colas BullMQ
CompanyApi / BranchesApi Empresas y establecimientos (solo lectura)
PlansApi Planes y consumo (quota)
PublicApi Consulta pública de comprobantes (sin auth)
AuthApi Autenticación
SystemApi /health, catálogos SUNAT

Desde la 3.0 la administración de la cuenta —crear o editar empresas, credenciales SOL/GRE, certificado, logo, registrar establecimientos y webhooks— se hace desde el panel de Intifact, no con la API key (la API responde 403). Por eso WebhooksApi y los métodos de escritura de CompanyApi/BranchesApi ya no están en el SDK: una key filtrada solo puede emitir y consultar.

Regenerar desde la API

El proyecto se generó con OpenAPI Generator (python) contra https://api-facturacion.intifact.com/docs/json. Para regenerar tras un cambio de la API:

npx @openapitools/openapi-generator-cli generate \
  -i https://api-facturacion.intifact.com/docs/json \
  -g python --package-name intifact_sdk \
  -o .

Nota sobre los nombres de métodos

Las rutas de la API no declaran operationId explícito en su schema de Fastify, así que el generador deriva nombres desde el método+path (api_v1_invoice_send_post en vez de algo como send_invoice). Si la API le agrega operationId a sus rutas, una regeneración futura produciría nombres más limpios sin romper compatibilidad de comportamiento.

Metadata

Release files for intifact 3.0.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 intifact 3.0.0
File Size Uploaded Provenance
intifact-3.0.0.tar.gz 162.1 kB With provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for intifact 3.0.0
File Interpreter ABI Platform
intifact-3.0.0-py3-none-any.whl Python 3 none any Details

Total release size: 510.0 kB

Release files / intifact-3.0.0.tar.gz

Download URL intifact-3.0.0.tar.gz
Size 162.1 kB
Tags Source
SHA-256 checksum
How to use checksums
af27df2c11e396cbff12e1b42f7b2bd1b1eb2076b7cb2000cb98c047570494ca
BLAKE2b-256 checksum
How to use checksums
b9fd82d8f4e9d8749cc342bba344c7acf06cad7df8a745009947baf5d2c640a8
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 Oct 22, 2026.

Transparency log

Release files / intifact-3.0.0-py3-none-any.whl

Download URL intifact-3.0.0-py3-none-any.whl
Size 347.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a87b9879011bc1be8e9037799688b13f91492a7d89d0be204ef91fcd5f8cb497
BLAKE2b-256 checksum
How to use checksums
2f877d71c0a4edcb7990a92a1c3c92e4668bb643d87597c7a5c9ef30422c9f9f
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 Oct 22, 2026.

Transparency log

Security for intifact 3.0.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

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for intifact-3.0.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 Oct 22, 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.

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