agentleFS
AdeniyikayodeeAdeniyikayodee/ng-postcode/docs/llms-full.txt

ng-postcode

llms.txt6 starsChanged 41 days agoMITView on GitHub

Open-source tools for Nigeria's National Digital Alphanumeric Postcode System (NDAPS), the 11-character building-level postcode issued by NIPOST, e.g. EK-01-A03-FK-01. Libraries for Rust, Python, JavaScript, and Java, MCP servers for AI assistants on PyPI and npm, and a resolver that turns described addresses into postcodes. MIT licensed. Use these when a task involves validating, parsing, formatting or looking up a Nigerian postcode, or finding the postcode for a Nigerian address or coordinate. Since 1 October 2026 a Nigerian building's postcode is…

  • Reads credentials
  • Installs packages
  • In this repositoryOne other file it gives its agents.

The file

We split this llms-full.txt into the rules it gives an agent

7 rules. About 0 are common, 3 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use these when a task involves validating, parsing, formatting or looking up a Nigerian postcode, or finding the postcode for a Nigerian …

    line 7
  2. Very specific:

    No runtime dependencies. Needs Node 22.12 or later, or any runtime with fetch.

    line 621
  3. Distinctive:

    Check the address again on the server, since the browser's check can be skipped:

    line 706
  4. Very specific:

    Look-alike characters, such as O for 0, with a one-tap fix the customer confirms.

    line 718
  5. Very specific:

    Every tool is read-only except lookup_postcode_details, which spends credits.

    line 836
  6. Very specific:

    Every tool is read-only except lookup_postcode_details, which spends credits.

    line 974
  7. Distinctive:

    Use the SQL file on a managed service that accepts no extensions.

    line 1136

≈ “Common” is an estimate: at least 1 in 5 of the 4,067 llms.txt files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
llms-full.txt
<!-- docs/llms.txt -->

# ng-postcode

> Open-source tools for Nigeria's National Digital Alphanumeric Postcode System (NDAPS), the 11-character building-level postcode issued by NIPOST, e.g. EK-01-A03-FK-01. Libraries for Rust, Python, JavaScript, and Java, MCP servers for AI assistants on PyPI and npm, and a resolver that turns described addresses into postcodes. MIT licensed.

Use these when a task involves validating, parsing, formatting or looking up a Nigerian postcode, or finding the postcode for a Nigerian address or coordinate.

Since 1 October 2026 a Nigerian building's postcode is this 11-character code. A six-digit pattern such as `^\d{6}$` does not match it: that is the older area postal code, which these libraries reject.

- NIPOST's own example is `FC 02 A09 DB 09` (FCT, LGA 02, district A09, area DB, building 09). Spaces, hyphens or no separator: all the same code.
- Format: state (2 letters), LGA (2 digits, 01 to 99), district (3 letters or digits), area (2 letters), building unit (2 digits, 01 to 99).
- Compact regex: `^[A-Z]{2}(0[1-9]|[1-9][0-9])[A-Z0-9]{3}[A-Z]{2}(0[1-9]|[1-9][0-9])$`
- Validation is offline and needs no key. Lookup, autocomplete and reverse geocoding call api.postcode.gov.ng and need a key from https://dashboard.postcode.gov.ng.
- A well-formed code is not necessarily assigned to a building; only the API confirms that.

- To pass a postcode between systems or agents, use a postcode reference: `{"code": "EK-01-A03-FK", "level": "area", "confidence": "medium"}`. Schema: https://adeniyikayodee.github.io/ng-postcode/schemas/postcode-reference.schema.json
- To pass a whole address, wrap that reference in an address record with `country: "NG"` and optional `state`, `lga`, `locality`, `street_address`, `description`, and `location`. It maps onto ISO 20022, FHIR, schema.org, vCard, and UPU's address layout for Nigeria: https://adeniyikayodee.github.io/ng-postcode/address-record

## Packages

