Skip to main content
Glama
open-postcodes

open-postcodes

by Shadojus

@shadojus/open-postcodes

Zero-dependency global postal grammar for 250 countries and territories, a local SQLite postcode directory, a Share-Alike CSV exporter, an OpenAPI REST server, a CLI, an MCP server and a Python SDK.

CI Explorer: https://shadojus.github.io/open-postcodes/ — Global Postal Atlas & 250-Territory Grammar Inspector.

IMPORTANT

A postal point is an approximate location aid,never proof of a deliverable address. Every match carries approximate: true and an honest precision.

  • 250 territories: the 249 ISO 3166-1 alpha-2 codes plus XK (Kosovo), with English/German CLDR names and endonym aliases (Deutschland, Nippon, Schweiz, …).

  • 52 NO_POSTAL_SYSTEM territories (HK, AE, QA, JM, FJ, …) are reported as such, never as "not found".

  • Shared systems (POSTAL_PARENT): Åland → FI, Liechtenstein → CH, Monaco and the French overseas collectivities → FR, Puerto Rico/Guam/… → US, Christmas Island → AU, and the Crown Dependencies Guernsey GG (GY…), Jersey JE and Isle of Man IM → GB. GeoNames ships the Crown Dependencies inside GB; the builder and the reader move them to their own country.

  • Fallback keys, fine → coarse: ZIP+4 → ZIP, Eircode → routing key, CEDEX → base, GB unit → sector → district, Canada → FSA, Netherlands → PC4, Portugal → CP4, Brazil CEP → prefix, China/Taiwan/Chile area codes, Malta locality, GhanaPostGPS → postcode.

  • Free-text parser: "D-80331 München", "Beverly Hills, CA 90210", "Sydney NSW 2000", "Italien 28100", "75008 Paris CEDEX 08".

  • 24 precision kinds on 6 honest ranks (postcode-address-centroid 5 … postcode-zone 0), with reader-facing notes such as "approximate area (town centre)". Office and zone records never get a map point.

  • German bulk-recipient filter: accuracy-0 German rows named like a firm or an office (Finanzamt Berlin, … GmbH) yield to real places in reverse lookups. US military mail (APO AE) is listed, never mapped.

  • Share-Alike CSV export (RFC 4180, UTF-8 BOM, one file per licence, notice lines, spreadsheet formula-injection guard: cells starting with = + - @ TAB CR get a leading apostrophe).

Install

npx @shadojus/open-postcodes lookup 10115 --country DE   # Node >= 22.5 (node:sqlite)
pip install shadojus-postcodes                           # Python >= 3.9, stdlib only

No runtime dependencies in either language ("dependencies": {}).

Related MCP server: Zippopotam MCP

Data

The package bundles a curated ~230-row global seed (data/seed.json, 104 countries, all four source kinds) that is loaded into an in-memory SQLite database, so lookups work out of the box. For full coverage, build a local directory from GeoNames:

curl -LO https://download.geonames.org/export/zip/allCountries.zip
unzip allCountries.zip                      # → allCountries.txt
node tools/build-data.mjs --geonames allCountries.txt [--ndjson osm-rows.ndjson] --out data/postcodes.sqlite

The builder streams the TSV into node:sqlite, assigns honest precision by code shape, moves GY/JE/IM rows out of GB, records each source's rowid span in the manifest and renames the finished file into place atomically. data/postcodes.sqlite (or OPEN_POSTCODES_DB) is picked up automatically; *.sqlite is git-ignored.

Source

Licence

Share-alike

GeoNames Postal Code Gazetteer

CC BY 4.0

no

OpenStreetMap postal boundaries & address centroids

ODbL 1.0

yes → /v1/share-alike/odbl.csv

IBGE CNEFE census address centroids (Brazil)

CC BY 4.0

no

National postal operator schedules (zones, post offices)

public reference data

no

Details and dates: data/SOURCES.json.

JavaScript

import { createPostcodeDirectory, validate, parse, countryCode } from '@shadojus/open-postcodes';

validate('SW1A 1AA', 'GB');   // { valid: true, form: 'full', system: 'own', keys: [SW1A1AA → SW1A1 → SW1A], … }
validate('JE3 6AA', 'JE');    // { valid: true, system: 'shared', parent: 'GB', … }
validate('12345', 'HK');      // { valid: false, reason: 'no-postal-system' }
parse('Beverly Hills, CA 90210'); // { code: '90210', countryHint: 'US', hintSource: 'country-word', … }

