clearpostcode 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ClearPostcode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11
+ Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # ClearPostcode: UK postcode data API for JavaScript
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Postcode data for any UK postcode: look it up, validate and autocomplete it, and get its council, ward, constituency, coordinates, police force
4
+ and more, from the ONS Postcode Directory and OS Open Names. Nearest postcodes, reverse geocoding, distances and
5
+ places too. No dependencies. Free: 10,000 postcode lookups a month, no card, and single postcode lookups work with no key at all.
6
+
7
+ ```sh
8
+ npm install clearpostcode
9
+ ```
10
+
11
+ ```js
12
+ import { ClearPostcode } from "clearpostcode";
13
+
14
+ const cp = new ClearPostcode(); // add { key: process.env.CLEAR_POSTCODE_KEY } for your full allowance
15
+ const { data, meta } = await cp.lookup("SW1A 1AA");
16
+ console.log(data.local_authority.name, data.constituency.name); // Westminster, Cities of London and Westminster
17
+ console.log(meta.attribution); // credit lines to show with the data
18
+ ```
19
+
20
+ Every answer is `{ data, meta }`. Every failure throws a `ClearPostcodeError` with `status`, `problem` (the RFC 9457
21
+ problem body) and `request_id`:
22
+
23
+ ```js
24
+ import { ClearPostcode, ClearPostcodeError } from "clearpostcode";
25
+
26
+ try {
27
+ await new ClearPostcode().lookup("not a postcode");
28
+ } catch (e) {
29
+ if (e instanceof ClearPostcodeError) console.log(e.status, e.problem.title, e.request_id);
30
+ }
31
+ ```
32
+
33
+ | Method | Endpoint | Key |
34
+ |---|---|---|
35
+ | `lookup(postcode, { fields })` | `GET /postcodes/{postcode}` | optional |
36
+ | `validate(postcode)` | `GET /postcodes/{postcode}/validate` | optional |
37
+ | `nearest(postcode, { radius, limit })` | `GET /postcodes/{postcode}/nearest` | optional |
38
+ | `reverse({ lat, lon, radius, limit })` | `GET /postcodes` | optional |
39
+ | `autocomplete(q, { limit })` | `GET /autocomplete` | optional |
40
+ | `distance(from, to)` | `GET /distance` | optional |
41
+ | `outcode(outcode)`, `sector(sector)`, `area(area)` | `GET /outcodes`, `/sectors`, `/areas` | optional |
42
+ | `places(q, { limit })` | `GET /places` | optional |
43
+ | `bulk(postcodes, { fields })` | `POST /postcodes` (up to 100) | secret key |
44
+ | `bulkReverse(points)` | `POST /reverse` (up to 20) | secret key |
45
+ | `outcodePostcodes(outcode, { after, limit })` | `GET /outcodes/{outcode}/postcodes` | secret key |
46
+ | `usage()` | `GET /usage` | any key |
47
+ | `addresses(postcode)`, `addressSuggest(q)`, `address(udprn)` | `GET /addresses` (early access, Royal Mail PAF) | key |
48
+
49
+ Keys start `cp_live_` (secret, keep on the server) or `cp_pub_` (publishable, safe in a browser).
50
+
51
+ - Free key and plans: https://clearpostcode.co.uk/developers
52
+ - Docs, every field: https://clearpostcode.co.uk/developers/docs
53
+ - OpenAPI: https://clearpostcode.co.uk/openapi.json
54
+ - AI assistants (MCP): https://clearpostcode.co.uk/mcp
55
+
56
+ Contains OS data © Crown copyright and database right; Royal Mail data © Royal Mail copyright and database right;
57
+ Office for National Statistics data licensed under the Open Government Licence v3.0.
package/index.d.ts ADDED
@@ -0,0 +1,121 @@
1
+ export declare const BASE: string;
2
+
3
+ export type Named = { code: string; name: string | null } | null;
4
+ export type Meta = {
5
+ edition: string;
6
+ next_edition_due: string;
7
+ coverage: string;
8
+ licence: string;
9
+ attribution: string[];
10
+ docs: string;
11
+ [k: string]: unknown;
12
+ };
13
+ export type Answer<T = unknown> = { data: T; meta: Meta };
14
+
15
+ export type Postcode = {
16
+ postcode: string;
17
+ status: "live" | "terminated";
18
+ outcode?: string;
19
+ incode?: string;
20
+ sector?: string;
21
+ district?: string;
22
+ area?: string;
23
+ introduced?: string | null;
24
+ terminated?: string | null;
25
+ replaced_by?: string | null;
26
+ user_type?: "small" | "large";
27
+ location?: {
28
+ latitude: number | null;
29
+ longitude: number | null;
30
+ easting: number | null;
31
+ northing: number | null;
32
+ positional_quality: number | null;
33
+ positional_quality_label: string | null;
34
+ };
35
+ country?: Named;
36
+ region?: Named;
37
+ county?: Named;
38
+ county_electoral_division?: Named;
39
+ local_authority?: Named;
40
+ ward?: Named;
41
+ parish?: Named;
42
+ constituency?: Named;
43
+ police_force?: Named;
44
+ nhs_region?: Named;
45
+ icb?: Named;
46
+ sub_icb?: Named;
47
+ national_park?: Named;
48
+ built_up_area?: Named;
49
+ travel_to_work_area?: Named;
50
+ lsoa?: Named;
51
+ msoa?: Named;
52
+ output_area?: string | null;
53
+ rural_urban?: { code: string; name: string | null; urban: boolean | null } | null;
54
+ area_classification?: string | null;
55
+ deprivation?: { index: string; rank: number; of: number; decile: number } | null;
56
+ [k: string]: unknown;
57
+ };
58
+
59
+ export type Validation = {
60
+ input: string;
61
+ postcode: string;
62
+ format_valid: boolean;
63
+ known: boolean | null;
64
+ status: "live" | "terminated" | null;
65
+ valid: boolean | null;
66
+ coverage: "covered" | "not_covered";
67
+ replaced_by?: string | null;
68
+ [k: string]: unknown;
69
+ };
70
+
71
+ /** RFC 9457 problem details. */
72
+ export type Problem = {
73
+ type?: string;
74
+ title?: string;
75
+ status?: number;
76
+ detail?: string;
77
+ instance?: string;
78
+ request_id?: string;
79
+ [k: string]: unknown;
80
+ };
81
+
82
+ export declare class ClearPostcodeError extends Error {
83
+ constructor(status: number, problem?: Problem, request_id?: string);
84
+ status: number;
85
+ problem: Problem;
86
+ request_id: string | undefined;
87
+ }
88
+
89
+ export type Options = { key?: string; base?: string; fetch?: typeof fetch; timeout?: number };
90
+ export type Query = Record<string, string | number | null | undefined>;
91
+
92
+ export declare class ClearPostcode {
93
+ constructor(opts?: Options);
94
+ key: string | undefined;
95
+ base: string;
96
+ request<T = unknown>(method: "GET" | "POST", path: string, init?: { query?: Query; body?: unknown }): Promise<Answer<T>>;
97
+ get<T = unknown>(path: string, query?: Query): Promise<Answer<T>>;
98
+ post<T = unknown>(path: string, body: unknown, query?: Query): Promise<Answer<T>>;
99
+
100
+ lookup(postcode: string, opts?: { fields?: string }): Promise<Answer<Postcode>>;
101
+ validate(postcode: string): Promise<Answer<Validation>>;
102
+ nearest(postcode: string, opts?: { radius?: number; limit?: number }): Promise<Answer<unknown[]>>;
103
+ reverse(point: { lat: number; lon: number; radius?: number; limit?: number }): Promise<Answer<unknown[]>>;
104
+ bulk(postcodes: string[], opts?: { fields?: string }): Promise<Answer<unknown[]>>;
105
+ bulkReverse(points: { lat: number; lon: number; limit?: number }[]): Promise<Answer<unknown[]>>;
106
+ autocomplete(q: string, opts?: { limit?: number }): Promise<Answer<{ type: string; postcode: string }[]>>;
107
+ distance(from: string, to: string): Promise<Answer>;
108
+
109
+ outcode(outcode: string): Promise<Answer>;
110
+ outcodePostcodes(outcode: string, opts?: { after?: string; limit?: number }): Promise<Answer<unknown[]>>;
111
+ sector(sector: string): Promise<Answer>;
112
+ area(area: string): Promise<Answer>;
113
+
114
+ places(q: string, opts?: { limit?: number }): Promise<Answer<unknown[]>>;
115
+ usage(): Promise<Answer>;
116
+
117
+ addresses(postcode: string): Promise<Answer<unknown[]>>;
118
+ addressSuggest(q: string): Promise<Answer<unknown[]>>;
119
+ address(udprn: string | number): Promise<Answer>;
120
+ }
121
+ export default ClearPostcode;
package/index.js ADDED
@@ -0,0 +1,88 @@
1
+ // ClearPostcode API client for UK postcode data: lookup, validation, autocomplete, nearest, reverse geocoding, distance and
2
+ // area data. No dependencies. Docs: https://clearpostcode.co.uk/developers/docs
3
+ export const BASE = "https://api.clearpostcode.co.uk/v1";
4
+
5
+ /** A non-2xx answer. `problem` is the RFC 9457 problem+json body; `request_id` is the id to quote to support. */
6
+ export class ClearPostcodeError extends Error {
7
+ constructor(status, problem, request_id) {
8
+ super(problem?.detail ?? problem?.title ?? `HTTP ${status}`);
9
+ this.name = "ClearPostcodeError";
10
+ this.status = status;
11
+ this.problem = problem ?? {};
12
+ this.request_id = request_id ?? this.problem.request_id;
13
+ }
14
+ }
15
+
16
+ const seg = (s) => encodeURIComponent(String(s).trim());
17
+
18
+ export class ClearPostcode {
19
+ /** @param {{ key?: string, base?: string, fetch?: typeof fetch, timeout?: number }} [opts] key: cp_live_ (secret) or cp_pub_ (publishable); most postcode lookups also work without one. */
20
+ constructor(opts = {}) {
21
+ this.key = opts.key;
22
+ this.base = opts.base ?? BASE;
23
+ this.fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
24
+ this.timeout = opts.timeout ?? 20000;
25
+ }
26
+
27
+ async request(method, path, { query, body } = {}) {
28
+ const q = query
29
+ ? new URLSearchParams(Object.entries(query).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])).toString()
30
+ : "";
31
+ const headers = { accept: "application/json" };
32
+ if (this.key) headers["x-api-key"] = this.key;
33
+ if (body !== undefined) headers["content-type"] = "application/json";
34
+ const r = await this.fetch(`${this.base}${path}${q ? `?${q}` : ""}`, {
35
+ method,
36
+ headers,
37
+ body: body === undefined ? undefined : JSON.stringify(body),
38
+ signal: this.timeout ? AbortSignal.timeout(this.timeout) : undefined,
39
+ });
40
+ const text = await r.text();
41
+ let json;
42
+ try { json = text ? JSON.parse(text) : undefined; } catch { json = undefined; }
43
+ if (!r.ok) throw new ClearPostcodeError(r.status, json, r.headers?.get?.("x-request-id") ?? undefined);
44
+ return json;
45
+ }
46
+ get(path, query) { return this.request("GET", path, { query }); }
47
+ post(path, body, query) { return this.request("POST", path, { body, query }); }
48
+
49
+ // Postcodes
50
+ /** Everything about one postcode. opts.fields: comma-separated top-level fields to return. */
51
+ lookup(postcode, opts = {}) { return this.get(`/postcodes/${seg(postcode)}`, { fields: opts.fields }); }
52
+ /** Format valid? In the current edition? Live? */
53
+ validate(postcode) { return this.get(`/postcodes/${seg(postcode)}/validate`); }
54
+ /** Postcodes near a postcode. opts: { radius (metres, up to 2000), limit (1 to 50) } */
55
+ nearest(postcode, opts = {}) { return this.get(`/postcodes/${seg(postcode)}/nearest`, { radius: opts.radius, limit: opts.limit }); }
56
+ /** Postcodes near a point (reverse geocode). { lat, lon, radius?, limit? } */
57
+ reverse({ lat, lon, radius, limit }) { return this.get("/postcodes", { lat, lon, radius, limit }); }
58
+ /** Up to 100 postcodes in one call. Needs a secret key. */
59
+ bulk(postcodes, opts = {}) { return this.post("/postcodes", { postcodes }, { fields: opts.fields }); }
60
+ /** Up to 20 points in one call: [{ lat, lon, limit? }]. Needs a secret key. */
61
+ bulkReverse(points) { return this.post("/reverse", { points }); }
62
+ /** Complete a partial postcode. opts.limit: 1 to 20. */
63
+ autocomplete(q, opts = {}) { return this.get("/autocomplete", { q, limit: opts.limit }); }
64
+ /** Distance between two postcodes. */
65
+ distance(from, to) { return this.get("/distance", { from, to }); }
66
+
67
+ // Geography
68
+ outcode(outcode) { return this.get(`/outcodes/${seg(outcode)}`); }
69
+ /** Every postcode in a district, 100 a page. opts: { after (cursor: last postcode of the previous page), limit (1 to 500) }. Needs a secret key. */
70
+ outcodePostcodes(outcode, opts = {}) { return this.get(`/outcodes/${seg(outcode)}/postcodes`, { after: opts.after, limit: opts.limit }); }
71
+ sector(sector) { return this.get(`/sectors/${seg(sector)}`); }
72
+ area(area) { return this.get(`/areas/${seg(area)}`); }
73
+
74
+ // Places
75
+ /** Find a place by name. opts.limit: 1 to 20. */
76
+ places(q, opts = {}) { return this.get("/places", { q, limit: opts.limit }); }
77
+
78
+ // Account
79
+ /** Your month's usage. Needs a key. */
80
+ usage() { return this.get("/usage"); }
81
+
82
+ // Addresses (early access)
83
+ addresses(postcode) { return this.get("/addresses", { postcode }); }
84
+ addressSuggest(q) { return this.get("/addresses/suggest", { q }); }
85
+ address(udprn) { return this.get(`/addresses/${seg(udprn)}`); }
86
+ }
87
+
88
+ export default ClearPostcode;
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "clearpostcode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "UK postcode data API client: postcode lookup, validation, autocomplete, nearest, reverse geocoding, distance, council, ward and constituency. No dependencies.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "types": "index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "default": "./index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "index.d.ts",
17
+ "README.md"
18
+ ],
19
+ "scripts": {
20
+ "test": "node --test test.mjs",
21
+ "smoke": "node smoke.mjs"
22
+ },
23
+ "keywords": [
24
+ "postcode",
25
+ "uk postcode",
26
+ "postcode lookup",
27
+ "postcode api",
28
+ "postcode validation",
29
+ "postcode autocomplete",
30
+ "reverse geocode",
31
+ "geocoding",
32
+ "council",
33
+ "ward",
34
+ "constituency",
35
+ "uk"
36
+ ],
37
+ "homepage": "https://clearpostcode.co.uk/developers",
38
+ "license": "MIT",
39
+ "author": "ClearPostcode <hello@clearpostcode.co.uk>",
40
+ "engines": {
41
+ "node": ">=18"
42
+ },
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/clearpostcode/postcode-api.git",
46
+ "directory": "npm"
47
+ },
48
+ "bugs": {
49
+ "url": "https://clearpostcode.co.uk/contact",
50
+ "email": "hello@clearpostcode.co.uk"
51
+ }
52
+ }