- [ng-postcode for Python](https://pypi.org/project/ng-postcode/): `pip install ng-postcode`. `parse`, `parse_lenient`, `from_segments`, `is_valid`; add the `client` extra for sync and async API clients.
- [ng-postcode for Rust](https://docs.rs/ng-postcode): `cargo add ng-postcode`. `Postcode::parse`, `parse_lenient`, `from_segments`; features `serde`, `api`, `client`.
- [ng-postcode-js](https://www.npmjs.com/package/ng-postcode-js): `npm install ng-postcode-js`. On npm, `ng-postcode` is a different project. `parse`, `parseLenient`, `fromSegments`, `isValid`; `ng-postcode-js/api` and `ng-postcode-js/client` call the API with `fetch`.
- [ng-postcode for Java](https://central.sonatype.com/artifact/io.github.adeniyikayodee/ng-postcode): Maven `io.github.adeniyikayodee:ng-postcode` (offline, no dependencies) and `io.github.adeniyikayodee:ng-postcode-api` (API client), Java 17 or later. `Postcode.parse`, `parseLenient`, `fromSegments`, `isValid`.
- [ng-postcode-mcp](https://pypi.org/project/ng-postcode-mcp/): MCP server, run with `uvx ng-postcode-mcp`, or with `npx -y ng-postcode-mcp` for the Node edition, which has every tool except `resolve_address`. Tools: `validate_postcode`, `lookup_postcode`, `autocomplete_postcode`, `find_postcode_at_location`, `resolve_address`. Registry name `io.github.Adeniyikayodee/ng-postcode`.
- [ng-address-resolver](https://pypi.org/project/ng-address-resolver/): `pip install ng-address-resolver`. Import it as `ng_address`, e.g. `from ng_address import Resolver`. Resolves free-text Nigerian addresses to postcodes, only as precisely as the evidence allows. Pre-release.
- [WooCommerce plugin](https://wordpress.org/plugins/adeniyikayode-nigerian-postcode-for-woocommerce/): install from WordPress.org; source on [GitHub](https://github.com/Adeniyikayodee/ng-postcode-woocommerce). Checks and tidies the postcode at checkout, finds it from the customer's location, and makes shipping zones match on postcode prefixes.
- [SQL](https://github.com/Adeniyikayodee/ng-postcode/tree/main/sql): the postcode as a PostgreSQL domain and DuckDB macros, with `ng_postcode_parse`, `ng_postcode_format`, and `ng_postcode_truncate` for grouping by state, LGA, district, or area.
- [ng-postcode-polars](https://pypi.org/project/ng-postcode-polars/): `pip install ng-postcode-polars`, then `import ng_postcode_polars`. Polars expressions under `pl.col(...).ng`: `parse`, `parse_prefix`, `format`, `truncate`, `is_valid`. Compiled from the Rust core.
- [ng_postcode for PostgreSQL](https://github.com/Adeniyikayodee/ng-postcode/tree/main/native/pg): a native extension for PostgreSQL 14 to 18. Types `ng_postcode` and `ng_postcode_prefix` take 8 bytes and support B-tree and hash indexes. Install a package from the repository's Releases, then `CREATE EXTENSION ng_postcode`.
- [ng_postcode for DuckDB](https://github.com/Adeniyikayodee/ng-postcode-duckdb): a DuckDB extension in Rust with `ng_postcode_parse`, `ng_postcode_prefix_parse`, `ng_postcode_format`, `ng_postcode_truncate`, `ng_postcode_parent`, and `ng_postcode_within`. Install with `INSTALL ng_postcode FROM community; LOAD ng_postcode;` on DuckDB 1.5.6; other versions report the extension as not found.
- Convert a CSV file: `pip install ng-postcode`, then `ng-postcode --column postcode customers.csv --out checked.csv`. It adds the compact code, a status of valid, suggested, invalid, or empty, and the reason for each invalid row.
- [Nigerian address form](https://github.com/Adeniyikayodee/ng-postcode/tree/main/templates/nigerian-address-form): a React checkout form built with shadcn/ui and `ng-postcode-js`. Add it with `npx shadcn@latest add https://adeniyikayodee.github.io/ng-postcode/r/nigerian-address-form.json`. It returns the postcode as `FC-02-A09-DB-09` and a phone number as `+234` and ten digits, and exports `addressSchema` (zod) for the server.
- [Group records by place](https://adeniyikayodee.github.io/ng-postcode/group-by-place): count or select records by state, LGA, district, or area by cutting each code to a prefix with `truncate`.

## Docs

- [Guide](https://adeniyikayodee.github.io/ng-postcode/): install and usage for every package
- [llms-full.txt](https://adeniyikayodee.github.io/ng-postcode/llms-full.txt): every package's README in one file
- [Python README](https://github.com/Adeniyikayodee/ng-postcode/blob/main/python/README.md)
- [Rust README](https://github.com/Adeniyikayodee/ng-postcode/blob/main/CRATE.md)
- [JavaScript README](https://github.com/Adeniyikayodee/ng-postcode/blob/main/js/packages/ng-postcode-js/README.md)
- [Java README](https://github.com/Adeniyikayodee/ng-postcode/blob/main/java/README.md)
- [MCP server README](https://github.com/Adeniyikayodee/ng-postcode/blob/main/mcp/README.md): per-client setup and configuration
- [Resolver README](https://github.com/Adeniyikayodee/ng-postcode/blob/main/agent/README.md)
- [Integration notes for the NIPOST API](https://github.com/Adeniyikayodee/ng-postcode/blob/main/docs/api-differences.md)

## Optional

- [Shared test vectors](https://github.com/Adeniyikayodee/ng-postcode/tree/main/spec): the cases every implementation must pass
- [NIPOST API docs](https://docs.postcode.gov.ng)

---

<!-- README.md -->

# ng-postcode

[![CI](https://github.com/Adeniyikayodee/ng-postcode/actions/workflows/ci.yml/badge.svg)](https://github.com/Adeniyikayodee/ng-postcode/actions/workflows/ci.yml)
[![crates.io](https://img.shields.io/crates/v/ng-postcode.svg)](https://crates.io/crates/ng-postcode)
[![PyPI](https://img.shields.io/pypi/v/ng-postcode.svg?label=pypi%20ng-postcode)](https://pypi.org/project/ng-postcode/)
[![MCP server](https://img.shields.io/pypi/v/ng-postcode-mcp.svg?label=pypi%20ng-postcode-mcp)](https://pypi.org/project/ng-postcode-mcp/)
[![npm](https://img.shields.io/npm/v/ng-postcode-js.svg?label=npm%20ng-postcode-js)](https://www.npmjs.com/package/ng-postcode-js)
[![npm MCP server](https://img.shields.io/npm/v/ng-postcode-mcp.svg?label=npm%20ng-postcode-mcp)](https://www.npmjs.com/package/ng-postcode-mcp)

Developer tools for Nigeria's National Digital Alphanumeric Postcode System (NDAPS), the building-level postcode NIPOST launched in October 2026: libraries for Rust and Python (`ng-postcode`), JavaScript (`ng-postcode-js` on npm), and Java (`ng-postcode-api`), MCP servers for AI assistants on PyPI and npm, and a resolver that turns described addresses into postcodes.

A postcode has 11 characters in five segments, written `EK-01-A03-FK-01`: state, LGA, district, area and building unit. NIPOST's own example, `FC 02 A09 DB 09`, is the same shape with spaces.

## Packages

| Package | What it does | Install | Source |
| --- | --- | --- | --- |
| `ng-postcode` (Rust) | Parse, validate and format codes offline; client for the postcode.gov.ng API | `cargo add ng-postcode` | [`src/`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/src), [docs](https://docs.rs/ng-postcode) |
| `ng-postcode` (Python) | The same behaviour, with sync and async clients | `pip install ng-postcode` | [`python/`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/python) |
| `ng-postcode-js` | The same behaviour for JavaScript and TypeScript, with a `fetch` client | `npm install ng-postcode-js` | [`js/packages/ng-postcode-js`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/js/packages/ng-postcode-js) |
| `ng-postcode` and `ng-postcode-api` (Java) | The same behaviour for Java 17 and later; the core has no dependencies | `io.github.adeniyikayodee:ng-postcode-api` | [`java/`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/java) |
| `ng-postcode-mcp` | MCP server: validate, look up, autocomplete, find by location, resolve addresses | `uvx ng-postcode-mcp` | [`mcp/`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/mcp) |
| `ng-postcode-mcp` (npm) | The same server for Node, without address resolution | `npx ng-postcode-mcp` | [`js/packages/ng-postcode-mcp`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/js/packages/ng-postcode-mcp) |
| `ng-postcode-polars` | Polars expressions that parse, format and group codes by place, compiled from the Rust core | `pip install ng-postcode-polars` | [`native/polars`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/native/polars) |
| `ng_postcode` (PostgreSQL) | The postcode as native 8-byte types with index support, compiled from the Rust core | Package from [Releases](https://github.com/Adeniyikayodee/ng-postcode/releases), then `CREATE EXTENSION ng_postcode` | [`native/pg`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/native/pg) |
| `ng_postcode` (DuckDB) | The same functions as a DuckDB extension, compiled from the Rust core | `INSTALL ng_postcode FROM community` (DuckDB 1.5.6) | [ng-postcode-duckdb](https://github.com/Adeniyikayodee/ng-postcode-duckdb) |
| `ng-address-resolver` | Resolve free-text addresses to postcodes, only as precisely as the evidence allows (pre-alpha) | `pip install ng-address-resolver` | [`agent/`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/agent) |

Each package has its own README with full usage.

For databases, [`sql/`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/sql) holds the postcode as a PostgreSQL domain and as DuckDB macros, in plain SQL that runs the same shared cases.

Two names are easy to get wrong. On npm the library is `ng-postcode-js`, because `ng-postcode` there is another project. `ng-address-resolver` is imported as `ng_address`.

For online stores, [ng-postcode-woocommerce](https://github.com/Adeniyikayodee/ng-postcode-woocommerce) is a WooCommerce plugin built on the same rules and the same shared test cases: it checks and tidies the postcode at checkout, finds it from the customer's location, and makes shipping zones match on postcode prefixes.

For React and Next.js, [`templates/nigerian-address-form`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/templates/nigerian-address-form) is a checkout address form built with shadcn/ui and `ng-postcode-js`. Add it with `npx shadcn@latest add https://adeniyikayodee.github.io/ng-postcode/r/nigerian-address-form.json`, or deploy the folder as an app.

## Quick start

Parsing and validation are offline and need no key.

**Python**

```python
from ng_postcode import Postcode, parse

match parse("ek 01 a03 fk 01"):
    case Postcode() as code:
        print(code, code.compact)  # EK-01-A03-FK-01 EK01A03FK01
    case error:
        print(error)               # e.g. "invalid lga segment"
```

**JavaScript and TypeScript**

```ts
import { Postcode, parse } from "ng-postcode-js";

const code = parse("ek 01 a03 fk 01");
if (code instanceof Postcode) {
  console.log(String(code), code.compact); // EK-01-A03-FK-01 EK01A03FK01
} else {
  console.log(String(code));               // e.g. "invalid lga segment"
}
```

**Java**

```java
import io.github.adeniyikayodee.ngpostcode.Postcode;

if (Postcode.parse("ek 01 a03 fk 01") instanceof Postcode code) {
    System.out.println(code + " " + code.compact()); // EK-01-A03-FK-01 EK01A03FK01
}
```

**Rust**

```rust
use ng_postcode::{Postcode, Segment};

let code: Postcode = "ek 01 a03 fk 01".parse()?;
assert_eq!(code.to_string(), "EK-01-A03-FK-01");
assert_eq!(code.prefix(Segment::Area), "EK-01-A03-FK");
```

**AI assistants**

The MCP server works with any MCP client. It runs over stdio as `uvx ng-postcode-mcp`, with the API key in the environment. Most clients take this entry in their MCP settings:

```json
{
  "mcpServers": {
    "ng-postcode": {
      "command": "uvx",
      "args": ["ng-postcode-mcp"],
      "env": { "NG_POSTCODE_API_KEY": "nipost_live_..." }
    }
  }
}
```

To run it with Node, use `"command": "npx"` and `"args": ["-y", "ng-postcode-mcp"]`; that edition has every tool except address resolution. Per-client steps for Cursor, VS Code, Codex, Claude and others are in the [MCP server README](https://github.com/Adeniyikayodee/ng-postcode/tree/main/mcp#install). Validation works without a key; the other tools need one from the [NIPOST developer dashboard](https://dashboard.postcode.gov.ng). The server is listed in the MCP Registry as `io.github.Adeniyikayodee/ng-postcode`.

**PostgreSQL**

Load the plain SQL file with `psql -f sql/postgres.sql`. It needs no extension, so it runs on managed services.

```sql
CREATE TABLE customers (
    id       bigint PRIMARY KEY,
    postcode ng_postcode            -- refuses anything that is not a compact code
);

INSERT INTO customers VALUES (1, ng_postcode_parse('ek 01 a03 fk 01'));

SELECT ng_postcode_format(ng_postcode_truncate(postcode, 'district')) AS district, count(*)
FROM customers
GROUP BY 1;
-- EK-01-A03 | 1
```

On a server where you can install an extension, the [native extension](https://github.com/Adeniyikayodee/ng-postcode/tree/main/native/pg) has the same functions and stores a code in 8 bytes. Unpack the package for your PostgreSQL version from [Releases](https://github.com/Adeniyikayodee/ng-postcode/releases), then run `CREATE EXTENSION ng_postcode`.

**DuckDB**

Load the same functions with `duckdb my.db < sql/duckdb.sql`.

```sql
SELECT ng_postcode_parse('ek 01 a03 fk 01');
-- EK01A03FK01
```

The compiled extension, [ng-postcode-duckdb](https://github.com/Adeniyikayodee/ng-postcode-duckdb), has the same functions: on DuckDB 1.5.6, run `INSTALL ng_postcode FROM community`, then `LOAD ng_postcode`.

**Polars**

```python
import polars as pl
import ng_postcode_polars  # pip install ng-postcode-polars

frame = pl.DataFrame({"postcode": ["ek 01 a03 fk 01", "EK-01-A03-ZZ-14", "100001"]})

print(frame.with_columns(code=pl.col("postcode").ng.parse(), ok=pl.col("postcode").ng.is_valid()))
# ek 01 a03 fk 01  EK01A03FK01  true
# EK-01-A03-ZZ-14  EK01A03ZZ14  true
# 100001           null         false
```

**A CSV file**

```sh
pip install ng-postcode
ng-postcode --column postcode customers.csv --out checked.csv
```

The output keeps every row and adds the compact code, a status of `valid`, `suggested`, `invalid`, or `empty`, a suggested correction, and the reason for each invalid row.

## For coding agents

Language models trained before October 2026 expect a six-digit Nigerian postcode. To point a coding agent at the current format, paste this into your project's `AGENTS.md`, `CLAUDE.md`, or editor rules:

```text
Nigerian postcodes: since 1 October 2026 a building's postcode is NIPOST's 11-character
digital postcode (NDAPS), such as EK-01-A03-FK-01, and a six-digit pattern does not match it.
Validate and format it with ng-postcode (pip, cargo), ng-postcode-js (npm), or
io.github.adeniyikayodee:ng-postcode (Maven). On npm, ng-postcode is a different project.
Reference: https://adeniyikayodee.github.io/ng-postcode/llms.txt
```

## The format

| Segment | Example | Shape |
| --- | --- | --- |
| State | `EK` | 2 letters |
| LGA | `01` | 2 digits, 01 to 99 |
| District | `A03` | 3 letters or digits |
| Area | `FK` | 2 letters |
| Building unit | `01` | 2 digits, 01 to 99 |

| Form | Example | Use it to |
| --- | --- | --- |
| Canonical | `EK-01-A03-FK-01` | Write a code and pass it between systems |
| Spaced | `EK 01 A03 FK 01` | Show a code to people |
| Compact | `EK01A03FK01` | Store and compare codes |

Input may be hyphenated, spaced or compact, in either case. The compact form matches `^[A-Z]{2}(0[1-9]|[1-9][0-9])[A-Z0-9]{3}[A-Z]{2}(0[1-9]|[1-9][0-9])$`. A well-formed code is not necessarily assigned to a building; only the NIPOST API can confirm that.

## Passing a postcode between systems

[`docs/schemas/postcode-reference.schema.json`](https://github.com/Adeniyikayodee/ng-postcode/blob/main/docs/schemas/postcode-reference.schema.json) defines a small JSON object for handing a location from one system or AI agent to another: the code, its level (`state` to `building`), and optionally a confidence and whether NIPOST confirmed it. A resolved or partial `resolve_address` answer already fits it.

For a whole address, [`docs/address-record.md`](https://github.com/Adeniyikayodee/ng-postcode/blob/main/docs/address-record.md) wraps the reference in an address record and maps it onto ISO 20022, FHIR, schema.org, vCard, and UPU's address layout for Nigeria.

## Design

- **One behaviour, four languages:** Rust, Python, JavaScript and Java all run the cases in [`spec/`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/spec), so they cannot drift apart. The Node MCP server registers its tools from [`spec/mcp.json`](https://github.com/Adeniyikayodee/ng-postcode/blob/main/spec/mcp.json), which the Python server generates.
- **Offline first:** parsing and validation never touch the network. API access is a separate, optional layer.
- **Errors are values:** expected failures, such as a malformed code or a rejected API key, come back as return values.
- **Careful with money and guesses:** the MCP server caps lookups at the free level unless told otherwise, and never corrects a mistyped code into a paid call. The resolver gives an area or district code when that is all the evidence supports.

## Status

- The NIPOST API needs a key for every endpoint, from the [developer dashboard](https://dashboard.postcode.gov.ng). Offline validation needs nothing.
- The API layer is tested against responses captured from the live API with a level 1 key, kept in [`spec/responses.json`](https://github.com/Adeniyikayodee/ng-postcode/blob/main/spec/responses.json). Run [`scripts/live_check.py`](https://github.com/Adeniyikayodee/ng-postcode/blob/main/scripts/live_check.py) with your own key to repeat the comparison. Lookup levels 2 and up need a higher-access key and are tested only against NIPOST's documented examples.
- The resolver and the `resolve_address` tool are pre-release. They work against the live API, but their accuracy on real addresses is unmeasured. Described addresses need a geocoder you run or pay for; text alone rarely identifies a building, so ask users for a location pin when the exact building matters.
- Notes for integrators on how the live API behaves, each with the date it was observed, are in [`docs/api-differences.md`](https://github.com/Adeniyikayodee/ng-postcode/blob/main/docs/api-differences.md).

## Development

See [CONTRIBUTING.md](https://github.com/Adeniyikayodee/ng-postcode/blob/main/CONTRIBUTING.md) for the shared spec, how to add a language, and the commit standards.

```sh
cargo test --all-features                              # Rust
cd python && uv run --group dev pytest                 # Python library
cd mcp && uv run --group dev pytest                    # MCP server
cd agent && uv run --group dev pytest                  # resolver
cd js && npm ci && npm test                            # JavaScript library and Node MCP server
cd java && ./mvnw verify                               # Java libraries
```

CI runs formatting, linting, type checks and tests for every package. Releases publish from tags (`v*` to crates.io; `py-v*`, `mcp-v*` and `agent-v*` to PyPI and the MCP Registry; `js-v*` and `js-mcp-v*` to npm) through trusted publishing, so no tokens are stored. Maven Central has no trusted publishing, so `java-v*` uses a token and a signing key held as environment secrets, and the upload is published by hand. An `mcp-v*` release also creates a GitHub release, which Glama rebuilds its listing from, and republishes the Smithery bundle with a key held the same way.

## License

MIT

---

<!-- docs/api-differences.md -->

# Integration notes for the NIPOST API

How `api.postcode.gov.ng` behaved on the dates given, for anyone building on it. These notes add detail to [NIPOST's documentation](https://docs.postcode.gov.ng), which remains the reference. The observations from 6 October onward were made with a level 1 test key. To repeat the comparison with your own key, run [`scripts/live_check.py`](https://github.com/Adeniyikayodee/ng-postcode/blob/main/scripts/live_check.py).

| Topic | The live API | Observed |
| --- | --- | --- |
| Keys | Every endpoint needs a key, including search, assembly and level 1 lookup. | 3 October 2026 |
| Lookup | Also returns `status` (`valid`, `not_found`, `invalid`) and `verified`. A malformed code is answered with HTTP 200 and `status: invalid`. | 3 October 2026 |
| Lookup level | Asking for a level the key lacks returns `403 level_not_granted`. | 3 October 2026 |
| Lookup level | A level the API cannot read, or `0`, is answered at level 1. | 6 October 2026 |
| Autocomplete | Suggestions carry `code`, the value of the next segment. Treat `label` as optional. | 3 October 2026 |
| Autocomplete | An empty query is answered with no suggestions. On 3 October it never got a response, so the libraries refuse to send one. | 6 October 2026 |
| Reverse geocoding | Also returns `depth`. | 3 October 2026 |
| Reverse geocoding | A latitude outside -90 to 90, or a longitude outside -180 to 180, returns `500 internal`. | 9 October 2026 |
| Nearby search | Returns a list of `postcode`, `display` and `distance_m`, nearest first. | 3 October 2026 |
| Load balancer | A request it rejects, such as a 5,000-character autocomplete query, returns `403` with an HTML body. | 6 October 2026 |
| Example code | `EK-01-A03-FK-01`, the example in NIPOST's docs, shows the format and is not an assigned building. | 3 October 2026 |
| Test keys | With a level 1 test key, `FC-03-B06-AG-12`, autocomplete, reverse geocoding and nearby search all return empty answers where [`spec/responses.json`](https://github.com/Adeniyikayodee/ng-postcode/blob/main/spec/responses.json) records data. | 6 October 2026 |

---

<!-- docs/address-record.md -->

# A Nigerian address record

A small JSON object for passing a Nigerian address between systems. It is built around the building postcode NIPOST issues, and it maps onto the address formats that payments, health, web, and postal systems already use.

```json
{
  "postcode": { "code": "EK-01-A03-FK-01", "level": "building", "assigned": true, "checked_at": "2026-10-03T12:00:00Z" },
  "country": "NG",
  "state": "Ekiti",
  "lga": "Ado Ekiti",
  "locality": "Ado Ekiti",
  "street_address": "12 NTA Road",
  "location": { "lat": 7.6211, "lng": 5.2214 }
}
```

Validate a record against the [JSON Schema](https://github.com/Adeniyikayodee/ng-postcode/blob/main/docs/schemas/address.schema.json). Only `postcode` and `country` are required, and a receiver ignores fields it does not know.

## Fields

| Field | Holds | Where it comes from |
| --- | --- | --- |
| `postcode` | A [postcode reference](https://github.com/Adeniyikayodee/ng-postcode/blob/main/docs/schemas/postcode-reference.schema.json): the code, its level, and optionally a confidence and whether NIPOST confirmed it | A code the person gave, a location pin, or `resolve_address` |
| `country` | `NG` | Fixed |
| `state` | State name | `state_name` in NIPOST's lookup |
| `lga` | Local government area name | `lga_name` in NIPOST's lookup |
| `locality` | Town or locality name | `locality_name` in NIPOST's lookup |
| `street_address` | House number and street on one line | The person, or `recent_house_address` in NIPOST's lookup |
| `description` | What else locates the place, such as "behind Fabian Hotel" | The person |
| `location` | A point on the building, in WGS 84 decimal degrees | A location pin |

NIPOST returns the three names and the house address from lookup level 2, which needs a key granted that level. These libraries hold no tables of names, so leave a name out when you have not looked it up.

## Rules

- **Send the code at the level you know:** an area or district code with its `level` is more useful to the receiver than a building code that was guessed.
- **Write the hyphenated form:** `EK-01-A03-FK-01` in a record or a message, and the compact `EK01A03FK01` in a database column.
- **Fill another format's postcode field only at building level:** a coarser code is a prefix of a postcode. Keep it in the record and leave the other format's field empty.
- **Treat it as personal data:** an address tied to a person is covered by the Nigeria Data Protection Act.

## Mapping to other formats

| Record | ISO 20022 `PstlAdr` | FHIR `Address` | schema.org `PostalAddress` | vCard `ADR` |
| --- | --- | --- | --- | --- |
| `postcode.code` | `PstCd` | `postalCode` | `postalCode` | postal code |
| `country` | `Ctry` | `country` | `addressCountry` | country name |
| `state` | `CtrySubDvsn` | `state` | `addressRegion` | region |
| `lga` | `DstrctNm` | `district` | none | none |
| `locality` | `TwnNm` | `city` | `addressLocality` | locality |
| `street_address` | `StrtNm` and `BldgNb`, or an `AdrLine` in a hybrid address | `line` | `streetAddress` | street address |
| `description` | An `AdrLine` in a hybrid address | `line` | none | none |
| `location` | none | The `geolocation` extension | `geo` on the enclosing `Place` | The separate `GEO` property |

### Payments

`PstCd` holds [up to 16 characters](https://www.frbservices.org/wp-content/uploads/whats-in-an-iso-20022-message-sidebar.pdf), so the 15-character hyphenated code fits as written. `TwnNm`, `DstrctNm`, and `CtrySubDvsn` hold up to 35 characters each, `StrtNm` and an `AdrLine` up to 70, and `BldgNb` up to 16.

Swift is retiring unstructured addresses from cross-border payments in favour of structured and hybrid ones. In a hybrid address the town and the country are mandatory in their own fields, with up to two free-text lines beside them, according to [bank guidance](https://www.jpmorgan.com/insights/payments/cross-border-payments/iso-20022-migration). `locality` and `country` cover that minimum. The date, the field lengths, and the mandatory fields depend on the message version and the market, so check Swift's current notices and the usage guideline you send under.

### Post

The Universal Postal Union (UPU) publishes an [addressing sheet for Nigeria](https://www.upu.int/UPU/media/upu/PostalEntitiesFiles/addressingUnit/ngaEn.pdf), dated October 2022, that sets out the lines of a Nigerian address. The record's fields fall onto those lines in this order.

| Line | UPU's label | From the record |
| --- | --- | --- |
| 1 | addressee | The person or organisation, which the record leaves to you |
| 2 | house no + street | `street_address` |
| 3 | locality + postcode | `locality`, then `postcode.code` |
| 4 | sub-province | `lga` |
| 5 | province | `state`, in capitals |
| 6 | country | `NIGERIA`, in capitals, on an item sent from abroad |

```
Mrs Ada Obi
12 NTA Road
Ado Ekiti EK-01-A03-FK-01
Ado Ekiti
EKITI STATE
NIGERIA
```

The sheet predates the digital postcode and shows a six-digit code to the right of the locality. NIPOST has published no layout for the new code that this project could find, so the example carries the 2022 position forward. Follow NIPOST's guidance once it appears. The sheet has no line for `description` or `location`.

UPU's standard for address data is S42, International postal address components and templates. It names the elements of an address and gives each country a template for arranging them. UPU's [public overview of S42](https://www.upu.int/UPU/media/upu/documents/PostCode/S42_International-Addressing-Standards.pdf) shows the elements below. This project found no S42 template for Nigeria on UPU's site.

| Record | S42 element in UPU's overview |
| --- | --- |
| `street_address` | Street No, Street Name, Street type |
| `locality` | Town |
| `state` | Region |
| `postcode.code` | Postcode |
| `country` | Country |
| `lga` | none shown |

The full list of S42 elements and their codes is in UPU's Technical Standards Manual, which is sold and which this project has not read. The table above goes only as far as UPU's public overview does.

### ISO 19160-4

[ISO 19160-4:2023](https://www.iso.org/standard/83470.html), Addressing, Part 4: International postal address components and template language, is the ISO standard for the same subject. Its text is sold, so the points below come from its published abstract alone.

- **Three levels of component:** elements, such as an organization name or a postcode; constructs, which group elements; and segments, which group constructs by function. `postcode.code` is an element in these terms.
- **Sub-elements for levels of administrative region:** the standard lets one element occur at several levels. `state` and `lga` are two levels of administrative region in Nigeria, so they fit that mechanism.
- **No fixed lengths or value ranges:** the standard sets neither for any component, so nothing in it restricts a postcode to six digits.
- **Templates:** each country's rendering rules are written as a template that software can process. A template for Nigeria would carry the line order shown under Post above.

The element codes are in the body of the standard, so this page gives no code-by-code mapping.

---

<!-- python/README.md -->

# ng-postcode

Python library for Nigeria's National Digital Alphanumeric Postcode System (NDAPS), the building-level postcode NIPOST launched in October 2026. Parse, validate and format postcodes offline, and call the [postcode.gov.ng](https://docs.postcode.gov.ng) API for lookup, autocomplete and reverse geocoding.

Also available for Rust as [`ng-postcode` on crates.io](https://crates.io/crates/ng-postcode) for JavaScript as [`ng-postcode-js` on npm](https://www.npmjs.com/package/ng-postcode-js), and for Java as [`ng-postcode-api` on Maven Central](https://central.sonatype.com/artifact/io.github.adeniyikayodee/ng-postcode-api).

```sh
pip install ng-postcode            # offline core, no dependencies
pip install "ng-postcode[client]"  # adds the API client (httpx)
```

## Format

An 11-character code in five segments: state, LGA, district, area, building unit.

| Form | Example | Use it to |
| --- | --- | --- |
| Canonical | `EK-01-A03-FK-01` | Write a code and pass it between systems |
| Spaced | `EK 01 A03 FK 01` | Show a code to people |
| Compact | `EK01A03FK01` | Store and compare codes |

Compact form as a regular expression: `^[A-Z]{2}(0[1-9]|[1-9][0-9])[A-Z0-9]{3}[A-Z]{2}(0[1-9]|[1-9][0-9])$`

## Offline

Expected failures are returned as values, so the type checker makes you handle them.

```python
from ng_postcode import Postcode, Segment, parse

match parse("ek 01 a03 fk 01"):
    case Postcode() as code:
        print(code)  # EK-01-A03-FK-01
        print(code.compact)  # EK01A03FK01, store this
        print(code.spaced)  # EK 01 A03 FK 01
        print(code.prefix(Segment.AREA))  # EK-01-A03-FK
    case error:
        print(error)  # e.g. "invalid lga segment"
```

- `parse` accepts hyphenated, spaced or compact input in either case.
- `parse_lenient` first swaps look-alikes that cannot occur where they stand (`O`/`0`, `I`/`1`, `S`/`5`, `B`/`8`) and reports how many it changed.
- `from_segments` assembles a code from its parts and zero-fills the LGA and unit.
- `parse_prefix` reads a code cut off after a segment, such as the district `EK-01-A03`, and `Postcode.truncate` cuts a code down to one. A prefix knows which codes it contains, so it groups them by state, LGA, district, or area.
- `Postcode` is immutable, hashable and sorts by state, LGA, district, area, unit.

A well-formed code is not necessarily assigned to a building. Only the API can confirm that a postcode exists.

## Convert a CSV file

The package installs an `ng-postcode` command that checks a column of postcodes and writes the file back with four columns added.

```sh
ng-postcode orders.csv --column postcode --out checked.csv
```

```text
id,postcode,postcode_compact,postcode_status,postcode_suggestion,postcode_error
1,ek 01 a03 fk 01,EK01A03FK01,valid,,
2,EK-O1-A03-FK-01,,suggested,EK-01-A03-FK-01,invalid lga segment
3,360001,,invalid,,"expected 11 letters and digits, found 6"
4,,,empty,,
```

- `valid` rows carry the compact code to store.
- `suggested` rows only parse after look-alike characters are swapped. The fix is offered for a person to confirm, and the compact column is left empty.
- `invalid` rows say what is wrong, and `empty` rows had no value.

It works offline and reads one row at a time, so the size of the file does not matter. It never writes over the file it reads, and it stops at a header that already has one of these columns or a row with more cells than the header. Add `--confirm` to ask NIPOST whether each well-formed code is assigned to a building. That needs `pip install "ng-postcode[client]"` and your own key in `NG_POSTCODE_API_KEY`, makes one free level 1 lookup for each distinct code, and adds a `postcode_assigned` column. When NIPOST's rate limit is reached it waits a minute and asks again; after any other failure the remaining rows are left unconfirmed. A test key may report an assigned code as not assigned, and the command says so when it is given one.

## API

```python
from ng_postcode import Postcode, parse
from ng_postcode.api import ApiError, lookup
from ng_postcode.client import Client, TransportError

code = parse("FC-03-B06-AG-12")
assert isinstance(code, Postcode)

with Client(api_key="nipost_live_...") as client:
    found = client.send(lookup(code, level=1))

match found:
    case ApiError() | TransportError():
        print(found)  # e.g. "invalid_api_key (401): ..."
    case _:
        print(found.valid, found.status)  # True valid
```

`send` returns the typed response, an `ApiError` (for example `auth_required` or `insufficient_credits`) or a `TransportError`. `AsyncClient` has the same interface for asyncio.

`ng_postcode.api` covers lookup, autocomplete, reverse geocoding and nearby search. Each function returns a `Request` value and `decode` turns a status and body into a typed result, so it works with any HTTP client without the `client` extra.

Get a key from the [NIPOST developer dashboard](https://dashboard.postcode.gov.ng). Level 1 lookups confirm a code is assigned; levels 2 and up return address details and consume credits.

## License

MIT

---

<!-- CRATE.md -->

# ng-postcode

[![crates.io](https://img.shields.io/crates/v/ng-postcode.svg)](https://crates.io/crates/ng-postcode)
[![docs.rs](https://docs.rs/ng-postcode/badge.svg)](https://docs.rs/ng-postcode)

Rust library for Nigeria's National Digital Alphanumeric Postcode System (NDAPS), the building-level postcode NIPOST launched in October 2026. Parse, validate and format postcodes offline, and call the [postcode.gov.ng](https://docs.postcode.gov.ng) API for lookup, autocomplete and reverse geocoding.

Part of the [ng-postcode project](https://github.com/Adeniyikayodee/ng-postcode), which has the same behaviour in Python, JavaScript and Java, MCP servers for AI assistants, and an address resolver.

## Format

An 11-character code in five segments: state, LGA, district, area, building unit.

| Form | Example | Use it to |
| --- | --- | --- |
| Canonical | `EK-01-A03-FK-01` | Write a code and pass it between systems |
| Spaced | `EK 01 A03 FK 01` | Show a code to people |
| Compact | `EK01A03FK01` | Store and compare codes |

Compact form as a regular expression: `^[A-Z]{2}(0[1-9]|[1-9][0-9])[A-Z0-9]{3}[A-Z]{2}(0[1-9]|[1-9][0-9])$`

## Offline

```rust
use ng_postcode::{ParseError, Postcode, Segment};

fn main() -> Result<(), ParseError> {
    // Hyphens, spaces and case are all accepted.
    let code: Postcode = "ek 01 a03 fk 01".parse()?;

    assert_eq!(code.to_string(), "EK-01-A03-FK-01"); // canonical
    assert_eq!(code.as_str(), "EK01A03FK01");        // compact, for storage
    assert_eq!(code.to_spaced(), "EK 01 A03 FK 01"); // for display

    assert_eq!(code.state(), "EK");
    assert_eq!(code.prefix(Segment::Area), "EK-01-A03-FK");
    Ok(())
}
```

- `Postcode::parse` checks the structure: 2 letters, 2 digits, 3 letters or digits, 2 letters, 2 digits, with numeric segments from 01 to 99.
- `Postcode::parse_lenient` first swaps look-alike characters that cannot occur where they stand (`O`/`0`, `I`/`1`, `S`/`5`, `B`/`8`) and reports how many it changed.
- `Postcode::from_segments` assembles a code from its parts and zero-fills the LGA and unit.
- `Prefix::parse` reads a code cut off after a segment, such as the district `EK-01-A03`, and `Postcode::truncate` cuts a code down to one. A prefix knows which codes it contains, so it groups them by state, LGA, district, or area.
- `Postcode` is `Copy`, 11 bytes, and sorts by state, LGA, district, area, unit.

A well-formed code is not necessarily assigned to a building, and the state is not checked against a list of state codes. Only the API can confirm that a postcode exists.

## API

```sh
cargo add ng-postcode --features client
```

```rust,no_run
use ng_postcode::{api, client::Client};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new(std::env::var("NG_POSTCODE_API_KEY")?);
    let found = client.send(&api::lookup("FC-03-B06-AG-12".parse()?, 2)?)?;
    println!("{:?}", found.administrative_address);
    Ok(())
}
```

`api` covers lookup, autocomplete, reverse geocoding and nearby search. Each function returns a `Request` value, or `InvalidRequest` for one the API cannot answer, such as an empty autocomplete or a coordinate that is not finite, and `Request::decode` turns a status and body into a typed result, so the `api` feature alone works with any HTTP client, sync or async. The `client` feature adds a small blocking one, built on `ureq`. If your program installs a `log` logger at trace level, `ureq` writes each request's bytes to it, the key among them.

## Features

| Feature | Adds |
| --- | --- |
| `serde` | `Serialize` and `Deserialize` for `Postcode` |
| `api` | Request and response types, no I/O |
| `client` | Blocking HTTP client |

## License

MIT

---

<!-- js/packages/ng-postcode-js/README.md -->

# ng-postcode-js

JavaScript and TypeScript library for Nigeria's National Digital Alphanumeric Postcode System (NDAPS), the building-level postcode NIPOST launched in October 2026. Parse, validate and format postcodes offline, and call the [postcode.gov.ng](https://docs.postcode.gov.ng) API for lookup, autocomplete and reverse geocoding.

Part of the [ng-postcode project](https://github.com/Adeniyikayodee/ng-postcode), which has the same behaviour in Rust, Python and Java and an MCP server for AI assistants. All four run the same shared test cases.

```sh
npm install ng-postcode-js
```

No runtime dependencies. Needs Node 22.12 or later, or any runtime with `fetch`. It is an ES module that `require()` can also load; a TypeScript project compiled to CommonJS needs `"module": "nodenext"` for that, as `node16` rejects it.

## Offline

Expected failures are returned as values, so the type checker makes you handle them.

```ts
import { Postcode, parse } from "ng-postcode-js";

const code = parse("ek 01 a03 fk 01");
if (code instanceof Postcode) {
  console.log(String(code)); // EK-01-A03-FK-01
  console.log(code.compact); // EK01A03FK01, store this
  console.log(code.spaced); // EK 01 A03 FK 01
  console.log(code.prefix("area")); // EK-01-A03-FK
} else {
  console.log(String(code)); // e.g. "invalid lga segment"
}
```

- `parse` accepts hyphenated, spaced or compact input in either case.
- `parseLenient` first swaps look-alikes that cannot occur where they stand (`O`/`0`, `I`/`1`, `S`/`5`, `B`/`8`) and reports how many it changed.
- `fromSegments` assembles a code from its parts and zero-fills the LGA and unit.
- `parsePrefix` reads a code cut off after a segment, such as the district `EK-01-A03`, and `truncate` cuts a code down to one. A prefix knows which codes it contains, so it groups them by state, LGA, district, or area.
- `isValid` answers yes or no.

A well-formed code is not necessarily assigned to a building. Only the API can confirm that a postcode exists.

## API

```ts
import { Postcode, parse } from "ng-postcode-js";
import { ApiError, lookup } from "ng-postcode-js/api";
import { Client, TransportError } from "ng-postcode-js/client";

const code = parse("FC-03-B06-AG-12");
if (!(code instanceof Postcode)) throw new Error(String(code));

const client = new Client(process.env.NG_POSTCODE_API_KEY ?? "");
const found = await client.send(lookup(code, 1));

if (found instanceof ApiError || found instanceof TransportError) {
  console.error(String(found)); // e.g. "invalid_api_key (401): ..."
} else {
  console.log(found.valid, found.status); // true valid
}
```

`ng-postcode-js/api` covers `lookup`, `autocomplete`, `reverse` and `nearby`. Each returns a plain `Request`, and `decode` turns a status and body into a typed result, so it works with any HTTP client. A request that cannot succeed, such as a level outside 1 to 5, an empty autocomplete or a coordinate that is not finite, throws `RangeError` before anything is sent.

The client refuses redirects and a plain http base URL (except on this machine), so the key is never sent to another host or unencrypted. Response fields keep the API's own names, such as `administrative_address`.

Get a key from the [NIPOST developer dashboard](https://dashboard.postcode.gov.ng). Level 1 lookups confirm a code is assigned; levels 2 and up return address details and consume credits.

## License

MIT

---

<!-- templates/nigerian-address-form/README.md -->

# Nigerian address form

A React checkout address form for Nigeria that accepts the 11-character NIPOST digital postcode (NDAPS), such as `FC-02-A09-DB-09`. It is built with [shadcn/ui](https://ui.shadcn.com) and [`ng-postcode-js`](https://www.npmjs.com/package/ng-postcode-js), and this folder is a Next.js app that uses it.

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FAdeniyikayodee%2Fng-postcode%2Ftree%2Fmain%2Ftemplates%2Fnigerian-address-form&project-name=nigerian-address-form)
[![Open in v0](https://v0.app/chat-static/button.svg)](https://v0.app/chat/api/open?url=https%3A%2F%2Fadeniyikayodee.github.io%2Fng-postcode%2Fr%2Fnigerian-address-form.json)

## Add it to your project

In a project set up with shadcn/ui:

```sh
npx shadcn@latest add https://adeniyikayodee.github.io/ng-postcode/r/nigerian-address-form.json
```

```tsx
import { NigerianAddressForm } from "@/components/nigerian-address-form";

<NigerianAddressForm onSubmit={saveAddress} postcodeRequired={false} />;
```

`onSubmit` receives the address with the postcode as `FC-02-A09-DB-09` and the phone number as `+2348031234567`. Return field errors, such as `{ postcode: "..." }`, to show them on the form.

Check the address again on the server, since the browser's check can be skipped:

```ts
import { addressSchema, fieldErrors } from "@/lib/nigerian-address";

const result = addressSchema().safeParse(input);
if (!result.success) return fieldErrors(result.error);
```

## What it handles

- Hyphens, spaces, no separator, and either case: the postcode is tidied to `FC-02-A09-DB-09` when the customer leaves the field.
- Look-alike characters, such as `O` for `0`, with a one-tap fix the customer confirms.
- An old six-digit code, with a message that shows the new format.
- Errors in plain words, linked to their field for screen readers, with focus moved to the first one.
- Browser autofill, through the standard `autocomplete` names and a native state picker.
- Optional confirmation with NIPOST: set `NG_POSTCODE_API_KEY` to a live key from the [NIPOST developer dashboard](https://dashboard.postcode.gov.ng), and the server refuses codes NIPOST has not assigned. If NIPOST is slow or unreachable, the order goes through on the offline check. Test keys answer "not found" for every code, so they are ignored.

## Run it

```sh
npm install
npm run dev
```

`npm test` runs the tests, and `npm run registry` rebuilds the published registry item in `docs/r`.

---

<!-- java/README.md -->

# ng-postcode for Java

Java libraries for Nigeria's National Digital Alphanumeric Postcode System (NDAPS), the building-level postcode NIPOST launched in October 2026. Parse, validate and format postcodes offline, and call the [postcode.gov.ng](https://docs.postcode.gov.ng) API for lookup, autocomplete and reverse geocoding.

Part of the [ng-postcode project](https://github.com/Adeniyikayodee/ng-postcode), which has the same behaviour in Rust, Python and JavaScript. All four run the same shared test cases.

| Artifact | What it does | Dependencies |
| --- | --- | --- |
| `io.github.adeniyikayodee:ng-postcode` | Parse, validate and format codes offline | None |
| `io.github.adeniyikayodee:ng-postcode-api` | Requests, decoding and an HTTP client | The core and Jackson |

```xml
<dependency>
  <groupId>io.github.adeniyikayodee</groupId>
  <artifactId>ng-postcode-api</artifactId>
  <version>0.3.2</version>
</dependency>
```

Needs Java 17 or later. Neither library has been tested on Android, and the client cannot run there, as Android has no `java.net.http`.

## Offline

Expected failures are returned as values of a sealed type, so the compiler makes you handle them.

```java
import io.github.adeniyikayodee.ngpostcode.Postcode;
import io.github.adeniyikayodee.ngpostcode.Segment;

if (Postcode.parse("ek 01 a03 fk 01") instanceof Postcode code) {
    System.out.println(code);                      // EK-01-A03-FK-01
    System.out.println(code.compact());            // EK01A03FK01, store this
    System.out.println(code.spaced());             // EK 01 A03 FK 01
    System.out.println(code.prefix(Segment.AREA)); // EK-01-A03-FK
}
```

- `Postcode.parse` accepts hyphenated, spaced or compact input in either case, and returns a `Postcode` or a `ParseError` such as "invalid lga segment".
- `Postcode.parseLenient` first swaps look-alikes that cannot occur where they stand (`O`/`0`, `I`/`1`, `S`/`5`, `B`/`8`) and reports how many it changed.
- `Postcode.fromSegments` assembles a code from its parts and zero-fills the LGA and unit.
- `Prefix.parse` reads a code cut off after a segment, such as the district `EK-01-A03`, and `Postcode.truncate` cuts a code down to one. A prefix knows which codes it contains, so it groups them by state, LGA, district, or area.
- `Postcode.isValid` answers yes or no.

A well-formed code is not necessarily assigned to a building. Only the API can confirm that a postcode exists.

## API

```java
import io.github.adeniyikayodee.ngpostcode.Postcode;
import io.github.adeniyikayodee.ngpostcode.api.Api;
import io.github.adeniyikayodee.ngpostcode.api.Client;
import io.github.adeniyikayodee.ngpostcode.api.Lookup;
import io.github.adeniyikayodee.ngpostcode.api.Result;

var client = new Client(System.getenv("NG_POSTCODE_API_KEY"));
Result<Lookup> found = client.send(Api.lookup(new Postcode("FC03B06AG12"), 1));

if (found instanceof Result.Ok<Lookup> ok) {
    System.out.println(ok.value().valid() + " " + ok.value().status()); // true valid
} else if (found instanceof Result.Failed<Lookup> failed) {
    System.err.println(failed.failure()); // e.g. "invalid_api_key (401): ..."
}
```

`Api` covers `lookup`, `autocomplete`, `reverse` and `nearby`. Each returns a plain `Request`, and `Api.decode` turns a status and body into a typed result, so it works with any HTTP client. A request that cannot succeed, such as a level outside 1 to 5, a blank autocomplete or a coordinate that is not finite, throws `IllegalArgumentException` before anything is sent.

The client never follows redirects and refuses a plain http base URL (except on this machine), so the key is never sent to another host or unencrypted, and it gives up after 10 seconds. Fields the API may omit are `null`.

Get a key from the [NIPOST developer dashboard](https://dashboard.postcode.gov.ng). Level 1 lookups confirm a code is assigned; levels 2 and up return address details and consume credits.

## License

MIT

---

<!-- mcp/README.md -->

# ng-postcode-mcp

MCP server for Nigeria's National Digital Alphanumeric Postcode System (NDAPS), the building-level postcode NIPOST launched in October 2026. It lets AI assistants validate postcodes offline, look them up, autocomplete them and find them by location through the [postcode.gov.ng](https://docs.postcode.gov.ng) API, and resolve described addresses to postcodes.

Built on the [`ng-postcode`](https://pypi.org/project/ng-postcode/) and [`ng-address-resolver`](https://pypi.org/project/ng-address-resolver/) libraries. A Node edition with the same tools, apart from `resolve_address`, is on npm as [`ng-postcode-mcp`](https://www.npmjs.com/package/ng-postcode-mcp) and runs with `npx`.

To validate postcodes in your own code, use the libraries: [`ng-postcode`](https://pypi.org/project/ng-postcode/) for Python, [`ng-postcode-js`](https://www.npmjs.com/package/ng-postcode-js) for JavaScript, [`ng-postcode`](https://crates.io/crates/ng-postcode) for Rust, and [`ng-postcode-api`](https://central.sonatype.com/artifact/io.github.adeniyikayodee/ng-postcode-api) for Java.

<!-- mcp-name: io.github.Adeniyikayodee/ng-postcode -->

## Tools

| Tool | What it does | Needs a key | Cost |
| --- | --- | --- | --- |
| `validate_postcode` | Checks structure offline; returns canonical forms, segments and a suggested fix for look-alike characters | No | Free |
| `lookup_postcode` | Confirms a code is assigned to a building | Yes | Free |
| `lookup_postcode_details` | Adds the address (level 2), building use (level 3) and more. Offered only when `NG_POSTCODE_MAX_LEVEL` is 2 or more | Yes | Uses credits on every call |
| `autocomplete_postcode` | Suggests the next segment of a partly typed code | Yes | Free tier |
| `find_postcode_at_location` | Returns the postcode of the nearest building to a coordinate | Yes | Free tier |
| `resolve_address` | Turns a described address ("back of Fabian Hotel, off NTA Road") or a location pin into a postcode, only as precisely as the evidence allows | Yes, plus a geocoder for text | Free tier |

Every tool is read-only except `lookup_postcode_details`, which spends credits. Errors come back as messages the model can act on, such as a missing key or an exhausted credit balance.

### How `resolve_address` answers

The assistant reads the address and passes its landmarks and map searches to the tool; the server makes no model calls of its own. The answer is never more precise than its evidence:

| Evidence | Answer |
| --- | --- |
| A postcode written in the address, or a location pin on a building | Building code |
| A landmark the address *is* | Building code, medium confidence |
| A building near a landmark ("behind", "opposite") | Area code, plus a question for the user |
| A street only | District code, low confidence |
| A town only, or nothing found | No code, plus a question |

Text alone rarely identifies a building, so ask users for a location pin when the exact building matters. This tool is pre-release: it works against the live API, but its accuracy on real addresses is unmeasured.

## Install

Works with any MCP client. The server runs over stdio:

| Setting | Value |
| --- | --- |
| Command | `uvx` |
| Arguments | `ng-postcode-mcp` |
| Environment | `NG_POSTCODE_API_KEY` (optional for `validate_postcode`) |

It needs [uv](https://docs.astral.sh/uv/) installed. Get an API key from the [NIPOST developer dashboard](https://dashboard.postcode.gov.ng).

Most clients take this entry in their MCP settings:

```json
{
  "mcpServers": {
    "ng-postcode": {
      "command": "uvx",
      "args": ["ng-postcode-mcp"],
      "env": { "NG_POSTCODE_API_KEY": "nipost_live_..." }
    }
  }
}
```

| Client | How to add it |
| --- | --- |
| Claude Code | `claude mcp add ng-postcode -e NG_POSTCODE_API_KEY=nipost_live_... -- uvx ng-postcode-mcp` |
| Claude Desktop | The entry above, in its MCP server settings |
| Codex | `codex mcp add ng-postcode --env NG_POSTCODE_API_KEY=nipost_live_... -- uvx ng-postcode-mcp` |
| Cursor | The entry above, in `.cursor/mcp.json` (project) or `~/.cursor/mcp.json` (global) |
| VS Code | The same server object in `.vscode/mcp.json`, under a top-level `"servers"` key instead of `"mcpServers"` |
| Others | Any client that launches stdio servers: use the command, arguments and environment above |

### As a bundle

[`bundle/`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/mcp/bundle) holds an MCPB manifest for clients that install `.mcpb` files, such as Claude Desktop. It runs the published package with uv and asks for the API key in the client's own settings. Build it with `npx @anthropic-ai/mcpb pack mcp/bundle ng-postcode.mcpb` from the repository root. [`bundle-python/`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/mcp/bundle-python) is the same bundle for hosts that only run Python bundles, such as Smithery; it starts the server with `uvx`, so uv must be installed. `scripts/smithery_bundle.py` builds the copy Smithery accepts, which also carries each tool's input schema.

## Configuration

| Variable | Default | Purpose |
| --- | --- | --- |
| `NG_POSTCODE_API_KEY` | none | NIPOST API key. Read from the environment only; never passed through tools. |
| `NG_POSTCODE_MAX_LEVEL` | `1` | Highest lookup level tools may request. Levels 2+ consume credits, so raise it deliberately. |
| `NG_POSTCODE_MAX_PAID_CALLS` | `25` | How many paid lookups one run of the server may make with its own key. |
| `NG_POSTCODE_BASE_URL` | `https://api.postcode.gov.ng` | Alternative API host, such as a staging stack. Must be https, except on this machine. |
| `NG_GEOCODER_URL` | none | A Nominatim server `resolve_address` uses to place described addresses. Without it, only typed postcodes and location pins resolve. |
| `NG_GEOCODER_CONTACT` | none | A URL or email sent in the User-Agent. Required for the public Nominatim. |
| `NG_POSTCODE_TRANSPORT` | `stdio` | `http` serves streamable HTTP at `/mcp` instead. |
| `NG_POSTCODE_HOST`, `NG_POSTCODE_PORT` | `127.0.0.1`, `8000` | Where the HTTP transport listens. |
| `NG_POSTCODE_ALLOW_SHARED_KEY` | unset | `1` lets the HTTP transport start with a server key on a public address. Without it, that combination is refused. |
| `NG_POSTCODE_ALLOWED_HOSTS` | unset | Host names the HTTP transport answers to, separated by commas, such as `mcp.example.com`. Required with a server key on a public address, so that a web page cannot reach the key through DNS rebinding. |

The public Nominatim at `https://nominatim.openstreetmap.org` allows light personal use only; a service whose main job is geocoding must run its own instance. Map data © OpenStreetMap contributors.

## HTTP and Docker

```sh
NG_POSTCODE_TRANSPORT=http uvx ng-postcode-mcp        # http://127.0.0.1:8000/mcp
docker build -t ng-postcode-mcp . && docker run --rm -i ng-postcode-mcp   # from the repository root
```

Over HTTP a caller can send its own NIPOST key in the `X-NIPOST-API-Key` header, and that key is used for that caller's requests only. A caller that sends none uses the server's key, if `NG_POSTCODE_API_KEY` is set.

To host the server for other people, leave `NG_POSTCODE_API_KEY` unset so every caller brings a key, and serve it over HTTPS so the header is encrypted. Callers are trusting the host with their key, and all of them share the host's geocoder, which answers one search a second. Validation still works without any key. If you do set a server key, anyone who can reach the server spends its credits, so keep it on loopback or behind your own authentication. The server refuses to start with a key on a public address unless you set `NG_POSTCODE_ALLOW_SHARED_KEY=1` and name the hosts it answers to in `NG_POSTCODE_ALLOWED_HOSTS`. `NG_POSTCODE_MAX_LEVEL` caps every caller either way, and `NG_POSTCODE_MAX_PAID_CALLS` caps what the server's own key can spend.

## Safety

- The key is read from the environment or the `X-NIPOST-API-Key` header, never from tool arguments, and never appears in results or logs.
- `lookup_postcode` is always level 1, which is free. The paid tool, `lookup_postcode_details`, does not exist for the model unless you raise `NG_POSTCODE_MAX_LEVEL`.
- The paid tool is not marked read-only or safe to retry, so a client that approves read-only tools on its own will still ask before spending.
- A mistyped code is never corrected and sent to the API silently. The server returns the suggestion and asks the model to confirm it with the user.
- Levels 2 and up return house addresses. Treat them as personal data under the Nigeria Data Protection Act.
- `resolve_address` sends the search strings to the geocoder you configure. With a third-party geocoder, that shares address text with it.

## License

MIT

---

<!-- js/packages/ng-postcode-mcp/README.md -->

# ng-postcode-mcp

MCP server for Nigeria's National Digital Alphanumeric Postcode System (NDAPS), the building-level postcode NIPOST launched in October 2026. It lets AI assistants validate postcodes offline, look them up, autocomplete them and find them by location through the [postcode.gov.ng](https://docs.postcode.gov.ng) API.

This is the Node edition of the [ng-postcode](https://github.com/Adeniyikayodee/ng-postcode) server. It registers its tools from the same contract as the Python edition, so names, descriptions and schemas are identical. The Python edition also has `resolve_address` and an HTTP transport.

To validate postcodes in your own code, use the library, [`ng-postcode-js`](https://www.npmjs.com/package/ng-postcode-js).

<!-- mcp-name: io.github.Adeniyikayodee/ng-postcode -->

## Install

It runs over stdio with `npx` and needs Node 22.12 or later. Most clients take this entry in their MCP settings:

```json
{
  "mcpServers": {
    "ng-postcode": {
      "command": "npx",
      "args": ["-y", "ng-postcode-mcp"],
      "env": { "NG_POSTCODE_API_KEY": "nipost_live_..." }
    }
  }
}
```

Get an API key from the [NIPOST developer dashboard](https://dashboard.postcode.gov.ng). Validation works without one.

## Tools

| Tool | What it does | Needs a key | Cost |
| --- | --- | --- | --- |
| `validate_postcode` | Checks structure offline; returns canonical forms, segments and a suggested fix for look-alike characters | No | Free |
| `lookup_postcode` | Confirms a code is assigned to a building | Yes | Free |
| `lookup_postcode_details` | Adds the address (level 2), building use (level 3) and more. Offered only when `NG_POSTCODE_MAX_LEVEL` is 2 or more | Yes | Uses credits on every call |
| `autocomplete_postcode` | Suggests the next segment of a partly typed code | Yes | Free tier |
| `find_postcode_at_location` | Returns the postcode of the nearest building to a coordinate | Yes | Free tier |

Every tool is read-only except `lookup_postcode_details`, which spends credits. Errors come back as messages the model can act on.

## Configuration

| Variable | Default | Purpose |
| --- | --- | --- |
| `NG_POSTCODE_API_KEY` | none | NIPOST API key. Read from the environment only; never passed through tools. |
| `NG_POSTCODE_MAX_LEVEL` | `1` | Highest lookup level tools may request. Levels 2+ consume credits, so raise it deliberately. |
| `NG_POSTCODE_MAX_PAID_CALLS` | `25` | How many paid lookups one run of the server may make with its own key. |
| `NG_POSTCODE_BASE_URL` | `https://api.postcode.gov.ng` | Alternative API host, such as a staging stack. Must be https, except on this machine. |

## Safety

- `lookup_postcode` is always level 1, which is free. The paid tool, `lookup_postcode_details`, does not exist for the model unless you raise `NG_POSTCODE_MAX_LEVEL`.
- The paid tool is not marked read-only or safe to retry, so a client that approves read-only tools on its own will still ask before spending.
- A mistyped code is never corrected and sent to the API silently. The server returns the suggestion and asks the model to confirm it with the user.
- Names and house addresses are withheld from location results unless the cap is 2 or more. Treat them as personal data under the Nigeria Data Protection Act.
- The key is never sent to another host: the client refuses redirects.

## License

MIT

---

<!-- agent/README.md -->

# ng-address-resolver

Resolve free-text Nigerian addresses, such as "back of Fabian Hotel, off NTA Road, Ado Ekiti", to NIPOST digital postcodes (NDAPS). It answers only as precisely as the evidence allows, and asks a question when it cannot.

**Status: pre-release.** The typed-postcode, location-pin and geocoded paths have run against the live NIPOST API and a live geocoder. The Claude reading step is tested only against a mocked API, and accuracy on real addresses is unmeasured.

## How it decides

1. **A postcode written in the text** is extracted (never auto-corrected) and confirmed with NIPOST.
2. **A location pin** is reverse-geocoded by NIPOST. This is the only route to a high-confidence building code.
3. **Text only** is read by Claude into street, landmarks and their relation ("behind", "opposite", "at"), area, LGA and state, then placed with a geocoder and reverse-geocoded by NIPOST.

| Evidence | Answer |
| --- | --- |
| Typed postcode NIPOST confirms, or a pin within 10 m of a building | Building code, high confidence |
| A pin within 25 m, or the landmark the address *is* | Building code, medium confidence |
| A building near a landmark ("behind", "opposite") | Area code, e.g. `EK-01-A03-FK` |
| A street only | District code, low confidence |
| A town only, or nothing found | No code, plus a question for the user |

Text alone rarely identifies a building: a landmark's own building is not the one behind it, and a road's map point is not any house on it. Ask users for a location pin when you need the exact building.

## Usage

```sh
ng-address "back of Fabian Hotel, off NTA Road, Ado Ekiti"
ng-address "my house" --lat 7.6211 --lng 5.2214
```

The result is JSON: `status` (`resolved`, `partial`, `unresolved`), `code`, `level`, `confidence`, `method`, `question` and the `evidence` behind it.

```python
from ng_address import Resolver

result = await Resolver(nipost=..., parser=..., geocoder=...).resolve("...")
```

The core needs no model. Install `ng-address-resolver[claude]` to let the CLI and `ng_address.parse.ClaudeParser` read addresses with Claude. A caller that has already read the address, such as the host model of an MCP server, passes its own `ParsedAddress` as `resolve(..., parsed=...)` instead.

## Configuration

| Variable | Purpose |
| --- | --- |
| Anthropic credentials | Needs the `claude` extra. Read by the Anthropic SDK (`ANTHROPIC_API_KEY` or an `ant auth login` profile). Without them the raw text is searched instead. |
| `NG_POSTCODE_API_KEY` | NIPOST API key. Without it the only postcode returned is one written in the address as a code, unconfirmed and at medium confidence. |
| `NG_GEOCODER_URL` | A Nominatim server, ideally your own. |
| `NG_GEOCODER_CONTACT` | A URL or email sent in the User-Agent to identify you. Required for the public Nominatim. |
| `NG_ADDRESS_MODEL` | Claude model. Defaults to `claude-opus-5-5`. |

The public Nominatim at `https://nominatim.openstreetmap.org` allows light personal use only. A service whose main job is geocoding must run its own instance or use a commercial geocoder. Map data © OpenStreetMap contributors.

Each address uses at most one Claude call at low effort, up to three geocoder searches, and one or two NIPOST calls.

## License

MIT

---

<!-- native/polars/README.md -->

# ng-postcode-polars

Polars expressions for Nigeria's NIPOST digital postcode (NDAPS), the 11-character building code such as `EK-01-A03-FK-01`. They parse, format, and cut codes down to a state, LGA, district, or area, so that a DataFrame can be grouped by place with no map.

The work is done in Rust by the same core as the [`ng-postcode`](https://github.com/Adeniyikayodee/ng-postcode) libraries, in one pass over the column. On a million rows that is about 40 times faster than calling a Python function for each row.

```sh
pip install ng-postcode-polars
```

## Usage

Importing the package adds an `ng` namespace to every expression.

```python
import polars as pl
import ng_postcode_polars  # noqa: F401

frame = pl.DataFrame({"postcode": ["ek 01 a03 fk 01", "EK-01-A03-ZZ-14", "la11w06tc10", "100001"]})

print(
    frame.with_columns(
        code=pl.col("postcode").ng.parse(),
        ok=pl.col("postcode").ng.is_valid(),
    )
)
# postcode         code         ok
# ek 01 a03 fk 01  EK01A03FK01  true
# EK-01-A03-ZZ-14  EK01A03ZZ14  true
# la11w06tc10      LA11W06TC10  true
# 100001           null         false
```

A value that is not a well-formed code becomes null, so it can be counted and followed up.

## Group by place

```python
by_district = frame.group_by(
    pl.col("postcode").ng.truncate("district").ng.format().alias("district")
).len()
# EK-01-A03  2
# LA-11-W06  1
# null       1
```

## Expressions

| Expression | Returns |
| --- | --- |
| `.ng.parse()` | The compact code, `EK01A03FK01`, or null |
| `.ng.is_valid()` | Whether the value is a well-formed code |
| `.ng.format()` | The hyphenated form of a code or a prefix |
| `.ng.truncate(segment)` | The compact prefix through `state`, `lga`, `district`, `area`, or `unit` |
| `.ng.parse_prefix()` | The compact prefix, such as `EK01A03`, or null |

A type checker cannot see a namespace that is registered at import time. For checked code, call the class directly: `Postcodes(pl.col("postcode")).parse()`.

The expressions follow the shared cases in [`spec/vectors.json`](https://github.com/Adeniyikayodee/ng-postcode/blob/main/spec/vectors.json), as every `ng-postcode` library does. A well-formed code is not necessarily assigned to a building, and only the NIPOST API can confirm that.

## License

MIT

---

<!-- native/pg/README.md -->

# ng_postcode for PostgreSQL

Nigeria's NIPOST digital postcode (NDAPS) as native PostgreSQL types, written in Rust on the same core as the [`ng-postcode`](https://github.com/Adeniyikayodee/ng-postcode) libraries.

It has the function names and answers of the plain SQL file in [`sql/`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/sql), so a query written for one runs on the other. The difference is storage. A code is held as 8 bytes and compared as an integer, where the SQL file stores 11 characters of text.

Use the SQL file on a managed service that accepts no extensions. Use this extension where you can install one and the table is large.

## What you gain

Measured on PostgreSQL 17 with one million codes, on one laptop:

| | SQL file | Extension |
| --- | --- | --- |
| Table size | 42 MB | 35 MB |
| Index size | 30 MB | 21 MB |
| Count by district | 5.6 s | 1.4 s |

Sorting and joining on the column were within a fifth of each other.

## Install

Each [release](https://github.com/Adeniyikayodee/ng-postcode/releases) tagged `pg-v` attaches a package for each PostgreSQL version from 14 to 18, for x86-64 and ARM Linux, built against the PostgreSQL project's own Debian and Ubuntu packages. Unpack the one for your version at the root of the filesystem:

```sh
sudo tar -xzf ng_postcode-0.1.0-pg17-x86_64.tar.gz -C /
```

Then, in the database:

```sql
CREATE EXTENSION ng_postcode;
```

To build from source, install [`cargo-pgrx`](https://github.com/pgcentralfoundation/pgrx) 0.19.3 and run `cargo pgrx install --release` in this directory.

## Use

```sql
CREATE TABLE customers (
    id       bigint PRIMARY KEY,
    postcode ng_postcode
);

INSERT INTO customers VALUES (1, 'ek 01 a03 fk 01'), (2, 'EK-01-A03-ZZ-14');

SELECT postcode, ng_postcode_format(postcode) FROM customers;
-- EK01A03FK01 | EK-01-A03-FK-01
-- EK01A03ZZ14 | EK-01-A03-ZZ-14
```

The type accepts a code typed in any style and refuses one that is not well formed. To turn a doubtful value into NULL without an error, pass it through `ng_postcode_parse`.

## Group and select by place

```sql
SELECT ng_postcode_format(ng_postcode_truncate(postcode, 'district')) AS district, count(*)
FROM customers
GROUP BY 1;
-- EK-01-A03 | 2
```

`code <@ prefix` tests whether a code starts with a prefix. To make selection by district use an index, index the truncated value and compare it for equality:

```sql
CREATE INDEX ON customers (ng_postcode_truncate(postcode, 'district'));

SELECT * FROM customers WHERE ng_postcode_truncate(postcode, 'district') = 'EK01A03';
```

## Types and functions

| Name | What it is |
| --- | --- |
| `ng_postcode` | A well-formed code, 8 bytes, with btree and hash index support |
| `ng_postcode_prefix` | A code cut off after a segment, such as `EK01A03`; a whole code is the narrowest prefix |
| `ng_postcode_parse(text)` | The code, or NULL |
| `ng_postcode_prefix_parse(text)` | The prefix, or NULL |
| `ng_postcode_format(code or prefix)` | The hyphenated form |
| `ng_postcode_truncate(code, segment)` | The prefix through `state`, `lga`, `district`, `area`, or `unit` |
| `ng_postcode_parent(prefix)` | The prefix one segment shorter, or NULL for a state |
| `ng_postcode_within(code, prefix)`, `code <@ prefix` | Whether the code starts with the prefix |
| `ng_postcode_version()` | The version of the installed extension |

Both types sort as their compact text does, so a prefix comes just before the codes it contains.

The extension runs the shared cases in [`spec/vectors.json`](https://github.com/Adeniyikayodee/ng-postcode/blob/main/spec/vectors.json) through the same script as the SQL file. A well-formed code is not necessarily assigned to a building, and only the NIPOST API can confirm that.

## License

MIT

---

<!-- sql/README.md -->

# ng-postcode for SQL

Nigeria's NDAPS postcode as a column type in PostgreSQL and DuckDB. Both files are plain SQL with no extension to build, so they load on managed services, and both give the same answers as the libraries: [`scripts/sql_conformance.py`](https://github.com/Adeniyikayodee/ng-postcode/blob/main/scripts/sql_conformance.py) runs the shared cases in [`spec/vectors.json`](https://github.com/Adeniyikayodee/ng-postcode/blob/main/spec/vectors.json) against them.

```sh
psql -f sql/postgres.sql          # PostgreSQL, tested on 14 and 17
duckdb my.db < sql/duckdb.sql     # DuckDB, tested on 1.5
```

Each numbered version of the two files is attached to a [GitHub release](https://github.com/Adeniyikayodee/ng-postcode/releases) tagged `sql-v`, so you can pin the copy you load.

## Store and check

```sql
CREATE TABLE customers (
    id       bigint PRIMARY KEY,
    postcode ng_postcode            -- refuses anything that is not a compact code
);

INSERT INTO customers VALUES (1, ng_postcode_parse('ek 01 a03 fk 01'));

SELECT postcode, ng_postcode_format(postcode) FROM customers;
-- EK01A03FK01 | EK-01-A03-FK-01
```

`ng_postcode_parse` accepts a hyphenated, spaced, or compact code in either case, and returns NULL for one that is not well formed. DuckDB has no domains, so declare the column as `text` with `CHECK (ng_postcode_parse(postcode) IS NOT DISTINCT FROM postcode)`. A plain `=` would let a malformed code through, because comparing with NULL is not false.

## Group by state, LGA, district, or area

A prefix is a code cut off after one of its segments. It needs no map: every building in a district shares that district's prefix.

```sql
SELECT ng_postcode_format(ng_postcode_truncate(postcode, 'district')) AS district, count(*)
FROM customers
GROUP BY 1;
-- EK-01-A03 | 1
```

To select one district, compare a range so that the column's index is used:

```sql
SELECT * FROM customers WHERE postcode >= 'EK01A03' AND postcode < 'EK01A03' || '~';
```

## Functions

| Function | Returns |
| --- | --- |
| `ng_postcode_parse(text)` | The compact code, or NULL |
| `ng_postcode_prefix_parse(text)` | The compact prefix, such as `EK01A03`, or NULL |
| `ng_postcode_format(code or prefix)` | The hyphenated form |
| `ng_postcode_truncate(code, segment)` | The prefix through `state`, `lga`, `district`, `area`, or `unit` |
| `ng_postcode_parent(prefix)` | The prefix one segment shorter, or NULL for a state |
| `ng_postcode_within(code, prefix)` | Whether the code starts with the prefix |
| `ng_postcode_version()` | The version of the file that was loaded |

Where you can install an extension and the table is large, [`native/pg`](https://github.com/Adeniyikayodee/ng-postcode/tree/main/native/pg) offers the same functions over a native 8-byte type.

A well-formed code is not necessarily assigned to a building. Only the NIPOST API can confirm that, through one of the [libraries](https://github.com/Adeniyikayodee/ng-postcode/blob/main/README.md).

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.