const dir = createPostcodeDirectory();          // data/postcodes.sqlite if built, else the seed
dir.search('10115', { country: 'DE' });         // exact + stored prefix, each country's best row first
dir.locate('90210-1234');                       // fallback: { from: '90210-1234', to: '90210', kind: 'zip+4' }
dir.nearest(52.52, 13.40);                      // reverse lookup with km
dir.countries();                                // 250 × { code, name, system, parent, rows, coverage }
dir.shareAlikeCsv('odbl').body;                 // RFC 4180 CSV with notice lines

The grammar alone is browser-safe: import * as G from '@shadojus/open-postcodes/grammar'.

CLI

open-postcodes lookup 10115 --country DE
open-postcodes locate "SW1A 2AB" --country GB
open-postcodes validate "K1A 0B1" Canada
open-postcodes parse "D-80331 München"
open-postcodes nearest 48.8566 2.3522
open-postcodes countries --system none          # the 52 territories without postcodes
open-postcodes country "Isle of Man"
open-postcodes export-csv odbl --out odbl.csv
open-postcodes serve --port 8787

Global flags: --json, --db <file.sqlite>, --seed.

REST API

open-postcodes serve (default 127.0.0.1:8787). OpenAPI 3.1.0 at /openapi.json. CORS *, SHA-256 ETag with 304, rate limit per client (IPv6 grouped by /64, 429 + Retry-After).

Route

Purpose

GET /health

status, version, data mode, rows

GET /v1/countries · /v1/countries/{cc}

250 territories; one country's formats and coverage

GET /v1/validate?code=&country=

grammar validation

GET /v1/parse?q=

postcode + country hint in free text

GET /v1/postcodes/{code}?country=&limit=

stored rows

GET /v1/locate/{code}?country=

all readings with fallbacks

GET /v1/nearest?lat=&lng=&country=&maxKm=

reverse lookup

GET /v1/sources

sources, licences, precision vocabulary, share-alike files

GET /v1/share-alike/{slug}.csv

Share-Alike CSV (e.g. odbl)

curl "http://localhost:8787/v1/postcodes/10115?country=DE"
curl "http://localhost:8787/v1/validate?code=SW1A1AA&country=GB"

MCP

JSON-RPC 2.0 over stdio, protocol 2024-11-05. Tools: postcode_lookup, postcode_locate, postcode_validate, postcode_parse, postcode_nearest, postal_country.

{ "mcpServers": { "postcodes": { "command": "npx", "args": ["-y", "@shadojus/open-postcodes", "--mcp"] } } }

Python

from shadojus_postcodes import PostcodeDirectory, validate

print(validate("SW1A 1AA", "GB")["valid"])        # True
d = PostcodeDirectory()                            # bundled seed, or PostcodeDirectory("postcodes.sqlite")
print(d.search("10115", country="DE")["matches"][0]["place"])   # Berlin
python -m shadojus_postcodes lookup 10115 --country DE

See python/README.md.

Development

node --test test/*.test.mjs                       # grammar, directory, builder, REST, CLI, MCP, zero-leak
python -m unittest discover -s python/tests
node tools/sync.mjs                               # refresh docs/ and python/ copies after editing src/grammar.mjs, src/countries.mjs or data/seed.json

src/grammar.mjs and src/countries.mjs are the single source of truth; docs/grammar.mjs, docs/countries.mjs, docs/postcodes-seed.json, data/grammar.json and the Python package data are generated copies, and a test fails when they drift.

Licence

Code: MIT © Shadojus. Data: see the table above. GeoNames data © GeoNames (CC BY 4.0); OpenStreetMap data © OpenStreetMap contributors (ODbL 1.0) — rows derived from ODbL sources stay under ODbL and are offered as a separate download.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Global postal code lookups, validation, and city search for 240+ countries with timezone, admin region, and elevation metadata. Sub-10ms responses at $0.000028/query with 1,000 free queries on signup.
      4
      1
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables ZIP and postal code lookups—resolving codes to city, state, and coordinates for 60+ countries, and fetching all postal codes for a city—via the Zippopotam.us API.
      301 npm
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to search worldwide cities, landmarks, and regions; retrieve administrative divisions, coordinates, population, nearby places, timezone and sunrise/sunset data; and look up postal codes by place or code.
      78 npm
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to look up US and Canadian parcel records either by full address string or by lat/lon point, returning parcel number, owner, mailing address, land use, zoning, acreage, and boundary geometry. It can be run as a local stdio server or reached through a hosted gateway endpoint.
      307 npm
      MIT