How to invoice DIAN natively in Colombia with FastAPI + MATIAS API (complete guide 2026)
Electronic invoicing in Colombia has a reputation for being a labyrinth. The DIAN portal changes without notice, the OAuth2 flow expires at critical moments, and the municipality nomenclature in the XML schema does not match any obvious public listing. This article documents how we solved it at TRUJO TECHNOLOGIES using FastAPI + MATIAS API (LOPEZSOFT) in production.
Two paths: direct DIAN operator vs authorized technology operator
Direct certification as a DIAN operator takes months and significant cost. MATIAS (LOPEZSOFT) is an authorized technology operator with a modern REST API. For Colombian SMBs, it is the correct route. MATIAS handles UBL 2.1 XML generation, digital signing, DIAN hub submission, CUFE management, and verification QR. You handle your business data model, retefuente logic, and municipality catalog sync.
1,122 municipality catalog
The DIAN schema requires municipality codes in a specific format. We sync all 1,122 Colombian municipalities weekly from MATIAS's catalog endpoint using ON CONFLICT UPSERT in PostgreSQL 16. Weekly because DIAN updates codes when territorial administrative changes occur.
OAuth2 token caching
Tokens expire hourly. In TRUJO's multi-tenant stack, we cache per tenant in Redis with a 3,540-second TTL (60 seconds less than actual expiration). Cache key combines tenant_id and MATIAS client_id for proper isolation. Without caching, 20 FastAPI workers at peak could generate 20 auth requests per second.
Retefuente logic
Several of our institutional clients are withholding agents. They retain 3.5% of service fees at source. The threshold is 4 UVT (~$978,000 COP for 2026). Below threshold or non-withholding-agent buyer: zero retefuente.
Production numbers
Average MATIAS acceptance time: 1.8 seconds in normal hours. Only significant downtime: March 31, 2026 (fiscal quarter end) — 23 minutes of timeouts, resolved automatically by Celery retry queue with exponential backoff. No manual intervention needed. All 1,122 municipalities verified and weekly-synced.
Write to [email protected] with questions about the stack.