Skip to main content
Glama

Mexico Postal Codes API ๐Ÿ‡ฒ๐Ÿ‡ฝ

Ultra-fast RESTful API built with Python 3.12, FastAPI, SQLite in WAL mode, and Docker, designed to respond in < 1 ms with the official catalog of Postal Codes, Settlements, Municipalities, and States of Mexico.


This API uses and processes geographic and postal code information from the official catalog published by the Mexican Postal Service (SEPOMEX) through datos.gob.mx under the Creative Commons Attribution 4.0 International license.


๐Ÿš€ Main Features

  • API Contract and Specification: docs/api_contract.md

  • Speed and Performance: Sub-millisecond response times with SQLite in Write-Ahead Logging (WAL) mode and orjson serialization.

  • Cybersecurity: OWASP hardening, security headers, Rate Limiting, strict Pydantic v2 regex validation, and Docker non-root user.

  • Enterprise Error Handling: RFC 7807 (Problem Details) format with a unique X-Correlation-ID per request.

  • Audit & Logging: Structured JSON logs via loguru with daily rotation at midnight (00:00), .zip compression, and 30-day retention.

  • Deadlock Prevention: HTTP connections in read-only mode (mode=ro) with PRAGMA busy_timeout=5000;.

  • Automatic Ingestion Script: Downloads, cleans (ISO-8859-1 to UTF-8), and populates the database atomically.


๐Ÿ“ฆ Installation and Local Execution

1. Prerequisites

  • Python 3.10+

  • Virtualenv or Docker

2. Set up environment and install dependencies

python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt

3. Run Data Ingestion (SEPOMEX / datos.gob.mx)

python scripts/ingest_sepomex.py

This command will download the official CPdescarga.txt file and generate sepomex.db with more than 148,000 settlements and optimized indexes.

4. Start Development Server

uvicorn app.main:app --reload --port 8000

Visit the interactive documentation at: http://localhost:8000/docs


๐Ÿณ Running with Docker

Option A: Docker Build & Run

docker build -t codigos-postales-api .
docker run -p 8000:8000 codigos-postales-api

Option B: Docker Compose

docker-compose up -d

๐Ÿ” Authentication & Rate Limiting (API Key & JWT)

The API features a hybrid authentication scheme configurable from .env:

1. Operation Modes (REQUIRE_AUTH)

  • REQUIRE_AUTH=False (Public API Mode, default): The endpoints are freely accessible. Request control is performed via IP Rate Limiting (120 req/min by default).

  • REQUIRE_AUTH=True (Enterprise Protected API Mode): Requires every request to send valid credentials in the headers.

2. Supported Authentication Options

  1. Header X-API-Key:

    curl -H "X-API-Key: key-dev-12345" http://localhost:8000/api/v1/codigo-postal/01000
  2. JWT Bearer Token (Authorization: Bearer <token>):

    • JWT token exchange (valid for 24 hours):

      curl -X POST http://localhost:8000/api/v1/auth/token -H "X-API-Key: key-dev-12345"
    • Request with the returned token:

      curl -H "Authorization: Bearer <tu_jwt_token>" http://localhost:8000/api/v1/codigo-postal/01000

๐Ÿ› ๏ธ Available Endpoints

Method

Endpoint

Description

GET

/dashboard

Interactive web dashboard for observability, statistics, and GeoJSON map

GET

/api/v1/codigo-postal/{cp}

Query details of a postal code (includes nombre_sat and optional form validation colonia, estado, municipio)

POST

/api/v1/codigo-postal/batch-validate

Mass batch validation and normalization of up to 100 addresses in a single HTTP request

GET

/api/v1/codigo-postal/{cp}/geojson

Export coordinates and settlements in standard GeoJSON format (FeatureCollection)

GET

/api/v1/codigo-postal/autocomplete?prefix=01

Real-time autocomplete by prefix of 2 to 5 digits

GET

/api/v1/codigo-postal/cercanos?lat=19.43&lng=-99.13

Geographic proximity search (Haversine + Bounding Box)

GET

/api/v1/asentamientos

Accent-insensitive FTS5 search, combined filters, pagination, and direct export (format=csv)

GET

/api/v1/asentamientos/search?query=juarez

Fast accent-insensitive settlement search

GET

/api/v1/estados

List of the 32 federal entities (with nombre_sat)

GET

/api/v1/estados/{c_estado}/municipios

Municipalities by state code

GET

/api/v1/estados/{c_estado}/municipios/{c_municipio}

Full municipality detail with all its postal codes and settlements

GET

/api/v1/estados/{c_estado}/geojson

Export complete geographic layers of the state in GeoJSON format (FeatureCollection)

GET

/api/v1/estados/{c_estado}/pdf

Generate and download executive PDF report (optional parameters titulo, subtitulo, logo_url)

GET

/static/mx-postal-widget.js

JavaScript widget for automatic autocompletion of client-side HTML forms

GET

/api/v1/stats

Metric statistics and breakdown of the SEPOMEX catalog

GET

/api/v1/logs

Live audit logs and server events in JSON format

GET

/api/v1/attribution

CC BY 4.0 Legal Attribution Clause

GET

/metrics

Monitoring metrics in Prometheus standard

GET

/health

Healthcheck for Docker/K8s monitoring


