clearpostcode 1.0.0__py3-none-any.whl

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.
@@ -0,0 +1,142 @@
1
+ """ClearPostcode API client for UK postcode data: lookup, validation, autocomplete, nearest, reverse geocoding,
2
+ distance and area data. Standard library only. Docs: https://clearpostcode.co.uk/developers/docs"""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+ from typing import Any
11
+
12
+ __version__ = "1.0.0"
13
+ BASE = "https://api.clearpostcode.co.uk/v1"
14
+ __all__ = ["BASE", "ClearPostcode", "ClearPostcodeError"]
15
+
16
+ Answer = dict[str, Any]
17
+
18
+
19
+ class ClearPostcodeError(Exception):
20
+ """A non-2xx answer. `problem` is the RFC 9457 problem+json body; `request_id` is the id to quote to support."""
21
+
22
+ def __init__(self, status: int, problem: dict[str, Any] | None = None, request_id: str | None = None):
23
+ problem = problem or {}
24
+ super().__init__(problem.get("detail") or problem.get("title") or f"HTTP {status}")
25
+ self.status = status
26
+ self.problem = problem
27
+ self.request_id = request_id or problem.get("request_id")
28
+
29
+
30
+ def _seg(value: object) -> str:
31
+ return urllib.parse.quote(str(value).strip(), safe="")
32
+
33
+
34
+ class ClearPostcode:
35
+ """key: cp_live_ (secret) or cp_pub_ (publishable). Most calls also work without one (rate-limited per IP)."""
36
+
37
+ def __init__(self, key: str | None = None, base: str = BASE, timeout: float = 20):
38
+ self.key, self.base, self.timeout = key, base, timeout
39
+
40
+ def request(
41
+ self,
42
+ method: str,
43
+ path: str,
44
+ query: dict[str, Any] | None = None,
45
+ body: Any = None,
46
+ ) -> Answer:
47
+ params = {k: v for k, v in (query or {}).items() if v is not None}
48
+ url = self.base + path + (f"?{urllib.parse.urlencode(params)}" if params else "")
49
+ headers = {"user-agent": f"clearpostcode-python/{__version__}", "accept": "application/json"}
50
+ if self.key:
51
+ headers["x-api-key"] = self.key
52
+ data = None
53
+ if body is not None:
54
+ data = json.dumps(body).encode()
55
+ headers["content-type"] = "application/json"
56
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
57
+ try:
58
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
59
+ result: Answer = json.load(r)
60
+ return result
61
+ except urllib.error.HTTPError as e:
62
+ raw = e.read()
63
+ try:
64
+ problem = json.loads(raw) if raw else {}
65
+ except ValueError:
66
+ problem = {}
67
+ if not isinstance(problem, dict):
68
+ problem = {}
69
+ raise ClearPostcodeError(e.code, problem, e.headers.get("x-request-id") if e.headers else None) from None
70
+
71
+ def get(self, path: str, query: dict[str, Any] | None = None) -> Answer:
72
+ return self.request("GET", path, query)
73
+
74
+ def post(self, path: str, body: Any, query: dict[str, Any] | None = None) -> Answer:
75
+ return self.request("POST", path, query, body)
76
+
77
+ # Postcodes
78
+ def lookup(self, postcode: str, fields: str | None = None) -> Answer:
79
+ """Everything about one postcode. fields: comma-separated top-level fields to return."""
80
+ return self.get(f"/postcodes/{_seg(postcode)}", {"fields": fields})
81
+
82
+ def validate(self, postcode: str) -> Answer:
83
+ """Format valid? In the current edition? Live?"""
84
+ return self.get(f"/postcodes/{_seg(postcode)}/validate")
85
+
86
+ def nearest(self, postcode: str, radius: int | None = None, limit: int | None = None) -> Answer:
87
+ """Postcodes near a postcode. radius in metres (up to 2000), limit 1 to 50."""
88
+ return self.get(f"/postcodes/{_seg(postcode)}/nearest", {"radius": radius, "limit": limit})
89
+
90
+ def reverse(self, lat: float, lon: float, radius: int | None = None, limit: int | None = None) -> Answer:
91
+ """Postcodes near a point (reverse geocode)."""
92
+ return self.get("/postcodes", {"lat": lat, "lon": lon, "radius": radius, "limit": limit})
93
+
94
+ def bulk(self, postcodes: list[str], fields: str | None = None) -> Answer:
95
+ """Up to 100 postcodes in one call. Needs a secret key."""
96
+ return self.post("/postcodes", {"postcodes": postcodes}, {"fields": fields})
97
+
98
+ def bulk_reverse(self, points: list[dict[str, Any]]) -> Answer:
99
+ """Up to 20 points in one call: [{"lat": ..., "lon": ..., "limit": 1}]. Needs a secret key."""
100
+ return self.post("/reverse", {"points": points})
101
+
102
+ def autocomplete(self, q: str, limit: int | None = None) -> Answer:
103
+ """Complete a partial postcode. limit: 1 to 20."""
104
+ return self.get("/autocomplete", {"q": q, "limit": limit})
105
+
106
+ def distance(self, from_postcode: str, to_postcode: str) -> Answer:
107
+ """Distance between two postcodes."""
108
+ return self.get("/distance", {"from": from_postcode, "to": to_postcode})
109
+
110
+ # Geography
111
+ def outcode(self, outcode: str) -> Answer:
112
+ return self.get(f"/outcodes/{_seg(outcode)}")
113
+
114
+ def outcode_postcodes(self, outcode: str, after: str | None = None, limit: int | None = None) -> Answer:
115
+ """Every postcode in a district, a page at a time. after: last postcode of the last page. Needs a secret key."""
116
+ return self.get(f"/outcodes/{_seg(outcode)}/postcodes", {"after": after, "limit": limit})
117
+
118
+ def sector(self, sector: str) -> Answer:
119
+ return self.get(f"/sectors/{_seg(sector)}")
120
+
121
+ def area(self, area: str) -> Answer:
122
+ return self.get(f"/areas/{_seg(area)}")
123
+
124
+ # Places
125
+ def places(self, q: str, limit: int | None = None) -> Answer:
126
+ """Find a place by name. limit: 1 to 20."""
127
+ return self.get("/places", {"q": q, "limit": limit})
128
+
129
+ # Account
130
+ def usage(self) -> Answer:
131
+ """Your month's usage. Needs a key."""
132
+ return self.get("/usage")
133
+
134
+ # Addresses (early access)
135
+ def addresses(self, postcode: str) -> Answer:
136
+ return self.get("/addresses", {"postcode": postcode})
137
+
138
+ def address_suggest(self, q: str) -> Answer:
139
+ return self.get("/addresses/suggest", {"q": q})
140
+
141
+ def address(self, udprn: str | int) -> Answer:
142
+ return self.get(f"/addresses/{_seg(udprn)}")
clearpostcode/py.typed ADDED
File without changes
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.5
2
+ Name: clearpostcode
3
+ Version: 1.0.0
4
+ Summary: UK postcode data API client: postcode lookup, validation, autocomplete, nearest, reverse geocoding, distance, council, ward and constituency. Standard library only.
5
+ Project-URL: Homepage, https://clearpostcode.co.uk/developers
6
+ Project-URL: Documentation, https://clearpostcode.co.uk/developers/docs
7
+ Project-URL: Repository, https://github.com/clearpostcode/postcode-api
8
+ Author-email: ClearPostcode <hello@clearpostcode.co.uk>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: constituency,council,geocoding,postcode,postcode api,postcode autocomplete,postcode lookup,postcode validation,reverse geocode,uk postcode,ward
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Software Development :: Libraries
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.12
19
+ Description-Content-Type: text/markdown
20
+
21
+ # ClearPostcode: UK postcode data API for Python
22
+
23
+ Postcode data for any UK postcode: look it up, validate and autocomplete it, and get its council, ward, constituency, coordinates, police force
24
+ and more, from the ONS Postcode Directory and OS Open Names. Nearest postcodes, reverse geocoding, distances and
25
+ places too. Standard library only. Free: 10,000 postcode lookups a month, no card, and single postcode lookups work with no key at all.
26
+
27
+ ```sh
28
+ uv add clearpostcode # or: uv pip install clearpostcode
29
+ ```
30
+
31
+ ```python
32
+ from clearpostcode import ClearPostcode
33
+
34
+ cp = ClearPostcode() # add key="cp_live_..." for your full allowance
35
+ r = cp.lookup("SW1A 1AA")
36
+ print(
37
+ r["data"]["local_authority"]["name"], r["data"]["constituency"]["name"]
38
+ ) # Westminster, Cities of London and Westminster
39
+ print(r["meta"]["attribution"]) # credit lines to show with the data
40
+ ```
41
+
42
+ Every answer is a dict with `data` and `meta`. Every failure raises `ClearPostcodeError` with `status`, `problem` (the
43
+ RFC 9457 problem body) and `request_id`:
44
+
45
+ ```python
46
+ from clearpostcode import ClearPostcode, ClearPostcodeError
47
+
48
+ try:
49
+ ClearPostcode().lookup("not a postcode")
50
+ except ClearPostcodeError as e:
51
+ print(e.status, e.problem["title"], e.request_id)
52
+ ```
53
+
54
+ | Method | Endpoint | Key |
55
+ |---|---|---|
56
+ | `lookup(postcode, fields=None)` | `GET /postcodes/{postcode}` | optional |
57
+ | `validate(postcode)` | `GET /postcodes/{postcode}/validate` | optional |
58
+ | `nearest(postcode, radius=None, limit=None)` | `GET /postcodes/{postcode}/nearest` | optional |
59
+ | `reverse(lat, lon, radius=None, limit=None)` | `GET /postcodes` | optional |
60
+ | `autocomplete(q, limit=None)` | `GET /autocomplete` | optional |
61
+ | `distance(from_postcode, to_postcode)` | `GET /distance` | optional |
62
+ | `outcode(outcode)`, `sector(sector)`, `area(area)` | `GET /outcodes`, `/sectors`, `/areas` | optional |
63
+ | `places(q, limit=None)` | `GET /places` | optional |
64
+ | `bulk(postcodes, fields=None)` | `POST /postcodes` (up to 100) | secret key |
65
+ | `bulk_reverse(points)` | `POST /reverse` (up to 20) | secret key |
66
+ | `outcode_postcodes(outcode, after=None, limit=None)` | `GET /outcodes/{outcode}/postcodes` | secret key |
67
+ | `usage()` | `GET /usage` | any key |
68
+ | `addresses(postcode)`, `address_suggest(q)`, `address(udprn)` | `GET /addresses` (early access, Royal Mail PAF) | key |
69
+
70
+ Keys start `cp_live_` (secret, keep on the server) or `cp_pub_` (publishable, safe in a browser).
71
+
72
+ - Free key and plans: https://clearpostcode.co.uk/developers
73
+ - Docs, every field: https://clearpostcode.co.uk/developers/docs
74
+ - OpenAPI: https://clearpostcode.co.uk/openapi.json
75
+ - AI assistants (MCP): https://clearpostcode.co.uk/mcp
76
+
77
+ Contains OS data © Crown copyright and database right; Royal Mail data © Royal Mail copyright and database right;
78
+ Office for National Statistics data licensed under the Open Government Licence v3.0.
@@ -0,0 +1,6 @@
1
+ clearpostcode/__init__.py,sha256=QhL1nfbFyfPd8PVdbbz88R1dKM0H9JOMD23irmO0Dqc,6112
2
+ clearpostcode/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ clearpostcode-1.0.0.dist-info/METADATA,sha256=5-eqySm-SY4ku0Xkdk8za3rrxyUWSdeXxk7Ok1Gbzzg,3896
4
+ clearpostcode-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ clearpostcode-1.0.0.dist-info/licenses/LICENSE,sha256=w9UVAHSOFnq5d72T-0OXaxAv1qAtXjYxahg5-pjtNGY,1070
6
+ clearpostcode-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.