ipdatum 1.0.0__tar.gz

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,5 @@
1
+ dist/
2
+ *.egg-info/
3
+ __pycache__/
4
+ *.pyc
5
+ .venv/
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 — 2026-11-30
4
+ - Initial release of the official `ipdatum` Python SDK.
5
+ - Zero runtime dependencies (pure Python 3.9+ stdlib).
6
+ - Supports `lookup()`, `batch()`, `asn()`, `dns()`, `whois()`, and `health()`.
7
+ - Forward-compatible typed dataclass models with `.raw` dict escape hatch, `IPDatumError` with `retry_after`, and `last_rate_limit` tracking.
ipdatum-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 IPDatum
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.
ipdatum-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.5
2
+ Name: ipdatum
3
+ Version: 1.0.0
4
+ Summary: Official zero-dependency Python SDK for IPDatum — dual-stack IPv4/IPv6 geolocation, ASN metadata, VPN/proxy/Tor detection, DNS, and RDAP/WHOIS intelligence.
5
+ Project-URL: Homepage, https://www.ipdatum.com
6
+ Project-URL: Documentation, https://www.ipdatum.com/docs
7
+ Project-URL: MCP Server, https://www.ipdatum.com/docs/mcp
8
+ Project-URL: Get API Key, https://www.ipdatum.com/dashboard
9
+ Project-URL: Repository, https://github.com/ipdatum/ipdatum-python
10
+ Project-URL: Issues, https://github.com/ipdatum/ipdatum-python/issues
11
+ Project-URL: Changelog, https://github.com/ipdatum/ipdatum-python/blob/main/CHANGELOG.md
12
+ Author-email: IPDatum <support@ipdatum.com>
13
+ License-Expression: MIT
14
+ License-File: LICENSE
15
+ Keywords: asn,geolocation,ip,ip-geolocation,ip-intelligence,ip-lookup,rdap,vpn-detection,whois
16
+ Classifier: Development Status :: 5 - Production/Stable
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: License :: OSI Approved :: MIT License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.9
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: 3.13
26
+ Classifier: Topic :: Internet
27
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.9
30
+ Description-Content-Type: text/markdown
31
+
32
+ # ipdatum
33
+
34
+ Official zero-dependency Python SDK for [IPDatum](https://www.ipdatum.com) — dual-stack IPv4 & IPv6 geolocation, ASN metadata, VPN/proxy/Tor/cloud detection, reverse & forward DNS, and RDAP/WHOIS intelligence.
35
+
36
+ Works immediately on the **free keyless tier (1,000 requests/day)** or with an API key from the [IPDatum Dashboard](https://www.ipdatum.com/dashboard).
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ python -m pip install ipdatum
42
+ ```
43
+
44
+ Requires Python 3.9+ (zero third-party runtime dependencies).
45
+
46
+ ## Quick Start
47
+
48
+ ```python
49
+ from ipdatum import IPDatumClient
50
+
51
+ with IPDatumClient() as client: # or IPDatumClient(api_key="ipd_...")
52
+ info = client.lookup("88.198.47.21")
53
+ print(info.location.city, info.location.country, info.security.is_vpn)
54
+ print(client.last_rate_limit)
55
+ ```
56
+
57
+ ## Batch, ASN, DNS & WHOIS
58
+
59
+ ```python
60
+ from ipdatum import IPDatumClient
61
+
62
+ client = IPDatumClient()
63
+
64
+ # Up to 100 IPv4/IPv6 addresses (no-code tool: https://www.ipdatum.com/bulk-ip-lookup)
65
+ batch_res = client.batch(["8.8.8.8", "2606:4700:4700::1111"])
66
+
67
+ # ASN metadata & RDAP prefixes
68
+ google_asn = client.asn("AS15169")
69
+
70
+ # Reverse PTR or forward A/AAAA resolution + IP intelligence
71
+ dns_res = client.dns("8.8.8.8")
72
+
73
+ # RDAP / WHOIS for an IP, ASN, or domain
74
+ whois_res = client.whois("8.8.8.8")
75
+ ```
76
+
77
+ ## Error Handling
78
+
79
+ ```python
80
+ from ipdatum import IPDatumClient, IPDatumError
81
+
82
+ client = IPDatumClient()
83
+ try:
84
+ client.lookup("999.999.999.999")
85
+ except IPDatumError as exc:
86
+ print(exc.status_code, exc.code, exc.retry_after, str(exc))
87
+ ```
88
+
89
+ ## Documentation & Links
90
+
91
+ - **API Reference:** [https://www.ipdatum.com/docs](https://www.ipdatum.com/docs)
92
+ - **Remote MCP Server (Claude / Cursor / AI Agents):** [https://www.ipdatum.com/docs/mcp](https://www.ipdatum.com/docs/mcp)
93
+ - **API Keys & Usage Dashboard:** [https://www.ipdatum.com/dashboard](https://www.ipdatum.com/dashboard)
94
+ - **Source Code:** [https://github.com/ipdatum/ipdatum-python](https://github.com/ipdatum/ipdatum-python)
95
+
96
+ ## License
97
+
98
+ MIT — see [LICENSE](https://github.com/ipdatum/ipdatum-python/blob/main/LICENSE).
@@ -0,0 +1,67 @@
1
+ # ipdatum
2
+
3
+ Official zero-dependency Python SDK for [IPDatum](https://www.ipdatum.com) — dual-stack IPv4 & IPv6 geolocation, ASN metadata, VPN/proxy/Tor/cloud detection, reverse & forward DNS, and RDAP/WHOIS intelligence.
4
+
5
+ Works immediately on the **free keyless tier (1,000 requests/day)** or with an API key from the [IPDatum Dashboard](https://www.ipdatum.com/dashboard).
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ python -m pip install ipdatum
11
+ ```
12
+
13
+ Requires Python 3.9+ (zero third-party runtime dependencies).
14
+
15
+ ## Quick Start
16
+
17
+ ```python
18
+ from ipdatum import IPDatumClient
19
+
20
+ with IPDatumClient() as client: # or IPDatumClient(api_key="ipd_...")
21
+ info = client.lookup("88.198.47.21")
22
+ print(info.location.city, info.location.country, info.security.is_vpn)
23
+ print(client.last_rate_limit)
24
+ ```
25
+
26
+ ## Batch, ASN, DNS & WHOIS
27
+
28
+ ```python
29
+ from ipdatum import IPDatumClient
30
+
31
+ client = IPDatumClient()
32
+
33
+ # Up to 100 IPv4/IPv6 addresses (no-code tool: https://www.ipdatum.com/bulk-ip-lookup)
34
+ batch_res = client.batch(["8.8.8.8", "2606:4700:4700::1111"])
35
+
36
+ # ASN metadata & RDAP prefixes
37
+ google_asn = client.asn("AS15169")
38
+
39
+ # Reverse PTR or forward A/AAAA resolution + IP intelligence
40
+ dns_res = client.dns("8.8.8.8")
41
+
42
+ # RDAP / WHOIS for an IP, ASN, or domain
43
+ whois_res = client.whois("8.8.8.8")
44
+ ```
45
+
46
+ ## Error Handling
47
+
48
+ ```python
49
+ from ipdatum import IPDatumClient, IPDatumError
50
+
51
+ client = IPDatumClient()
52
+ try:
53
+ client.lookup("999.999.999.999")
54
+ except IPDatumError as exc:
55
+ print(exc.status_code, exc.code, exc.retry_after, str(exc))
56
+ ```
57
+
58
+ ## Documentation & Links
59
+
60
+ - **API Reference:** [https://www.ipdatum.com/docs](https://www.ipdatum.com/docs)
61
+ - **Remote MCP Server (Claude / Cursor / AI Agents):** [https://www.ipdatum.com/docs/mcp](https://www.ipdatum.com/docs/mcp)
62
+ - **API Keys & Usage Dashboard:** [https://www.ipdatum.com/dashboard](https://www.ipdatum.com/dashboard)
63
+ - **Source Code:** [https://github.com/ipdatum/ipdatum-python](https://github.com/ipdatum/ipdatum-python)
64
+
65
+ ## License
66
+
67
+ MIT — see [LICENSE](https://github.com/ipdatum/ipdatum-python/blob/main/LICENSE).
@@ -0,0 +1,4 @@
1
+ # Security Policy
2
+
3
+ Please report security vulnerabilities to support@ipdatum.com.
4
+ Zero hidden telemetry: this SDK only sends requests to the configured IPDatum API base URL (`https://api.ipdatum.com` by default).
@@ -0,0 +1,68 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25.0"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ipdatum"
7
+ version = "1.0.0"
8
+ description = "Official zero-dependency Python SDK for IPDatum — dual-stack IPv4/IPv6 geolocation, ASN metadata, VPN/proxy/Tor detection, DNS, and RDAP/WHOIS intelligence."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ authors = [
13
+ { name = "IPDatum", email = "support@ipdatum.com" },
14
+ ]
15
+ keywords = [
16
+ "ip",
17
+ "ip-geolocation",
18
+ "geolocation",
19
+ "ip-lookup",
20
+ "asn",
21
+ "whois",
22
+ "rdap",
23
+ "vpn-detection",
24
+ "ip-intelligence",
25
+ ]
26
+ classifiers = [
27
+ "Development Status :: 5 - Production/Stable",
28
+ "Intended Audience :: Developers",
29
+ "License :: OSI Approved :: MIT License",
30
+ "Operating System :: OS Independent",
31
+ "Programming Language :: Python :: 3",
32
+ "Programming Language :: Python :: 3.9",
33
+ "Programming Language :: Python :: 3.10",
34
+ "Programming Language :: Python :: 3.11",
35
+ "Programming Language :: Python :: 3.12",
36
+ "Programming Language :: Python :: 3.13",
37
+ "Topic :: Internet",
38
+ "Topic :: Software Development :: Libraries :: Python Modules",
39
+ "Typing :: Typed",
40
+ ]
41
+ dependencies = []
42
+
43
+ [project.urls]
44
+ Homepage = "https://www.ipdatum.com"
45
+ Documentation = "https://www.ipdatum.com/docs"
46
+ "MCP Server" = "https://www.ipdatum.com/docs/mcp"
47
+ "Get API Key" = "https://www.ipdatum.com/dashboard"
48
+ Repository = "https://github.com/ipdatum/ipdatum-python"
49
+ Issues = "https://github.com/ipdatum/ipdatum-python/issues"
50
+ Changelog = "https://github.com/ipdatum/ipdatum-python/blob/main/CHANGELOG.md"
51
+
52
+ [tool.hatch.build]
53
+ ignore-vcs = true
54
+
55
+ [tool.hatch.build.targets.sdist]
56
+ include = [
57
+ "src/ipdatum/**/*.py",
58
+ "src/ipdatum/py.typed",
59
+ "tests/**/*.py",
60
+ "README.md",
61
+ "LICENSE",
62
+ "CHANGELOG.md",
63
+ "SECURITY.md",
64
+ "pyproject.toml",
65
+ ]
66
+
67
+ [tool.hatch.build.targets.wheel]
68
+ packages = ["src/ipdatum"]
@@ -0,0 +1,47 @@
1
+ """Official zero-dependency Python SDK for IPDatum (https://www.ipdatum.com)."""
2
+
3
+ from .client import DEFAULT_BASE_URL, DEFAULT_TIMEOUT, IPDatumClient, SDK_VERSION, asn, batch, dns, health, lookup, whois
4
+ from .errors import IPDatumError
5
+ from .models import (
6
+ AsnLookupResponse,
7
+ BatchErrorItem,
8
+ BatchLookupResponse,
9
+ BatchResultItem,
10
+ DnsLookupResponse,
11
+ HealthResponse,
12
+ IpLocation,
13
+ IpLookupResponse,
14
+ IpNetwork,
15
+ IpSecurity,
16
+ RateLimitInfo,
17
+ WhoisLookupResponse,
18
+ )
19
+
20
+ __version__ = SDK_VERSION
21
+
22
+ __all__ = [
23
+ "DEFAULT_BASE_URL",
24
+ "DEFAULT_TIMEOUT",
25
+ "SDK_VERSION",
26
+ "__version__",
27
+ "IPDatumClient",
28
+ "IPDatumError",
29
+ "AsnLookupResponse",
30
+ "BatchErrorItem",
31
+ "BatchLookupResponse",
32
+ "BatchResultItem",
33
+ "DnsLookupResponse",
34
+ "HealthResponse",
35
+ "IpLocation",
36
+ "IpLookupResponse",
37
+ "IpNetwork",
38
+ "IpSecurity",
39
+ "RateLimitInfo",
40
+ "WhoisLookupResponse",
41
+ "asn",
42
+ "batch",
43
+ "dns",
44
+ "health",
45
+ "lookup",
46
+ "whois",
47
+ ]
@@ -0,0 +1,296 @@
1
+ """Pure-stdlib synchronous client for the IPDatum API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import email.utils
6
+ import json
7
+ import math
8
+ import time
9
+ import urllib.error
10
+ import urllib.parse
11
+ import urllib.request
12
+ from typing import Any, Optional, Sequence, Union
13
+
14
+ from .errors import IPDatumError
15
+ from .models import (
16
+ AsnLookupResponse,
17
+ BatchLookupResponse,
18
+ DnsLookupResponse,
19
+ HealthResponse,
20
+ IpLookupResponse,
21
+ RateLimitInfo,
22
+ WhoisLookupResponse,
23
+ )
24
+
25
+ DEFAULT_BASE_URL = "https://api.ipdatum.com"
26
+ DEFAULT_TIMEOUT = 10.0
27
+ SDK_VERSION = "1.0.0"
28
+
29
+
30
+ def _parse_int_header(headers: Any, name: str) -> Optional[int]:
31
+ val = headers.get(name) if headers is not None else None
32
+ if not val:
33
+ return None
34
+ try:
35
+ return int(str(val).strip())
36
+ except ValueError:
37
+ return None
38
+
39
+
40
+ def _parse_retry_after(headers: Any) -> Optional[int]:
41
+ val = headers.get("Retry-After") if headers is not None else None
42
+ if not val:
43
+ return None
44
+ raw = str(val).strip()
45
+ if raw.isdigit():
46
+ return int(raw)
47
+ try:
48
+ dt = email.utils.parsedate_to_datetime(raw)
49
+ return max(0, math.ceil(dt.timestamp() - time.time()))
50
+ except (TypeError, ValueError):
51
+ return None
52
+
53
+
54
+ def _validate_path_value(value: str, label: str) -> str:
55
+ trimmed = value.strip()
56
+ if not trimmed:
57
+ raise IPDatumError(f"{label} must not be empty", code="invalid_input")
58
+ if any(bad in trimmed for bad in ("/", "\\", "..", "%", "?", "#")):
59
+ raise IPDatumError(
60
+ f"{label} contains invalid path characters: {trimmed}",
61
+ code="invalid_input",
62
+ )
63
+ return urllib.parse.quote(trimmed, safe="")
64
+
65
+
66
+ class IPDatumClient:
67
+ """Reusable client for https://api.ipdatum.com."""
68
+
69
+ def __init__(
70
+ self,
71
+ api_key: Optional[str] = None,
72
+ *,
73
+ base_url: str = DEFAULT_BASE_URL,
74
+ timeout: float = DEFAULT_TIMEOUT,
75
+ user_agent: Optional[str] = None,
76
+ ) -> None:
77
+ self.api_key = api_key.strip() if api_key else None
78
+ self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
79
+ self.timeout = timeout
80
+ self.user_agent = user_agent or f"ipdatum-python/{SDK_VERSION}"
81
+ self.last_rate_limit: Optional[RateLimitInfo] = None
82
+
83
+ def __enter__(self) -> IPDatumClient:
84
+ return self
85
+
86
+ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
87
+ self.close()
88
+
89
+ def close(self) -> None:
90
+ """Close hook for context-manager compatibility (stateless stdlib transport)."""
91
+ return None
92
+
93
+ def lookup(
94
+ self,
95
+ ip: Optional[str] = None,
96
+ *,
97
+ timeout: Optional[float] = None,
98
+ ) -> IpLookupResponse:
99
+ """Look up geolocation, ASN, and security flags for an IP (or caller IP when omitted)."""
100
+ trimmed = (ip or "").strip()
101
+ path = f"/v1/ip/{_validate_path_value(trimmed, 'ip')}" if trimmed else "/v1/ip"
102
+ return IpLookupResponse.from_dict(self._request("GET", path, timeout=timeout))
103
+
104
+ def batch(
105
+ self,
106
+ ips: Sequence[str],
107
+ *,
108
+ timeout: Optional[float] = None,
109
+ ) -> BatchLookupResponse:
110
+ """Look up 1 to 100 IPv4/IPv6 addresses in one POST /v1/ip/batch call."""
111
+ ip_list = list(ips)
112
+ if not ip_list or len(ip_list) > 100:
113
+ raise IPDatumError(
114
+ "batch(ips) requires between 1 and 100 IP addresses",
115
+ code="invalid_batch_size",
116
+ )
117
+ return BatchLookupResponse.from_dict(
118
+ self._request("POST", "/v1/ip/batch", body={"ips": ip_list}, timeout=timeout)
119
+ )
120
+
121
+ def asn(
122
+ self,
123
+ asn_value: Union[int, str],
124
+ *,
125
+ timeout: Optional[float] = None,
126
+ ) -> AsnLookupResponse:
127
+ """Fetch ASN metadata and RDAP details (`15169` or `'AS15169'`)."""
128
+ encoded = _validate_path_value(str(asn_value), "asn")
129
+ return AsnLookupResponse.from_dict(self._request("GET", f"/v1/asn/{encoded}", timeout=timeout))
130
+
131
+ def dns(
132
+ self,
133
+ query: str,
134
+ *,
135
+ timeout: Optional[float] = None,
136
+ ) -> DnsLookupResponse:
137
+ """Perform reverse PTR or forward A/AAAA DNS + IP intelligence lookup."""
138
+ trimmed = query.strip()
139
+ if not trimmed:
140
+ raise IPDatumError("dns(query) requires a non-empty query", code="invalid_input")
141
+ qs = urllib.parse.urlencode({"q": trimmed})
142
+ return DnsLookupResponse.from_dict(self._request("GET", f"/v1/dns?{qs}", timeout=timeout))
143
+
144
+ def whois(
145
+ self,
146
+ query: str,
147
+ *,
148
+ timeout: Optional[float] = None,
149
+ ) -> WhoisLookupResponse:
150
+ """Fetch live RDAP / WHOIS ownership records for an IP, ASN, or domain."""
151
+ encoded = _validate_path_value(query, "whois query")
152
+ return WhoisLookupResponse.from_dict(self._request("GET", f"/v1/whois/{encoded}", timeout=timeout))
153
+
154
+ def health(self, *, timeout: Optional[float] = None) -> HealthResponse:
155
+ """Check API health and active database version."""
156
+ return HealthResponse.from_dict(self._request("GET", "/v1/health", timeout=timeout))
157
+
158
+ def _capture_rate_limit(self, headers: Any) -> RateLimitInfo:
159
+ info = RateLimitInfo(
160
+ limit=_parse_int_header(headers, "X-RateLimit-Limit"),
161
+ remaining=_parse_int_header(headers, "X-RateLimit-Remaining"),
162
+ lookup_ms=_parse_int_header(headers, "X-Lookup-Ms"),
163
+ retry_after=_parse_retry_after(headers),
164
+ )
165
+ self.last_rate_limit = info
166
+ return info
167
+
168
+ def _request(
169
+ self,
170
+ method: str,
171
+ path: str,
172
+ *,
173
+ body: Optional[dict[str, Any]] = None,
174
+ timeout: Optional[float] = None,
175
+ ) -> dict[str, Any]:
176
+ headers = {
177
+ "Accept": "application/json",
178
+ "User-Agent": self.user_agent,
179
+ }
180
+ if self.api_key:
181
+ headers["Authorization"] = f"Bearer {self.api_key}"
182
+
183
+ payload: Optional[bytes] = None
184
+ if body is not None:
185
+ headers["Content-Type"] = "application/json"
186
+ payload = json.dumps(body).encode("utf-8")
187
+
188
+ req = urllib.request.Request(f"{self.base_url}{path}", data=payload, headers=headers, method=method)
189
+ eff_timeout = self.timeout if timeout is None else timeout
190
+
191
+ try:
192
+ with urllib.request.urlopen(req, timeout=eff_timeout) as resp:
193
+ self._capture_rate_limit(resp.headers)
194
+ raw_text = resp.read().decode("utf-8", errors="replace")
195
+ try:
196
+ data = json.loads(raw_text)
197
+ except json.JSONDecodeError as exc:
198
+ raise IPDatumError(
199
+ "Expected JSON response from IPDatum API",
200
+ status_code=resp.status,
201
+ code="invalid_json",
202
+ body=raw_text,
203
+ ) from exc
204
+ if not isinstance(data, dict):
205
+ raise IPDatumError(
206
+ "Unexpected JSON payload shape from IPDatum API",
207
+ status_code=resp.status,
208
+ code="invalid_json",
209
+ body=raw_text,
210
+ )
211
+ return data
212
+ except urllib.error.HTTPError as err:
213
+ rl = self._capture_rate_limit(err.headers)
214
+ raw_text = err.read().decode("utf-8", errors="replace") if err.fp else ""
215
+ code = f"http_{err.code}"
216
+ msg = f"IPDatum API error ({err.code})"
217
+ if raw_text:
218
+ try:
219
+ parsed = json.loads(raw_text)
220
+ if isinstance(parsed, dict):
221
+ if isinstance(parsed.get("error"), str):
222
+ code = parsed["error"]
223
+ if isinstance(parsed.get("message"), str):
224
+ msg = parsed["message"]
225
+ except json.JSONDecodeError:
226
+ pass
227
+ raise IPDatumError(
228
+ msg,
229
+ status_code=err.code,
230
+ code=code,
231
+ retry_after=rl.retry_after,
232
+ body=raw_text,
233
+ ) from err
234
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
235
+ reason = getattr(exc, "reason", exc)
236
+ code = "timeout" if isinstance(reason, TimeoutError) or "timed out" in str(reason).lower() else "network_error"
237
+ raise IPDatumError(str(reason), code=code) from exc
238
+
239
+
240
+ def lookup(
241
+ ip: Optional[str] = None,
242
+ *,
243
+ api_key: Optional[str] = None,
244
+ base_url: str = DEFAULT_BASE_URL,
245
+ timeout: float = DEFAULT_TIMEOUT,
246
+ ) -> IpLookupResponse:
247
+ return IPDatumClient(api_key=api_key, base_url=base_url, timeout=timeout).lookup(ip)
248
+
249
+
250
+ def batch(
251
+ ips: Sequence[str],
252
+ *,
253
+ api_key: Optional[str] = None,
254
+ base_url: str = DEFAULT_BASE_URL,
255
+ timeout: float = DEFAULT_TIMEOUT,
256
+ ) -> BatchLookupResponse:
257
+ return IPDatumClient(api_key=api_key, base_url=base_url, timeout=timeout).batch(ips)
258
+
259
+
260
+ def asn(
261
+ asn_value: Union[int, str],
262
+ *,
263
+ api_key: Optional[str] = None,
264
+ base_url: str = DEFAULT_BASE_URL,
265
+ timeout: float = DEFAULT_TIMEOUT,
266
+ ) -> AsnLookupResponse:
267
+ return IPDatumClient(api_key=api_key, base_url=base_url, timeout=timeout).asn(asn_value)
268
+
269
+
270
+ def dns(
271
+ query: str,
272
+ *,
273
+ api_key: Optional[str] = None,
274
+ base_url: str = DEFAULT_BASE_URL,
275
+ timeout: float = DEFAULT_TIMEOUT,
276
+ ) -> DnsLookupResponse:
277
+ return IPDatumClient(api_key=api_key, base_url=base_url, timeout=timeout).dns(query)
278
+
279
+
280
+ def whois(
281
+ query: str,
282
+ *,
283
+ api_key: Optional[str] = None,
284
+ base_url: str = DEFAULT_BASE_URL,
285
+ timeout: float = DEFAULT_TIMEOUT,
286
+ ) -> WhoisLookupResponse:
287
+ return IPDatumClient(api_key=api_key, base_url=base_url, timeout=timeout).whois(query)
288
+
289
+
290
+ def health(
291
+ *,
292
+ api_key: Optional[str] = None,
293
+ base_url: str = DEFAULT_BASE_URL,
294
+ timeout: float = DEFAULT_TIMEOUT,
295
+ ) -> HealthResponse:
296
+ return IPDatumClient(api_key=api_key, base_url=base_url, timeout=timeout).health()
@@ -0,0 +1,29 @@
1
+ """Typed exceptions for the IPDatum Python SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Optional
6
+
7
+
8
+ class IPDatumError(Exception):
9
+ """Raised on validation failures, network/timeout errors, or non-2xx API responses."""
10
+
11
+ def __init__(
12
+ self,
13
+ message: str,
14
+ *,
15
+ status_code: int = 0,
16
+ code: str = "api_error",
17
+ retry_after: Optional[int] = None,
18
+ body: str = "",
19
+ ) -> None:
20
+ super().__init__(message)
21
+ self.status_code = status_code
22
+ self.code = code
23
+ self.retry_after = retry_after
24
+ self.body = body
25
+
26
+ @property
27
+ def is_rate_limited(self) -> bool:
28
+ """Return True if the request failed with HTTP 429 Too Many Requests."""
29
+ return self.status_code == 429
@@ -0,0 +1,251 @@
1
+ """Forward-compatible typed dataclasses for IPDatum API responses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, Optional, Union
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class IpLocation:
11
+ city: Optional[str] = None
12
+ region: Optional[str] = None
13
+ country: Optional[str] = None
14
+ area: Optional[str] = None
15
+ latitude: Optional[float] = None
16
+ longitude: Optional[float] = None
17
+ confidence_level: Optional[str] = None
18
+ accuracy_radius_km: Optional[int] = None
19
+
20
+ @classmethod
21
+ def from_dict(cls, data: Optional[dict[str, Any]]) -> IpLocation:
22
+ d = data if isinstance(data, dict) else {}
23
+ return cls(
24
+ city=d.get("city"),
25
+ region=d.get("region"),
26
+ country=d.get("country"),
27
+ area=d.get("area"),
28
+ latitude=d.get("latitude"),
29
+ longitude=d.get("longitude"),
30
+ confidence_level=d.get("confidence_level"),
31
+ accuracy_radius_km=d.get("accuracy_radius_km"),
32
+ )
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class IpNetwork:
37
+ asn: Optional[int] = None
38
+ org: Optional[str] = None
39
+ org_type: Optional[str] = None
40
+ network_type: Optional[str] = None
41
+
42
+ @classmethod
43
+ def from_dict(cls, data: Optional[dict[str, Any]]) -> IpNetwork:
44
+ d = data if isinstance(data, dict) else {}
45
+ return cls(
46
+ asn=d.get("asn"),
47
+ org=d.get("org"),
48
+ org_type=d.get("org_type"),
49
+ network_type=d.get("network_type"),
50
+ )
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class IpSecurity:
55
+ is_cloud: bool = False
56
+ is_datacenter: bool = False
57
+ is_vpn: bool = False
58
+ is_proxy: bool = False
59
+ is_tor: bool = False
60
+ is_relay: bool = False
61
+ is_abuser: bool = False
62
+ is_mobile: bool = False
63
+ is_satellite: bool = False
64
+ is_anycast: bool = False
65
+ is_ixp: bool = False
66
+ is_bogon: bool = False
67
+
68
+ @classmethod
69
+ def from_dict(cls, data: Optional[dict[str, Any]]) -> IpSecurity:
70
+ d = data if isinstance(data, dict) else {}
71
+ return cls(
72
+ is_cloud=bool(d.get("is_cloud", False)),
73
+ is_datacenter=bool(d.get("is_datacenter", False)),
74
+ is_vpn=bool(d.get("is_vpn", False)),
75
+ is_proxy=bool(d.get("is_proxy", False)),
76
+ is_tor=bool(d.get("is_tor", False)),
77
+ is_relay=bool(d.get("is_relay", False)),
78
+ is_abuser=bool(d.get("is_abuser", False)),
79
+ is_mobile=bool(d.get("is_mobile", False)),
80
+ is_satellite=bool(d.get("is_satellite", False)),
81
+ is_anycast=bool(d.get("is_anycast", False)),
82
+ is_ixp=bool(d.get("is_ixp", False)),
83
+ is_bogon=bool(d.get("is_bogon", False)),
84
+ )
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class IpLookupResponse:
89
+ ip: str
90
+ ip_version: int
91
+ bogon: bool
92
+ location: IpLocation
93
+ network: IpNetwork
94
+ security: IpSecurity
95
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
96
+
97
+ @classmethod
98
+ def from_dict(cls, data: dict[str, Any]) -> IpLookupResponse:
99
+ return cls(
100
+ ip=str(data.get("ip", "")),
101
+ ip_version=int(data.get("ip_version", 4)),
102
+ bogon=bool(data.get("bogon", False)),
103
+ location=IpLocation.from_dict(data.get("location")),
104
+ network=IpNetwork.from_dict(data.get("network")),
105
+ security=IpSecurity.from_dict(data.get("security")),
106
+ raw=dict(data),
107
+ )
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class BatchErrorItem:
112
+ ip: str
113
+ error: str
114
+ message: Optional[str] = None
115
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
116
+
117
+ @classmethod
118
+ def from_dict(cls, data: dict[str, Any]) -> BatchErrorItem:
119
+ return cls(
120
+ ip=str(data.get("ip", "")),
121
+ error=str(data.get("error", "")),
122
+ message=data.get("message"),
123
+ raw=dict(data),
124
+ )
125
+
126
+
127
+ BatchResultItem = Union[IpLookupResponse, BatchErrorItem]
128
+
129
+
130
+ @dataclass(frozen=True)
131
+ class BatchLookupResponse:
132
+ count: int
133
+ results: list[BatchResultItem]
134
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
135
+
136
+ @classmethod
137
+ def from_dict(cls, data: dict[str, Any]) -> BatchLookupResponse:
138
+ items: list[BatchResultItem] = []
139
+ for entry in data.get("results") or []:
140
+ if isinstance(entry, dict) and isinstance(entry.get("error"), str):
141
+ items.append(BatchErrorItem.from_dict(entry))
142
+ elif isinstance(entry, dict):
143
+ items.append(IpLookupResponse.from_dict(entry))
144
+ return cls(
145
+ count=int(data.get("count", len(items))),
146
+ results=items,
147
+ raw=dict(data),
148
+ )
149
+
150
+
151
+ @dataclass(frozen=True)
152
+ class AsnLookupResponse:
153
+ asn: int
154
+ as_label: str
155
+ org: Optional[str] = None
156
+ org_type: Optional[str] = None
157
+ country: Optional[str] = None
158
+ rdap: Optional[dict[str, Any]] = None
159
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
160
+
161
+ @classmethod
162
+ def from_dict(cls, data: dict[str, Any]) -> AsnLookupResponse:
163
+ rdap = data.get("rdap")
164
+ return cls(
165
+ asn=int(data.get("asn", 0)),
166
+ as_label=str(data.get("as_label", "")),
167
+ org=data.get("org"),
168
+ org_type=data.get("org_type"),
169
+ country=data.get("country"),
170
+ rdap=rdap if isinstance(rdap, dict) else None,
171
+ raw=dict(data),
172
+ )
173
+
174
+
175
+ @dataclass(frozen=True)
176
+ class DnsLookupResponse:
177
+ query: str
178
+ mode: str
179
+ ptr_name: Optional[str] = None
180
+ ptr_records: list[str] = field(default_factory=list)
181
+ ip_intel: Optional[IpLookupResponse] = None
182
+ a_records: list[str] = field(default_factory=list)
183
+ aaaa_records: list[str] = field(default_factory=list)
184
+ resolved_ips: list[IpLookupResponse] = field(default_factory=list)
185
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
186
+
187
+ @classmethod
188
+ def from_dict(cls, data: dict[str, Any]) -> DnsLookupResponse:
189
+ intel = data.get("ip_intel")
190
+ resolved = [
191
+ IpLookupResponse.from_dict(item)
192
+ for item in (data.get("resolved_ips") or [])
193
+ if isinstance(item, dict)
194
+ ]
195
+ return cls(
196
+ query=str(data.get("query", "")),
197
+ mode=str(data.get("mode", "")),
198
+ ptr_name=data.get("ptr_name"),
199
+ ptr_records=list(data.get("ptr_records") or []),
200
+ ip_intel=IpLookupResponse.from_dict(intel) if isinstance(intel, dict) else None,
201
+ a_records=list(data.get("a_records") or []),
202
+ aaaa_records=list(data.get("aaaa_records") or []),
203
+ resolved_ips=resolved,
204
+ raw=dict(data),
205
+ )
206
+
207
+
208
+ @dataclass(frozen=True)
209
+ class WhoisLookupResponse:
210
+ query: str
211
+ query_type: str
212
+ rdap: Optional[dict[str, Any]] = None
213
+ ip_intel: Optional[IpLookupResponse] = None
214
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
215
+
216
+ @classmethod
217
+ def from_dict(cls, data: dict[str, Any]) -> WhoisLookupResponse:
218
+ rdap = data.get("rdap")
219
+ intel = data.get("ip_intel")
220
+ return cls(
221
+ query=str(data.get("query", "")),
222
+ query_type=str(data.get("query_type", "")),
223
+ rdap=rdap if isinstance(rdap, dict) else None,
224
+ ip_intel=IpLookupResponse.from_dict(intel) if isinstance(intel, dict) else None,
225
+ raw=dict(data),
226
+ )
227
+
228
+
229
+ @dataclass(frozen=True)
230
+ class HealthResponse:
231
+ status: str
232
+ service: str
233
+ db_version: str
234
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
235
+
236
+ @classmethod
237
+ def from_dict(cls, data: dict[str, Any]) -> HealthResponse:
238
+ return cls(
239
+ status=str(data.get("status", "")),
240
+ service=str(data.get("service", "")),
241
+ db_version=str(data.get("db_version", "")),
242
+ raw=dict(data),
243
+ )
244
+
245
+
246
+ @dataclass(frozen=True)
247
+ class RateLimitInfo:
248
+ limit: Optional[int] = None
249
+ remaining: Optional[int] = None
250
+ lookup_ms: Optional[int] = None
251
+ retry_after: Optional[int] = None
File without changes
@@ -0,0 +1,133 @@
1
+ from __future__ import annotations
2
+
3
+ import http.server
4
+ import json
5
+ import pathlib
6
+ import threading
7
+ import unittest
8
+
9
+ from ipdatum import BatchErrorItem, IPDatumClient, IPDatumError
10
+
11
+ FIXTURES = pathlib.Path(__file__).resolve().parent / "fixtures"
12
+
13
+
14
+ def load_fixture(name: str) -> dict:
15
+ return json.loads((FIXTURES / name).read_text(encoding="utf-8"))
16
+
17
+
18
+ class _Handler(http.server.BaseHTTPRequestHandler):
19
+ def log_message(self, format: str, *args) -> None: # noqa: A002
20
+ return
21
+
22
+ def _send(self, status: int, body: bytes, headers: dict[str, str] | None = None) -> None:
23
+ self.send_response(status)
24
+ self.send_header("Content-Type", "application/json")
25
+ self.send_header("X-RateLimit-Limit", "1000")
26
+ self.send_header("X-RateLimit-Remaining", "997")
27
+ self.send_header("X-Lookup-Ms", "1")
28
+ for k, v in (headers or {}).items():
29
+ self.send_header(k, v)
30
+ self.end_headers()
31
+ self.wfile.write(body)
32
+
33
+ def do_GET(self) -> None: # noqa: N802
34
+ if self.path in ("/v1/ip", "/v1/ip/88.198.47.21"):
35
+ doc = load_fixture("ip_city.json")
36
+ doc["future_extra_field"] = {"ok": True}
37
+ self._send(200, json.dumps(doc).encode())
38
+ elif self.path == "/v1/ip/192.168.1.1":
39
+ self._send(200, (FIXTURES / "ip_bogon.json").read_bytes())
40
+ elif self.path == "/v1/ip/2606%3A4700%3A4700%3A%3A1111":
41
+ self._send(200, (FIXTURES / "ip_v6.json").read_bytes())
42
+ elif self.path == "/v1/asn/AS15169":
43
+ self._send(200, (FIXTURES / "asn_15169.json").read_bytes())
44
+ elif self.path == "/v1/dns?q=8.8.8.8":
45
+ self._send(200, (FIXTURES / "dns_reverse.json").read_bytes())
46
+ elif self.path == "/v1/dns?q=ipdatum.com":
47
+ self._send(200, (FIXTURES / "dns_forward.json").read_bytes())
48
+ elif self.path == "/v1/whois/8.8.8.8":
49
+ self._send(200, (FIXTURES / "whois_ip.json").read_bytes())
50
+ elif self.path == "/v1/health":
51
+ self._send(200, (FIXTURES / "health.json").read_bytes())
52
+ elif self.path == "/v1/ip/4.2.9.0":
53
+ self._send(429, json.dumps({"error": "rate_limited", "message": "Slow down"}).encode(), {"Retry-After": "30"})
54
+ elif self.path == "/v1/ip/5.0.2.0":
55
+ self.send_response(502)
56
+ self.send_header("Content-Type", "text/html")
57
+ self.end_headers()
58
+ self.wfile.write(b"<html>502 Bad Gateway</html>")
59
+ else:
60
+ self._send(404, b'{"error":"not_found"}')
61
+
62
+ def do_POST(self) -> None: # noqa: N802
63
+ length = int(self.headers.get("Content-Length", "0"))
64
+ _ = self.rfile.read(length)
65
+ if self.path == "/v1/ip/batch":
66
+ self._send(200, (FIXTURES / "batch_mixed.json").read_bytes())
67
+ else:
68
+ self._send(404, b'{"error":"not_found"}')
69
+
70
+
71
+ class IPDatumPythonSDKTests(unittest.TestCase):
72
+ @classmethod
73
+ def setUpClass(cls) -> None:
74
+ cls.srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
75
+ cls.thread = threading.Thread(target=cls.srv.serve_forever, daemon=True)
76
+ cls.thread.start()
77
+ cls.base_url = f"http://127.0.0.1:{cls.srv.server_address[1]}"
78
+
79
+ @classmethod
80
+ def tearDownClass(cls) -> None:
81
+ cls.srv.shutdown()
82
+ cls.srv.server_close()
83
+
84
+ def test_all_endpoints_and_guards(self) -> None:
85
+ with IPDatumClient("ipd_py_key", base_url=self.base_url) as client:
86
+ city = client.lookup("")
87
+ self.assertEqual(city.location.city, "Falkenstein")
88
+ self.assertEqual(city.raw["future_extra_field"], {"ok": True})
89
+ self.assertIsNotNone(client.last_rate_limit)
90
+ self.assertEqual(client.last_rate_limit.remaining, 997)
91
+
92
+ bogon = client.lookup("192.168.1.1")
93
+ self.assertTrue(bogon.bogon)
94
+ self.assertIsNone(bogon.location.city)
95
+ self.assertIsNone(bogon.network.asn)
96
+
97
+ v6 = client.lookup("2606:4700:4700::1111")
98
+ self.assertEqual(v6.ip_version, 6)
99
+ self.assertTrue(v6.security.is_anycast)
100
+
101
+ batch_res = client.batch(["8.8.8.8", "1.1.1.0/24"])
102
+ self.assertEqual(batch_res.count, 2)
103
+ self.assertFalse(isinstance(batch_res.results[0], BatchErrorItem))
104
+ self.assertTrue(isinstance(batch_res.results[1], BatchErrorItem))
105
+
106
+ self.assertEqual(client.asn("AS15169").asn, 15169)
107
+ self.assertEqual(client.dns("8.8.8.8").mode, "reverse_ptr")
108
+ self.assertEqual(client.dns("ipdatum.com").mode, "forward_host")
109
+ self.assertEqual(client.whois("8.8.8.8").query_type, "ip")
110
+ self.assertEqual(client.health().status, "ok")
111
+
112
+ with self.assertRaises(IPDatumError):
113
+ client.lookup("../health")
114
+ with self.assertRaises(IPDatumError):
115
+ client.whois("8.8.8.0/24")
116
+ with self.assertRaises(IPDatumError):
117
+ client.batch([])
118
+ with self.assertRaises(IPDatumError):
119
+ client.batch(["8.8.8.8"] * 101)
120
+
121
+ with self.assertRaises(IPDatumError) as ctx_rl:
122
+ client.lookup("4.2.9.0")
123
+ self.assertTrue(ctx_rl.exception.is_rate_limited)
124
+ self.assertEqual(ctx_rl.exception.retry_after, 30)
125
+
126
+ with self.assertRaises(IPDatumError) as ctx_html:
127
+ client.lookup("5.0.2.0")
128
+ self.assertEqual(ctx_html.exception.status_code, 502)
129
+ self.assertIn("Bad Gateway", ctx_html.exception.body)
130
+
131
+
132
+ if __name__ == "__main__":
133
+ unittest.main()