vardic 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.
vardic/__init__.py ADDED
@@ -0,0 +1,363 @@
1
+ """Vardic: one client for every Vardic UK data API (vehicle, business, sanctions, monitoring, location).
2
+
3
+ Docs: https://vardic.dev/docs
4
+ Standard library only (Python 3.9+).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import hmac
10
+ import json
11
+ import os
12
+ import socket
13
+ import time
14
+ import urllib.error
15
+ import urllib.parse
16
+ import urllib.request
17
+ from email.utils import parsedate_to_datetime
18
+ from typing import Any, Dict, Iterable, Mapping, Optional, Union, cast
19
+
20
+ from .types import ScreenQuery
21
+
22
+ __all__ = ["Vardic", "VardicApiError", "verify_webhook", "ScreenQuery", "__version__"]
23
+ __version__ = "1.0.0"
24
+
25
+ Response = Dict[str, Any]
26
+
27
+ _NO_RETRY_CODES = frozenset({"quota_exceeded", "coming_soon"})
28
+ _MAX_RETRY_WAIT_SECS = 30.0
29
+
30
+
31
+ class VardicApiError(Exception):
32
+ """Raised for every failed call: an error response from the API, a timeout (code "timeout") or a network failure (code "network_error")."""
33
+
34
+ def __init__(
35
+ self,
36
+ status: int,
37
+ code: str,
38
+ message: str,
39
+ body: Any = None,
40
+ request_id: Optional[str] = None,
41
+ retry_after: Optional[float] = None,
42
+ ):
43
+ super().__init__(message)
44
+ self.status = status
45
+ self.code = code
46
+ self.message = message
47
+ self.body = body
48
+ self.request_id = request_id
49
+ self.retry_after = retry_after
50
+
51
+ def __str__(self) -> str:
52
+ return f"{self.code} ({self.status}): {self.message}"
53
+
54
+
55
+ def _csv_list(value: Any) -> Any:
56
+ return ",".join(str(v) for v in value) if isinstance(value, (list, tuple)) else value
57
+
58
+
59
+ def _query(params: Mapping[str, Any]) -> str:
60
+ out = []
61
+ for key, value in params.items():
62
+ if value is None or value == "":
63
+ continue
64
+ if isinstance(value, bool):
65
+ value = "true" if value else "false"
66
+ out.append((key, str(_csv_list(value))))
67
+ return "?" + urllib.parse.urlencode(out) if out else ""
68
+
69
+
70
+ def _seg(value: Any) -> str:
71
+ return urllib.parse.quote(str(value), safe="")
72
+
73
+
74
+ def _body(**fields: Any) -> Dict[str, Any]:
75
+ return {k: v for k, v in fields.items() if v is not None}
76
+
77
+
78
+ def _parse_retry_after(value: Optional[str]) -> Optional[float]:
79
+ if value is None or value == "":
80
+ return None
81
+ try:
82
+ return max(0.0, float(value))
83
+ except ValueError:
84
+ pass
85
+ try:
86
+ when = parsedate_to_datetime(value)
87
+ return max(0.0, when.timestamp() - time.time())
88
+ except (TypeError, ValueError):
89
+ return None
90
+
91
+
92
+ class _Product:
93
+ def __init__(self, client: "Vardic"):
94
+ self._c = client
95
+
96
+
97
+ class _Vehicle(_Product):
98
+ def get(self, registration: str) -> Response:
99
+ """Look up a vehicle by registration: DVLA record, MOT history, mileage checks and ULEZ estimate."""
100
+ return self._c._json("GET", f"/v1/vehicles/{_seg(registration)}")
101
+
102
+ def bulk(self, registrations: Iterable[str]) -> Response:
103
+ """Look up up to 25 registrations. Each entry has its own data or error."""
104
+ return self._c._json("POST", "/v1/vehicles/bulk", body={"registrations": list(registrations)})
105
+
106
+
107
+ class _Business(_Product):
108
+ def check(self, number: str, vat: Optional[str] = None, eori: Optional[str] = None,
109
+ include: Union[None, str, Iterable[str]] = None) -> Response:
110
+ """Check a company. include: extra sources such as ["officers", "psc", "charges", "filings"]."""
111
+ q = _query({"vat": vat, "eori": eori, "include": list(include) if include is not None and not isinstance(include, str) else include})
112
+ return self._c._json("GET", f"/v1/companies/{_seg(number)}{q}")
113
+
114
+ def officers(self, number: str, page: Optional[int] = None, size: Optional[int] = None) -> Response:
115
+ """Company officers (one check)."""
116
+ return self._c._json("GET", f"/v1/companies/{_seg(number)}/officers{_query({'page': page, 'size': size})}")
117
+
118
+ def psc(self, number: str, page: Optional[int] = None, size: Optional[int] = None) -> Response:
119
+ """Persons with significant control (one check)."""
120
+ return self._c._json("GET", f"/v1/companies/{_seg(number)}/persons-with-significant-control{_query({'page': page, 'size': size})}")
121
+
122
+ def charges(self, number: str, page: Optional[int] = None, size: Optional[int] = None) -> Response:
123
+ """Registered charges (one check)."""
124
+ return self._c._json("GET", f"/v1/companies/{_seg(number)}/charges{_query({'page': page, 'size': size})}")
125
+
126
+ def filings(self, number: str, page: Optional[int] = None, size: Optional[int] = None,
127
+ category: Optional[str] = None) -> Response:
128
+ """Filing history (one check)."""
129
+ return self._c._json("GET", f"/v1/companies/{_seg(number)}/filing-history{_query({'page': page, 'size': size, 'category': category})}")
130
+
131
+ def ownership(self, number: str, depth: Optional[int] = None, threshold: Optional[int] = None) -> Response:
132
+ """UK ownership check: owners at 50% or more, screened against sanctions lists. A screening aid, not legal advice."""
133
+ return self._c._json("GET", f"/v1/companies/{_seg(number)}/ownership{_query({'depth': depth, 'threshold': threshold})}")
134
+
135
+ def search(self, query: str) -> Response:
136
+ """Search companies by name (at least 2 characters)."""
137
+ return self._c._json("GET", f"/v1/companies/search{_query({'q': query})}")
138
+
139
+ def eori(self, eori: str) -> Response:
140
+ """Check a UK (GB) EORI number with HMRC."""
141
+ return self._c._json("GET", f"/v1/eori/{_seg(eori)}")
142
+
143
+ def vat(self, vat_number: str) -> Response:
144
+ """Validate a UK VAT number with HMRC. Not open yet: raises a 503 (not counted) until it is."""
145
+ return self._c._json("GET", f"/v1/vat/{_seg(vat_number)}")
146
+
147
+
148
+ class _Sanctions(_Product):
149
+ def screen(self, query: Optional[Mapping[str, Any]] = None, **fields: Any) -> Response:
150
+ """Screen a name: pass a dict (see ScreenQuery) or keywords such as name="...", type="entity"."""
151
+ return self._c._json("POST", "/v1/sanctions/screen", body={**(query or {}), **fields})
152
+
153
+ def screen_bulk(self, queries: Iterable[Mapping[str, Any]]) -> Response:
154
+ """Screen up to 25 queries. One result per query, in order."""
155
+ return self._c._json("POST", "/v1/sanctions/screen/bulk", body={"queries": [dict(q) for q in queries]})
156
+
157
+ def screen_csv(self, csv: Union[str, bytes], record: Optional[bool] = None, format: Optional[str] = None,
158
+ threshold: Optional[int] = None, lists: Union[None, str, Iterable[str]] = None,
159
+ type: Optional[str] = None) -> Any:
160
+ """Screen a CSV file of names. With format="csv" the result is the CSV text; otherwise the parsed JSON summary."""
161
+ q = _query({"record": record, "format": format, "threshold": threshold,
162
+ "lists": list(lists) if lists is not None and not isinstance(lists, str) else lists, "type": type})
163
+ data = csv.encode("utf-8") if isinstance(csv, str) else csv
164
+ return self._c._request("POST", f"/v1/sanctions/screen/csv{q}", raw_body=data, content_type="text/csv",
165
+ as_="text" if format == "csv" else "json")
166
+
167
+ def list_checks(self, limit: Optional[int] = None, before: Optional[str] = None) -> Response:
168
+ """Your screening records, newest first (not counted). before: an ISO timestamp."""
169
+ return self._c._json("GET", f"/v1/sanctions/checks{_query({'limit': limit, 'before': before})}")
170
+
171
+ def get_check(self, check_id: str) -> Response:
172
+ """One screening record with its results."""
173
+ return self._c._json("GET", f"/v1/sanctions/checks/{_seg(check_id)}")
174
+
175
+ def delete_check(self, check_id: str) -> Response:
176
+ """Delete a screening record."""
177
+ return self._c._json("DELETE", f"/v1/sanctions/checks/{_seg(check_id)}")
178
+
179
+ def certificate(self, check_id: str, row: Optional[int] = None) -> bytes:
180
+ """PDF screening certificate. row: one row of a batch (1-based)."""
181
+ return cast(bytes, self._c._request("GET", f"/v1/sanctions/checks/{_seg(check_id)}/certificate{_query({'row': row})}", as_="bytes"))
182
+
183
+ def check_csv(self, check_id: str) -> str:
184
+ """Results file of a recorded CSV batch, as text."""
185
+ return cast(str, self._c._request("GET", f"/v1/sanctions/checks/{_seg(check_id)}/results.csv", as_="text"))
186
+
187
+ def lists(self) -> Response:
188
+ """List versions and publication dates (not counted)."""
189
+ return self._c._json("GET", "/v1/sanctions/lists")
190
+
191
+
192
+ class _Monitoring(_Product):
193
+ def list(self) -> Response:
194
+ """List your watches."""
195
+ return self._c._json("GET", "/v1/watches")
196
+
197
+ def create(self, registration: Optional[str] = None, company_number: Optional[str] = None,
198
+ sanctions: Optional[Mapping[str, Any]] = None, url: Optional[str] = None,
199
+ days_before: Optional[Iterable[int]] = None, events: Optional[Iterable[str]] = None,
200
+ email_digest: Optional[bool] = None) -> Response:
201
+ """Create a watch. Give one of registration, company_number or sanctions (a dict with a name) and a url."""
202
+ return self._c._json("POST", "/v1/watches", body=_body(
203
+ registration=registration, companyNumber=company_number,
204
+ sanctions=dict(sanctions) if sanctions is not None else None, url=url,
205
+ daysBefore=list(days_before) if days_before is not None else None,
206
+ events=list(events) if events is not None else None, emailDigest=email_digest))
207
+
208
+ def create_many(self, company_numbers: Iterable[str], url: Optional[str] = None,
209
+ events: Optional[Iterable[str]] = None, email_digest: Optional[bool] = None) -> Response:
210
+ """Watch up to 500 companies. The response holds the created watches and per-number errors."""
211
+ return self._c._json("POST", "/v1/watches/bulk", body=_body(
212
+ companyNumbers=list(company_numbers), url=url,
213
+ events=list(events) if events is not None else None, emailDigest=email_digest))
214
+
215
+ def delete(self, watch_id: str) -> None:
216
+ """Delete a watch."""
217
+ self._c._request("DELETE", f"/v1/watches/{_seg(watch_id)}")
218
+
219
+ def test_event(self, url: str, type: Optional[str] = None) -> Response:
220
+ """Send a sample signed event to a URL. Needs your own key; sandbox keys work."""
221
+ return self._c._json("POST", "/v1/watches/test-event", body=_body(url=url, type=type))
222
+
223
+
224
+ class _Location(_Product):
225
+ def postcode(self, postcode: str, include: Union[None, str, Iterable[str]] = None,
226
+ schools: Optional[int] = None, phase: Optional[str] = None) -> Response:
227
+ """Check a postcode in Great Britain: area codes, flood risk, crime and schools."""
228
+ q = _query({"include": list(include) if include is not None and not isinstance(include, str) else include,
229
+ "schools": schools, "phase": phase})
230
+ return self._c._json("GET", f"/v1/postcodes/{_seg(postcode)}{q}")
231
+
232
+ def fuel_nearest(self, postcode: Optional[str] = None, lat: Optional[float] = None, lng: Optional[float] = None,
233
+ fuel: Optional[str] = None, radius: Optional[float] = None, sort: Optional[str] = None,
234
+ limit: Optional[int] = None) -> Response:
235
+ """Nearest or cheapest forecourts. Give a postcode, or lat and lng. radius is in kilometres."""
236
+ q = _query({"postcode": postcode, "lat": lat, "lng": lng, "fuel": fuel, "radius": radius, "sort": sort, "limit": limit})
237
+ return self._c._json("GET", f"/v1/fuel/nearest{q}")
238
+
239
+ def fuel_station(self, station_id: str) -> Response:
240
+ """Every price at one forecourt."""
241
+ return self._c._json("GET", f"/v1/fuel/stations/{_seg(station_id)}")
242
+
243
+ def fuel_history(self, station_id: str, days: Optional[int] = None) -> Response:
244
+ """Price history for a forecourt (days: 1 to 90)."""
245
+ return self._c._json("GET", f"/v1/fuel/stations/{_seg(station_id)}/history{_query({'days': days})}")
246
+
247
+
248
+ class Vardic:
249
+ """Client for every Vardic API.
250
+
251
+ >>> vardic = Vardic() # reads VARDIC_API_KEY
252
+ >>> vardic.business.check("00445790")["data"]["company"]["name"] # Tesco PLC
253
+ """
254
+
255
+ def __init__(self, api_key: Optional[str] = None, base_url: str = "https://api.vardic.dev",
256
+ timeout: float = 15.0, max_retries: int = 2):
257
+ self.api_key = api_key or os.environ.get("VARDIC_API_KEY")
258
+ if not self.api_key:
259
+ raise ValueError("Pass api_key or set VARDIC_API_KEY. Get a free key at https://vardic.dev/signup")
260
+ self.base_url = base_url.rstrip("/")
261
+ self.timeout = timeout
262
+ self.max_retries = max_retries
263
+ self.vehicle = _Vehicle(self)
264
+ self.business = _Business(self)
265
+ self.sanctions = _Sanctions(self)
266
+ self.monitoring = _Monitoring(self)
267
+ self.location = _Location(self)
268
+
269
+ def account(self) -> Response:
270
+ """Your plans, usage this month and webhook secret."""
271
+ return self._json("GET", "/v1/account")
272
+
273
+ def status(self) -> Response:
274
+ """Public service status with uptime per source. Not counted."""
275
+ return self._json("GET", "/v1/status")
276
+
277
+ @staticmethod
278
+ def verify_webhook(raw_body: Union[bytes, str], header: Optional[str], secret: str, tolerance_secs: int = 300) -> bool:
279
+ """Same as the module-level verify_webhook."""
280
+ return verify_webhook(raw_body, header, secret, tolerance_secs)
281
+
282
+ def _json(self, method: str, path: str, body: Any = None) -> Response:
283
+ return cast(Response, self._request(method, path, body=body))
284
+
285
+ def _request(self, method: str, path: str, body: Any = None, raw_body: Optional[bytes] = None,
286
+ content_type: Optional[str] = None, as_: str = "json") -> Any:
287
+ headers = {"x-api-key": str(self.api_key), "user-agent": f"vardic-python/{__version__}",
288
+ "accept": "application/json" if as_ == "json" else "*/*"}
289
+ data: Optional[bytes] = None
290
+ if raw_body is not None:
291
+ data = raw_body
292
+ headers["content-type"] = content_type or "application/octet-stream"
293
+ elif body is not None:
294
+ data = json.dumps(body).encode("utf-8")
295
+ headers["content-type"] = "application/json"
296
+
297
+ attempt = 0
298
+ while True:
299
+ req = urllib.request.Request(self.base_url + path, data=data, method=method, headers=headers)
300
+ status = 0
301
+ resp_headers: Any = {}
302
+ try:
303
+ with urllib.request.urlopen(req, timeout=self.timeout) as res:
304
+ raw = res.read()
305
+ status = getattr(res, "status", 200)
306
+ resp_headers = getattr(res, "headers", None) or {}
307
+ if as_ == "bytes":
308
+ return raw
309
+ if as_ == "text":
310
+ return raw.decode("utf-8")
311
+ if not raw:
312
+ return None
313
+ try:
314
+ return json.loads(raw)
315
+ except ValueError:
316
+ raise VardicApiError(status, "invalid_response", "The response was not valid JSON",
317
+ request_id=resp_headers.get("x-request-id")) from None
318
+ except urllib.error.HTTPError as e:
319
+ try:
320
+ raw_err = e.read() or b"{}"
321
+ finally:
322
+ e.close()
323
+ try:
324
+ parsed = json.loads(raw_err)
325
+ except ValueError:
326
+ parsed = {}
327
+ err = (parsed.get("error") if isinstance(parsed, dict) else None) or {}
328
+ retry_after = _parse_retry_after(e.headers.get("retry-after") if e.headers else None)
329
+ api_error = VardicApiError(
330
+ e.code, err.get("code", "http_error"), err.get("message", f"HTTP {e.code}"), parsed,
331
+ request_id=(e.headers.get("x-request-id") if e.headers else None) or ((parsed.get("meta") or {}).get("requestId") if isinstance(parsed, dict) else None),
332
+ retry_after=retry_after)
333
+ except (socket.timeout, TimeoutError):
334
+ raise VardicApiError(0, "timeout", f"No response within {self.timeout} s") from None
335
+ except urllib.error.URLError as e:
336
+ if isinstance(e.reason, (socket.timeout, TimeoutError)):
337
+ raise VardicApiError(0, "timeout", f"No response within {self.timeout} s") from None
338
+ raise VardicApiError(0, "network_error", str(e.reason)) from None
339
+ except OSError as e:
340
+ raise VardicApiError(0, "network_error", str(e)) from None
341
+
342
+ retryable = api_error.status in (429, 503) and api_error.code not in _NO_RETRY_CODES
343
+ if not retryable or attempt >= self.max_retries:
344
+ raise api_error
345
+ wait = retry_after if retry_after is not None else 0.5 * 2 ** attempt
346
+ if wait > _MAX_RETRY_WAIT_SECS:
347
+ raise api_error
348
+ time.sleep(wait)
349
+ attempt += 1
350
+
351
+
352
+ def verify_webhook(raw_body: Union[bytes, str], header: Optional[str], secret: str, tolerance_secs: int = 300) -> bool:
353
+ """Check the vardic-signature header of a webhook. raw_body must be the exact bytes received."""
354
+ try:
355
+ parts = dict(p.strip().split("=", 1) for p in str(header).split(","))
356
+ ts = int(parts["t"])
357
+ except (KeyError, ValueError):
358
+ return False
359
+ if abs(time.time() - ts) > tolerance_secs:
360
+ return False
361
+ body = raw_body.encode("utf-8") if isinstance(raw_body, str) else bytes(raw_body)
362
+ expected = hmac.new(secret.encode("utf-8"), f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
363
+ return hmac.compare_digest(expected, parts.get("v1", ""))
vardic/py.typed ADDED
File without changes
vardic/types.py ADDED
@@ -0,0 +1,23 @@
1
+ """Typed shapes for request payloads. Responses are plain dicts shaped like https://vardic.dev/docs/openapi"""
2
+ from __future__ import annotations
3
+
4
+ from typing import List, TypedDict
5
+
6
+ __all__ = ["ScreenQuery"]
7
+
8
+
9
+ class _ScreenQueryRequired(TypedDict):
10
+ name: str # 2 to 200 characters
11
+
12
+
13
+ class ScreenQuery(_ScreenQueryRequired, total=False):
14
+ """A sanctions screening query. Only name is required."""
15
+
16
+ type: str # individual, entity, vessel, aircraft or any
17
+ dob: str # YYYY, YYYY-MM or YYYY-MM-DD
18
+ country: str # ISO 3166 alpha-2
19
+ lists: List[str] # uk, ofac_sdn, ofac_cons, eu
20
+ threshold: int # 50 to 100, default 80
21
+ limit: int # 1 to 50, default 10
22
+ record: bool # keep a screening record and PDF certificate
23
+ reference: str # your own reference, up to 100 characters
@@ -0,0 +1,221 @@
1
+ Metadata-Version: 2.4
2
+ Name: vardic
3
+ Version: 1.0.0
4
+ Summary: Official Vardic SDK for Python: UK vehicle data (DVLA and MOT), company checks, sanctions screening, company monitoring, postcodes and fuel prices on one API key.
5
+ Author-email: Vardic <hello@vardic.dev>
6
+ Maintainer-email: Vardic <hello@vardic.dev>
7
+ License: MIT
8
+ Project-URL: Homepage, https://vardic.dev
9
+ Project-URL: Documentation, https://vardic.dev/docs
10
+ Project-URL: Source, https://github.com/vardic-dev/vardic-python
11
+ Project-URL: Issues, https://github.com/vardic-dev/vardic-python/issues
12
+ Project-URL: Changelog, https://github.com/vardic-dev/vardic-python/blob/main/CHANGELOG.md
13
+ Keywords: vardic,sdk,api-client,uk,dvla,mot-history,vehicle-data,companies-house,kyb,sanctions,eori,postcode,fuel-prices,webhooks
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.9
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Dynamic: license-file
29
+
30
+ # Vardic for Python
31
+
32
+ [![CI](https://github.com/vardic-dev/vardic-python/actions/workflows/ci.yml/badge.svg)](https://github.com/vardic-dev/vardic-python/actions/workflows/ci.yml) [![Licence: MIT](https://img.shields.io/badge/licence-MIT-blue.svg)](LICENSE)
33
+
34
+ The official Python SDK for [Vardic](https://vardic.dev): UK vehicle data, company checks, sanctions screening, company monitoring, postcodes and fuel prices on one API key.
35
+
36
+ ```python
37
+ from vardic import Vardic
38
+
39
+ vardic = Vardic() # reads VARDIC_API_KEY
40
+ car = vardic.vehicle.get("AB12 CDE")
41
+ co = vardic.business.check("00445790") # Tesco PLC
42
+ hit = vardic.sanctions.screen({"name": "Example Trading Sanctioned LLC", "type": "entity"})
43
+ area = vardic.location.postcode("SW1A 1AA")
44
+ fuel = vardic.location.fuel_nearest(postcode="SW1A 1AA", fuel="E10", limit=3)
45
+
46
+ print(car["data"]["make"], car["data"]["mot"]["status"], co["data"]["company"]["name"], co["data"]["risk"])
47
+ print(hit["data"]["matchCount"], area["data"]["areas"]["localAuthority"]["name"], fuel["data"]["items"][0]["price"])
48
+ ```
49
+
50
+ ## Install
51
+
52
+ ```sh
53
+ pip install vardic
54
+ ```
55
+
56
+ Python 3.9+, standard library only. Type hints are included (`py.typed`).
57
+
58
+ Get a free key at https://vardic.dev/signup. Set it as `VARDIC_API_KEY`, or pass it to the constructor.
59
+
60
+ ## What is covered
61
+
62
+ One client, one namespace per product. Method names are snake_case here and camelCase in the [JavaScript SDK](https://github.com/vardic-dev/vardic-node) (`fuel_nearest` and `fuelNearest`).
63
+
64
+ | Namespace | Methods | API |
65
+ | --- | --- | --- |
66
+ | `vardic.vehicle` | `get`, `bulk` | DVLA vehicle record, DVSA MOT history, mileage checks, estimated clean air zone status |
67
+ | `vardic.business` | `check`, `officers`, `psc`, `charges`, `filings`, `ownership`, `search`, `eori`, `vat` | Companies House, charity status, EORI, risk flags |
68
+ | `vardic.sanctions` | `screen`, `screen_bulk`, `screen_csv`, `list_checks`, `get_check`, `delete_check`, `certificate`, `check_csv`, `lists` | UK, US (OFAC) and EU sanctions lists, screening records and certificates |
69
+ | `vardic.monitoring` | `list`, `create`, `create_many`, `delete`, `test_event` | Signed webhooks and email digests for vehicles, companies and monitored names |
70
+ | `vardic.location` | `postcode`, `fuel_nearest`, `fuel_station`, `fuel_history` | Postcode area codes, flood risk, crime and schools; UK fuel prices |
71
+ | `vardic` | `account`, `status` | Plan and usage; public service status |
72
+
73
+ Every call returns the parsed `{"data": ..., "meta": ...}` response, except `monitoring.delete` (`None`), `sanctions.certificate` (bytes) and the CSV downloads (text).
74
+
75
+ ### Vehicles
76
+
77
+ ```python
78
+ car = vardic.vehicle.get("AB12 CDE")["data"] # spaces and case are ignored
79
+ print(car["make"], car["model"], car["tax"]["status"], car["mot"]["expiryDate"])
80
+ print(car["mileage"]["anomalyFound"], (car["cleanAirZone"] or {}).get("result"))
81
+
82
+ rows = vardic.vehicle.bulk(["AB12CDE", "TL12OLD"])["data"] # up to 25
83
+ ```
84
+
85
+ ### Business checks
86
+
87
+ ```python
88
+ data = vardic.business.check("00445790", include=["officers", "psc"], eori="GB123456789000")["data"]
89
+ for f in data["flags"]:
90
+ print(f["severity"], f["message"])
91
+
92
+ vardic.business.officers("00445790", page=1, size=50)
93
+ vardic.business.filings("00445790", category="accounts")
94
+ vardic.business.ownership("00445790", depth=2)
95
+ vardic.business.search("tesco")
96
+ vardic.business.eori("GB123456789000")
97
+ ```
98
+
99
+ UK VAT number checks are not open yet: until they are, `vardic.business.vat()` fails with a 503 `upstream_unavailable` that is not counted, and `vat` in a company check is null. EORI checks cover UK (GB) numbers only.
100
+
101
+ ### Sanctions screening
102
+
103
+ ```python
104
+ data = vardic.sanctions.screen({"name": "Ivan Sandboxov", "type": "individual", "dob": "1965", "threshold": 85})["data"]
105
+ for m in data["matches"]:
106
+ print(m["score"], m["list"], m["matchedName"])
107
+
108
+ vardic.sanctions.screen_bulk([{"name": "A Name"}, {"name": "Another Name", "country": "RU"}]) # up to 25
109
+ summary = vardic.sanctions.screen_csv(csv_text, record=True)
110
+ pdf = vardic.sanctions.certificate(summary["data"]["checkId"]) # bytes
111
+ ```
112
+
113
+ Screening is a screening aid, not legal advice: review every potential match. Names are never logged; they are stored only when you ask for a screening record.
114
+
115
+ ### Monitoring and webhooks
116
+
117
+ ```python
118
+ vardic.monitoring.create(registration="AB12CDE", url="https://example.com/hooks/vardic", days_before=[30, 7, 1])
119
+ vardic.monitoring.create(company_number="00445790", url="https://example.com/hooks/vardic", email_digest=True)
120
+ vardic.monitoring.create_many(["00445790", "SC123456"], url="https://example.com/hooks/vardic")
121
+
122
+ watches = vardic.monitoring.list()["data"]
123
+ vardic.monitoring.delete(watches[0]["id"])
124
+ vardic.monitoring.test_event("https://example.com/hooks/vardic", type="company.filing")
125
+ ```
126
+
127
+ Watches need a live key. A sandbox key can still send a signed sample with `test_event`. Event types and payloads: https://vardic.dev/docs/webhooks
128
+
129
+ Verify every delivery with the `vardic-signature` header and your webhook secret (from `vardic.account()`). Reject anything older than five minutes (the default tolerance).
130
+
131
+ ```python
132
+ from vardic import verify_webhook
133
+
134
+ # raw_body must be the exact bytes received, not re-serialised JSON
135
+ ok = verify_webhook(raw_body, request.headers["vardic-signature"], WEBHOOK_SECRET)
136
+ if not ok:
137
+ abort(400)
138
+ ```
139
+
140
+ ### Postcodes and fuel
141
+
142
+ ```python
143
+ data = vardic.location.postcode("SW1A 1AA", include=["areas", "flood"], schools=3)["data"]
144
+ cheapest = vardic.location.fuel_nearest(postcode="SW1A 1AA", fuel="E10", radius=5)["data"]
145
+ vardic.location.fuel_station(cheapest["items"][0]["station"]["id"])
146
+ vardic.location.fuel_history(cheapest["items"][0]["station"]["id"], days=30)
147
+ ```
148
+
149
+ Postcode checks cover Great Britain; a Northern Ireland, Channel Islands or Isle of Man postcode fails with `unsupported_region`.
150
+
151
+ ### Account and status
152
+
153
+ ```python
154
+ account = vardic.account()["data"] # plans, usage this month, webhook secret
155
+ status = vardic.status()["data"] # public service status
156
+ ```
157
+
158
+ ## Options
159
+
160
+ ```python
161
+ vardic = Vardic(
162
+ api_key="vd_live_...", # default: the VARDIC_API_KEY environment variable
163
+ timeout=10.0, # seconds, per attempt, default 15
164
+ max_retries=2, # on 429 and 503, default 2
165
+ base_url="https://api.vardic.dev",
166
+ )
167
+ ```
168
+
169
+ ## Errors
170
+
171
+ Failed calls raise `VardicApiError` with `status`, `code`, `message`, `request_id` (from the `x-request-id` header; quote it if you contact support), `body` (the parsed error response) and `retry_after`.
172
+
173
+ ```python
174
+ from vardic import VardicApiError
175
+
176
+ try:
177
+ vardic.vehicle.get("ZZ99ZZZ")
178
+ except VardicApiError as e:
179
+ print(e.status, e.code, e.request_id) # 404 vehicle_not_found req_...
180
+ ```
181
+
182
+ Timeouts and network failures raise the same class with status `0` and code `timeout` or `network_error`. The full code list is at https://vardic.dev/docs/errors, for example `invalid_registration` (400), `vehicle_not_found` (404), `quota_exceeded` (429) and `upstream_unavailable` (503).
183
+
184
+ ### Retries
185
+
186
+ The SDK retries 429 and 503 responses up to twice, waiting for the `Retry-After` header (or 0.5 s then 1 s without one). It never retries `quota_exceeded` or `coming_soon`, which retrying cannot fix, and it gives up at once when `Retry-After` is longer than 30 seconds. 400, 401 and 404 are never retried. Failed calls that return 429 or 503 are not counted against your allowance.
187
+
188
+ ## Sandbox keys
189
+
190
+ Every account gets a `vd_test_` key as well as a live key. It returns realistic made-up data for any input, never counts towards your allowance and allows 5 requests a second. Special values:
191
+
192
+ - Vehicle `ZZ99ZZZ` returns `vehicle_not_found`; `TL12OLD` returns a 2012 diesel with a mileage reading that went down.
193
+ - Company `00000000` returns `company_not_found`.
194
+ - Sanctions names `Example Trading Sanctioned LLC`, `Ivan Sandboxov` and `Sandbox Example Bank` return fictional matches; any other name returns none.
195
+ - Postcode `ZZ1 1ZZ` returns `postcode_not_found`.
196
+
197
+ All sandbox values: https://vardic.dev/docs/sandbox
198
+
199
+ ## Pricing
200
+
201
+ Every product has a free monthly allowance on one key, no card needed: 100 vehicle lookups, 50 business checks, 50 sanctions screens, 5 watched companies, 100 postcode checks and 1,000 fuel requests. Paid plans and prices: https://vardic.dev/pricing
202
+
203
+ ## Links
204
+
205
+ - Get a free key: https://vardic.dev/signup
206
+ - API docs: https://vardic.dev/docs
207
+ - OpenAPI files: https://vardic.dev/docs/openapi
208
+ - Service status: https://vardic.dev/status
209
+ - JavaScript SDK: https://github.com/vardic-dev/vardic-node
210
+ - Examples: [examples/](examples/)
211
+ - Changelog: [CHANGELOG.md](CHANGELOG.md)
212
+ - Contributing: [CONTRIBUTING.md](CONTRIBUTING.md)
213
+ - Security: [SECURITY.md](SECURITY.md)
214
+
215
+ ## Data
216
+
217
+ Contains public sector information licensed under the Open Government Licence v3.0, from the DVLA, DVSA, Companies House, the Charity Commission, the Environment Agency, the Office for National Statistics, police.uk and Fuel Finder. EORI data from HMRC. Sanctions lists are published by the UK, US (OFAC) and EU authorities; screening results are a screening aid, not legal advice. Each response carries its licence text in `meta.attribution`: show it wherever you display the data to others. Not affiliated with or endorsed by any of the government bodies whose data we use. Clean air zone results are estimates: check the official TfL or GOV.UK vehicle checker before relying on one.
218
+
219
+ ## Licence
220
+
221
+ MIT. Made by [Vardic](https://vardic.dev).
@@ -0,0 +1,8 @@
1
+ vardic/__init__.py,sha256=c1j1rQ2Z5czBaSmidQZI-e6Yquh1-_Ax1KWC0XYa_hs,17743
2
+ vardic/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ vardic/types.py,sha256=V58PLzuTm-CKIGaHgtbUmOJSDqLGJBwPf51CkrwsKsw,809
4
+ vardic-1.0.0.dist-info/licenses/LICENSE,sha256=0hNGh_wfm73C9lFOODx1CSj2OoZRAVsIeST3E7KltRQ,1063
5
+ vardic-1.0.0.dist-info/METADATA,sha256=3abGHosKMa_tktmaT8QDx8Z4mhdamnMeJarv6B5zinA,10843
6
+ vardic-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ vardic-1.0.0.dist-info/top_level.txt,sha256=1j-h41E7vfFN_CdSshveFBXjrTYzrhukX-Bw0gebR2w,7
8
+ vardic-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vardic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ vardic