๐Ÿ“ฆ Official SDK Clients (mx-postal-client)

The project includes two lightweight SDK client packages to easily consume the API without writing manual HTTP requests:

  • Python SDK (sdk/python):

    pip install ./sdk/python
    from mx_postal_client import MXPostalClient
    client = MXPostalClient(base_url="http://localhost:8080")
    cp_data = client.get_codigo_postal("01000", colonia="San รngel")
  • TypeScript / Node.js SDK (sdk/typescript):

    npm install ./sdk/typescript
    import { MXPostalClient } from 'mx-postal-client';
    const client = new MXPostalClient({ baseUrl: 'http://localhost:8080' });
    const detail = await client.getCodigoPostal('01000');

๐Ÿค– Integration with AI Agents (Model Context Protocol - MCP)

The API includes an official MCP Server (scripts/mcp_server.py) that allows AI Agents (Claude Desktop, ChatGPT, Antigravity IDE, LangChain, AutoGPT) to query and interact with the official geographic database of Mexico in natural language.

Tools Exposed for AI:

  1. consultar_codigo_postal(cp): Returns the complete geographic record and list of settlements.

  2. validar_direccion_postal(codigo_postal, colonia, estado, municipio): Validates in real time the data match with SEPOMEX.

  3. buscar_asentamientos_por_nombre(nombre_colonia, limite): Natural language search by keywords.

Configuration in Claude Desktop / Antigravity IDE (mcp.json):

{
  "mcpServers": {
    "mx-postal-codes": {
      "command": "python3",
      "args": ["/ruta/absoluta/a/codigos-postales-api/scripts/mcp_server.py"]
    }
  }
}

๐Ÿ”„ Automatic Verification of the SEPOMEX Catalog

The container runs an asynchronous monthly scheduler in the background that checks for updates in datos.gob.mx without affecting HTTP latency (< 1 ms).

To manually run the verification or force the catalog update inside the Docker container:

docker exec codigos_postales_api python3 scripts/check_updates.py --force

๐Ÿ† Comparison with the State of the Art (2026)

Technical comparison of our solution against open-source alternatives and commercial SaaS services currently on the market:

Technical Dimension / Functionality

๐Ÿš€ This Project

๐ŸŸข Tlaloc.sh

๐Ÿ Sepomex-MCP

โšก go-mexpost

๐Ÿ’ณ Copomex

Architecture

Self-Hosted (Docker/WAL)

Cloud SaaS

Self-Hosted / Python

Self-Hosted / Go

Cloud SaaS

p99 Latency

< 0.5 ms (L1 RAM Cache)

~120 ms

~15 ms

~2 ms

~200 ms

SAT CFDI 4.0 Standard

โœ… Native (nombre_sat)

โœ… Native

โŒ Not available

โŒ Not available

โš ๏ธ Partial

Batch Mass Validation (POST)

โœ… Up to 100 req/request

โŒ Not available

โŒ Not available

โŒ Not available

โŒ Not available

GeoJSON Vector (Postal Code and State)

โœ… Complete (Point & Bounds)

โŒ Not available

โŒ Not available

โŒ Not available

โŒ Not available

Executive PDF Report

โœ… Native (ReportLab)

โŒ Not available

โŒ Not available

โŒ Not available

โŒ Not available

JavaScript Frontend Widget

โœ… mx-postal-widget.js

โŒ Not available

โŒ Not available

โŒ Not available

โš ๏ธ Custom JS

MCP Server for AI Agents

โœ… scripts/mcp_server.py

โŒ Not available

โœ… Included

โŒ Not available

โŒ Not available

Official SDKs (Python/TS)

โœ… mx-postal-client

โŒ HTTP requests

โŒ HTTP requests

โŒ HTTP requests

โŒ HTTP requests

Payload Size Protection (1 MB)

โœ… RequestBodyLimit

โš ๏ธ Unknown

โŒ Not available

โš ๏ธ Proxy level

โš ๏ธ Proxy level

Operational Cost

$0 USD (Unlimited)

Pay-per-lookup

$0 USD

$0 USD

$15-$150 USD/m


๐Ÿ”ฌ Experiments

The project includes a complete suite of load tests, GPS geofencing, tax normalization, and interoperability with Artificial Intelligence Agents (MCP).

  • Phase 1 (Latency and Batch): 58.91x acceleration in batch validation (POST /batch-validate).

  • Phase 2 (SAT Normalization): Algorithmic $F_1$-Score of 90.45% with 100% precision on a dataset of 1,000 noisy samples.

  • Phase 3 (AI Agents / MCP): 99.43% token savings when interoperating via the MCP Server.


๐Ÿงช Running Tests

pytest
-
license - not tested
-
quality - not tested
C
maintenance

Maintenance

โ€“Maintainers
โ€“Response time
โ€“Release cycle
โ€“Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

  • Official Mexican data for AI agents: CURP, RFC, CFDI, postal codes, phone, SPEI/CEP, DOF, geocoding.

  • Address validation & geocoding for AI agents: 240+ countries, UK PAF, free US/CA enrichment

  • Validate LatAm IDs: Mexican CLABE, Brazilian CNPJ/CPF checksums + BrasilAPI company/CEP/bank lookups

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/alonsomaciasm/codigos-postales-api'

If you have feedback or need assistance with the MCP directory API, please join our Discord server