# UK Postcode Validate + Region Attribution (`draeg82/postcode-geo-uk`) Actor

Deterministic UK postcode validation with country/local-authority/region/centroid attribution from a bundled ONS National Statistics Postcode Lookup snapshot (OGL v3.0). Batch with dedupe rollup. No live APIs, no scraping, pure local computation.

- **URL**: https://apify.com/draeg82/postcode-geo-uk.md
- **Developed by:** [Andy Mitchell](https://apify.com/draeg82) (community)
- **Categories:** AI
- **Stats:** 2 total users, 1 monthly users, 50.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## postcode-geo-uk

Deterministic UK postcode validation + attribution for lead-list address hygiene.
Pure local computation from a bundled static file: **no live APIs, no scraping, no keys, no network calls at runtime.** Same input → same output, byte for byte.

### What it does

Input: an array of UK postcode strings (any casing/spacing).
Output per postcode, in input order:

- `status` — `ok` (valid format **and** present in the bundled ONS snapshot), `invalid` (does not match the Royal Mail postcode format), or `unknown` (valid format but not found in the bundled snapshot — reported honestly, never guessed).
- `canonical` — corrected format: uppercase, single space before the 3-character inward code (e.g. `sw1a1aa` → `SW1A 1AA`).
- `country`, `local_authority`, `region` — from the bundled ONS data.
- `latitude` / `longitude` — postcode centroid from the bundled ONS data.
- `duplicate_of` — set when the same canonical postcode appeared earlier in the batch (dedupe rollup for hygiene use).

### What it does NOT do

- Does NOT do address matching, UPRN lookup, or street-level data.
- Does NOT validate that a postcode corresponds to any specific business or person.
- Does NOT fetch anything at runtime — `unknown` means "not in this snapshot", not "does not exist" (terminated, very new, or non-GB postcodes can be `unknown`).
- Does NOT cover Crown Dependencies (Guernsey/Jersey/Isle of Man) — they report `unknown`.
- Northern Ireland postcodes are absent from the bundled snapshot and report `unknown` (see data note below).

### Quickstart

```bash
cd /home/hermes/venture/postcode-geo-uk && node main.js --fixtures
```

Expected: `36/36 passed`, exit 0, and `dataset items: 36` emitted.

Process your own list:

```bash
node main.js input.json   # input.json: { "postcodes": ["SW1A 1AA", ...] }
```

### Data & licence

Bundle: `data/postcodes.csv.gz` (1,797,567 live UK postcodes; country, centroid, local authority, region) + `data/names.json` (dictionary for LA/region names).

Source: ONS **National Statistics Postcode Lookup (UK)** via data.gov.uk, OGL v3.0 snapshot (accessed 12 Sep 2026). The GOV.UK PDUK sample page linked in the build brief now 404s; the ONS NSPL on data.gov.uk is the current free OGL v3 route for the same postcode→geography data, so this build uses it instead. No Ordnance Survey premium (ODbL/paid) data is used.

Licensing notes: the underlying postcode list carries Royal Mail and Ordnance Survey Intellectual Property Rights *in the source publication*; the publication itself is released under OGL v3.0. This bundle redistributes only the OGL-published derivation (postcode → geography), not Royal Mail address records.

> Contains public sector information licensed under the Open Government Licence v3.

### Layout

- `main.js` — CLI entry (`--fixtures`, `--selftest`, or `<input.json>`)
- `engine.js` — grammar + lookup + batch/dedupe
- `bundle.js` — loads the gzipped bundle once per process
- `input_schema.json` / `output_schema.json` — Apify-style schemas (lowercase property names)
- `fixtures/cases.json` — 36 hand-checked cases: valid, badly-formatted/invalid, valid-format-but-unknown

### Limits

- Snapshot staleness: bundled data is a point-in-time copy; newly issued postcodes will report `unknown`.
- Centroids are ONS best-fit; not survey-grade.

# Actor input Schema

## `postcodes` (type: `array`):

Array of UK postcode strings (any casing/spacing; canonicalised on output).

## Actor input object example

```json
{
  "postcodes": [
    "SW1A 1AA",
    "m1 1ae",
    "EH1 1BB",
    "CF10 1AA",
    "ZZ9 9ZZ",
    "1HF"
  ]
}
```

# Actor output Schema

## `dataset` (type: `string`):

Fields: input (original string), status (ok|invalid|unknown), canonical (uppercase single-space form or null), reason (invalid-format|not-in-bundle, where applicable), country, local\_authority, region, latitude, longitude, source (ons-nspl|known-non-geographic), duplicate\_of (canonical of an earlier identical entry, where applicable).

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "postcodes": [
        "SW1A 1AA",
        "m1 1ae",
        "EH1 1BB",
        "CF10 1AA",
        "ZZ9 9ZZ",
        "1HF"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("draeg82/postcode-geo-uk").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "postcodes": [
        "SW1A 1AA",
        "m1 1ae",
        "EH1 1BB",
        "CF10 1AA",
        "ZZ9 9ZZ",
        "1HF",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("draeg82/postcode-geo-uk").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "postcodes": [
    "SW1A 1AA",
    "m1 1ae",
    "EH1 1BB",
    "CF10 1AA",
    "ZZ9 9ZZ",
    "1HF"
  ]
}' |
apify call draeg82/postcode-geo-uk --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,draeg82/postcode-geo-uk"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/vupj0MTa6nEhpe1bS/builds/LIh6s5TniRgNjXv2s/openapi.json
