subpermits 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.
- subpermits/__init__.py +15 -0
- subpermits/client.py +118 -0
- subpermits/errors.py +49 -0
- subpermits/py.typed +0 -0
- subpermits/types.py +113 -0
- subpermits/webhooks.py +27 -0
- subpermits-1.0.0.dist-info/METADATA +131 -0
- subpermits-1.0.0.dist-info/RECORD +11 -0
- subpermits-1.0.0.dist-info/WHEEL +5 -0
- subpermits-1.0.0.dist-info/licenses/LICENSE +21 -0
- subpermits-1.0.0.dist-info/top_level.txt +1 -0
subpermits/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Official Python client for the SubPermits API: commercial building permits matched to specialty trades.
|
|
2
|
+
|
|
3
|
+
Docs: https://subpermits.com/docs/api/
|
|
4
|
+
"""
|
|
5
|
+
__version__ = "1.0.0"
|
|
6
|
+
|
|
7
|
+
from .client import Client # noqa: E402
|
|
8
|
+
from .errors import (APIError, AuthenticationError, BadRequestError, NotFoundError, # noqa: E402
|
|
9
|
+
PermissionDeniedError, RateLimitError, SubPermitsError)
|
|
10
|
+
from .types import City, Match, Project, ProjectPage, RateLimit, ServiceLine # noqa: E402
|
|
11
|
+
from .webhooks import verify_webhook # noqa: E402
|
|
12
|
+
|
|
13
|
+
__all__ = ["Client", "verify_webhook", "City", "ServiceLine", "Project", "ProjectPage", "Match", "RateLimit",
|
|
14
|
+
"SubPermitsError", "BadRequestError", "AuthenticationError", "PermissionDeniedError", "NotFoundError",
|
|
15
|
+
"RateLimitError", "APIError", "__version__"]
|
subpermits/client.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""HTTP client for the SubPermits API (https://subpermits.com/docs/api/). Standard library only."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import urllib.error
|
|
5
|
+
import urllib.parse
|
|
6
|
+
import urllib.request
|
|
7
|
+
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
from . import __version__
|
|
10
|
+
from .errors import (APIError, AuthenticationError, BadRequestError, NotFoundError, PermissionDeniedError,
|
|
11
|
+
RateLimitError, SubPermitsError)
|
|
12
|
+
from .types import City, Project, ProjectPage, RateLimit, ServiceLine
|
|
13
|
+
|
|
14
|
+
DEFAULT_BASE_URL = "https://subpermits.com/api/v1"
|
|
15
|
+
|
|
16
|
+
# transport(method, url, headers, timeout) -> (status, headers, body bytes); replaceable in tests
|
|
17
|
+
Transport = Callable[[str, str, Dict[str, str], float], Tuple[int, Dict[str, str], bytes]]
|
|
18
|
+
|
|
19
|
+
_ERRORS = {400: BadRequestError, 401: AuthenticationError, 403: PermissionDeniedError, 404: NotFoundError,
|
|
20
|
+
429: RateLimitError}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _urllib_transport(method: str, url: str, headers: Dict[str, str], timeout: float):
|
|
24
|
+
req = urllib.request.Request(url, method=method, headers=headers)
|
|
25
|
+
try:
|
|
26
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
27
|
+
return resp.status, dict(resp.headers.items()), resp.read()
|
|
28
|
+
except urllib.error.HTTPError as e:
|
|
29
|
+
return e.code, dict(e.headers.items()) if e.headers else {}, e.read() or b""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Client:
|
|
33
|
+
"""SubPermits API client.
|
|
34
|
+
|
|
35
|
+
>>> from subpermits import Client
|
|
36
|
+
>>> sp = Client() # reads SUBPERMITS_API_KEY
|
|
37
|
+
>>> for p in sp.iter_projects(city="austin", max_pages=2):
|
|
38
|
+
... print(p.issue_date, p.project_category, p.valuation_range_usd)
|
|
39
|
+
|
|
40
|
+
Create a key in your account at https://subpermits.com/account/#api. Sandbox keys (free) return
|
|
41
|
+
records older than 14 days with exact fields removed; live keys (paid plans) return every field for
|
|
42
|
+
the cities and service lines of the plan.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(self, api_key: Optional[str] = None, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0,
|
|
46
|
+
transport: Optional[Transport] = None):
|
|
47
|
+
self.api_key = api_key or os.environ.get("SUBPERMITS_API_KEY", "")
|
|
48
|
+
if not self.api_key:
|
|
49
|
+
raise AuthenticationError("No API key. Pass api_key=... or set SUBPERMITS_API_KEY. "
|
|
50
|
+
"Get a free sandbox key at https://subpermits.com/account/#api")
|
|
51
|
+
self.base_url = base_url.rstrip("/")
|
|
52
|
+
self.timeout = timeout
|
|
53
|
+
self._transport = transport or _urllib_transport
|
|
54
|
+
self.last_rate_limit = RateLimit()
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def is_sandbox(self) -> bool:
|
|
58
|
+
return self.api_key.startswith("sp_test_")
|
|
59
|
+
|
|
60
|
+
# ------------------------------------------------------------------ low level
|
|
61
|
+
def request(self, path: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
62
|
+
"""GET ``path`` with query ``params`` (None values dropped) and return the decoded JSON body."""
|
|
63
|
+
query = {k: v for k, v in (params or {}).items() if v is not None}
|
|
64
|
+
url = f"{self.base_url}/{path.lstrip('/')}"
|
|
65
|
+
if query:
|
|
66
|
+
url += "?" + urllib.parse.urlencode(query)
|
|
67
|
+
headers = {"Authorization": f"Bearer {self.api_key}", "Accept": "application/json",
|
|
68
|
+
"User-Agent": f"subpermits-python/{__version__}"}
|
|
69
|
+
try:
|
|
70
|
+
status, resp_headers, body = self._transport("GET", url, headers, self.timeout)
|
|
71
|
+
except SubPermitsError:
|
|
72
|
+
raise
|
|
73
|
+
except Exception as e: # network errors, timeouts
|
|
74
|
+
raise APIError(f"Request failed: {e}") from e
|
|
75
|
+
self.last_rate_limit = RateLimit.from_headers(resp_headers)
|
|
76
|
+
try:
|
|
77
|
+
payload = json.loads(body.decode() or "{}")
|
|
78
|
+
except ValueError:
|
|
79
|
+
payload = {}
|
|
80
|
+
if 200 <= status < 300:
|
|
81
|
+
return payload
|
|
82
|
+
err = payload.get("error") or {}
|
|
83
|
+
cls = _ERRORS.get(status, APIError)
|
|
84
|
+
raise cls(err.get("message") or f"HTTP {status}", status=status, code=err.get("code", ""),
|
|
85
|
+
payload=payload, rate_limit=self.last_rate_limit)
|
|
86
|
+
|
|
87
|
+
# ------------------------------------------------------------------ endpoints
|
|
88
|
+
def cities(self) -> List[City]:
|
|
89
|
+
return [City.from_dict(d) for d in self.request("cities").get("data", [])]
|
|
90
|
+
|
|
91
|
+
def service_lines(self) -> List[ServiceLine]:
|
|
92
|
+
return [ServiceLine.from_dict(d) for d in self.request("service-lines").get("data", [])]
|
|
93
|
+
|
|
94
|
+
def projects(self, city: Optional[str] = None, service_line: Optional[str] = None,
|
|
95
|
+
since: Optional[str] = None, min_valuation: Optional[int] = None, page: int = 1,
|
|
96
|
+
page_size: Optional[int] = None) -> ProjectPage:
|
|
97
|
+
"""One page of projects, newest first. ``since`` is an issue date, YYYY-MM-DD."""
|
|
98
|
+
p = self.request("projects", {"city": city, "service_line": service_line, "since": since,
|
|
99
|
+
"min_valuation": min_valuation, "page": page, "page_size": page_size})
|
|
100
|
+
return ProjectPage(
|
|
101
|
+
data=[Project.from_dict(d) for d in p.get("data", [])], page=int(p.get("page", page)),
|
|
102
|
+
page_size=int(p.get("page_size", page_size or 0)), has_more=bool(p.get("has_more")),
|
|
103
|
+
next_page=p.get("next_page"), sandbox=bool(p.get("sandbox")), upgrade_url=p.get("upgrade_url"),
|
|
104
|
+
rate_limit=self.last_rate_limit, raw=p)
|
|
105
|
+
|
|
106
|
+
def iter_projects(self, max_pages: Optional[int] = None, **filters: Any) -> Iterator[Project]:
|
|
107
|
+
"""Iterate over every matching project, following ``next_page``. Each page costs one request."""
|
|
108
|
+
page, seen = filters.pop("page", 1), 0
|
|
109
|
+
while True:
|
|
110
|
+
result = self.projects(page=page, **filters)
|
|
111
|
+
yield from result.data
|
|
112
|
+
seen += 1
|
|
113
|
+
if not result.has_more or not result.next_page or (max_pages and seen >= max_pages):
|
|
114
|
+
return
|
|
115
|
+
page = result.next_page
|
|
116
|
+
|
|
117
|
+
def project(self, project_id: int) -> Project:
|
|
118
|
+
return Project.from_dict(self.request(f"projects/{int(project_id)}").get("data") or {})
|
subpermits/errors.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Exceptions raised by the SubPermits client."""
|
|
2
|
+
from typing import Any, Dict, Optional
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class SubPermitsError(Exception):
|
|
6
|
+
"""Base error. ``status`` is the HTTP status (0 for network errors), ``code`` the API error code."""
|
|
7
|
+
|
|
8
|
+
def __init__(self, message: str, status: int = 0, code: str = "", payload: Optional[Dict[str, Any]] = None,
|
|
9
|
+
rate_limit: Optional["RateLimit"] = None):
|
|
10
|
+
super().__init__(message)
|
|
11
|
+
self.message = message
|
|
12
|
+
self.status = status
|
|
13
|
+
self.code = code
|
|
14
|
+
self.payload = payload or {}
|
|
15
|
+
self.rate_limit = rate_limit
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class BadRequestError(SubPermitsError):
|
|
19
|
+
"""400: an invalid parameter, for example an unknown city slug or a bad date."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AuthenticationError(SubPermitsError):
|
|
23
|
+
"""401: the key is missing, invalid or revoked."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PermissionDeniedError(SubPermitsError):
|
|
27
|
+
"""403: city or service line outside the plan of a live key, or no active plan.
|
|
28
|
+
|
|
29
|
+
``upgrade_url`` points to the pricing page when the API provides it.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def upgrade_url(self) -> Optional[str]:
|
|
34
|
+
return (self.payload.get("error") or {}).get("upgrade_url")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class NotFoundError(SubPermitsError):
|
|
38
|
+
"""404: the project does not exist or is outside your access scope."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class RateLimitError(SubPermitsError):
|
|
42
|
+
"""429: daily or hourly limit reached. See ``rate_limit.reset`` for the next reset time."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class APIError(SubPermitsError):
|
|
46
|
+
"""Any other non 2xx response or a network failure."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
from .types import RateLimit # noqa: E402 (imported late to keep the module dependency light)
|
subpermits/py.typed
ADDED
|
File without changes
|
subpermits/types.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Lightweight typed views of API responses. Raw dicts are always available as ``.raw``."""
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from typing import Any, Dict, List, Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class RateLimit:
|
|
8
|
+
limit: Optional[int] = None
|
|
9
|
+
remaining: Optional[int] = None
|
|
10
|
+
reset: Optional[int] = None # unix time of the next reset (00:00 UTC)
|
|
11
|
+
|
|
12
|
+
@classmethod
|
|
13
|
+
def from_headers(cls, headers: Dict[str, str]) -> "RateLimit":
|
|
14
|
+
h = {k.lower(): v for k, v in (headers or {}).items()}
|
|
15
|
+
|
|
16
|
+
def num(name: str) -> Optional[int]:
|
|
17
|
+
try:
|
|
18
|
+
return int(h[name])
|
|
19
|
+
except (KeyError, TypeError, ValueError):
|
|
20
|
+
return None
|
|
21
|
+
|
|
22
|
+
return cls(num("x-ratelimit-limit"), num("x-ratelimit-remaining"), num("x-ratelimit-reset"))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class City:
|
|
27
|
+
slug: str
|
|
28
|
+
name: str
|
|
29
|
+
state: str
|
|
30
|
+
in_plan: Optional[bool] = None
|
|
31
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def from_dict(cls, d: Dict[str, Any]) -> "City":
|
|
35
|
+
return cls(d.get("slug", ""), d.get("name", ""), d.get("state", ""), d.get("in_plan"), d)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class ServiceLine:
|
|
40
|
+
slug: str
|
|
41
|
+
name: str
|
|
42
|
+
short_name: str = ""
|
|
43
|
+
in_plan: Optional[bool] = None
|
|
44
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def from_dict(cls, d: Dict[str, Any]) -> "ServiceLine":
|
|
48
|
+
return cls(d.get("slug", ""), d.get("name", ""), d.get("short_name", ""), d.get("in_plan"), d)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Match:
|
|
53
|
+
service_line: str
|
|
54
|
+
relevance_score: Optional[int] = None
|
|
55
|
+
est_contract_min_usd: Optional[int] = None
|
|
56
|
+
est_contract_max_usd: Optional[int] = None
|
|
57
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def from_dict(cls, d: Dict[str, Any]) -> "Match":
|
|
61
|
+
return cls(d.get("service_line", ""), d.get("relevance_score"), d.get("est_contract_min_usd"),
|
|
62
|
+
d.get("est_contract_max_usd"), d)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class Project:
|
|
67
|
+
"""One commercial permit project.
|
|
68
|
+
|
|
69
|
+
With a sandbox key the exact fields (address, permit number, value, contacts) are ``None`` or masked and
|
|
70
|
+
``contacts`` is a summary dict such as ``{"available": True, "count": 2}``. With a live key ``contacts`` is
|
|
71
|
+
a list of contact dicts.
|
|
72
|
+
"""
|
|
73
|
+
id: int
|
|
74
|
+
city: str
|
|
75
|
+
issue_date: Optional[str]
|
|
76
|
+
project_category: Optional[str]
|
|
77
|
+
summary: Optional[str]
|
|
78
|
+
address: Optional[str]
|
|
79
|
+
valuation_usd: Optional[int]
|
|
80
|
+
valuation_range_usd: Optional[str]
|
|
81
|
+
permit_number: Optional[str]
|
|
82
|
+
service_lines: List[Match]
|
|
83
|
+
contacts: Any
|
|
84
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def is_masked(self) -> bool:
|
|
88
|
+
"""True when the record came through a sandbox key (contacts reduced to a summary)."""
|
|
89
|
+
return isinstance(self.contacts, dict)
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def from_dict(cls, d: Dict[str, Any]) -> "Project":
|
|
93
|
+
city = d.get("city") or {}
|
|
94
|
+
return cls(
|
|
95
|
+
id=int(d.get("id", 0)), city=city.get("slug", "") if isinstance(city, dict) else str(city),
|
|
96
|
+
issue_date=d.get("issue_date"), project_category=d.get("project_category"), summary=d.get("summary"),
|
|
97
|
+
address=d.get("address"), valuation_usd=d.get("valuation_usd"),
|
|
98
|
+
valuation_range_usd=d.get("valuation_range_usd"), permit_number=d.get("permit_number"),
|
|
99
|
+
service_lines=[Match.from_dict(m) for m in d.get("service_lines") or []],
|
|
100
|
+
contacts=d.get("contacts"), raw=d)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True)
|
|
104
|
+
class ProjectPage:
|
|
105
|
+
data: List[Project]
|
|
106
|
+
page: int
|
|
107
|
+
page_size: int
|
|
108
|
+
has_more: bool
|
|
109
|
+
next_page: Optional[int]
|
|
110
|
+
sandbox: bool
|
|
111
|
+
upgrade_url: Optional[str]
|
|
112
|
+
rate_limit: RateLimit
|
|
113
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
subpermits/webhooks.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Webhook signature check for ``projects.new`` events."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
import time
|
|
5
|
+
from typing import Optional, Union
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def verify_webhook(secret: str, header: str, body: Union[bytes, str], tolerance: int = 300,
|
|
9
|
+
now: Optional[float] = None) -> bool:
|
|
10
|
+
"""Return True if ``header`` (the X-SubPermits-Signature value) matches ``body``.
|
|
11
|
+
|
|
12
|
+
The header has the form ``t=<unix time>,v1=<hex>``, where v1 is HMAC SHA-256 of ``"<t>." + raw body``
|
|
13
|
+
with your webhook secret. Pass the raw request body, not re-serialized JSON. Signatures older than
|
|
14
|
+
``tolerance`` seconds are rejected.
|
|
15
|
+
"""
|
|
16
|
+
if isinstance(body, str):
|
|
17
|
+
body = body.encode()
|
|
18
|
+
try:
|
|
19
|
+
parts = dict(p.split("=", 1) for p in (header or "").split(","))
|
|
20
|
+
ts = int(parts["t"])
|
|
21
|
+
sig = parts["v1"]
|
|
22
|
+
except (KeyError, ValueError):
|
|
23
|
+
return False
|
|
24
|
+
if abs((time.time() if now is None else now) - ts) > tolerance:
|
|
25
|
+
return False
|
|
26
|
+
expected = hmac.new(secret.encode(), f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
|
|
27
|
+
return hmac.compare_digest(expected, sig)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: subpermits
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Official Python client for the SubPermits API: commercial building permits matched to specialty trades
|
|
5
|
+
Author-email: BUILDTM LLC <support@subpermits.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://subpermits.com/?utm_source=pypi&utm_campaign=subpermits-sdk
|
|
8
|
+
Project-URL: Documentation, https://subpermits.com/docs/api/?utm_source=pypi&utm_campaign=subpermits-sdk
|
|
9
|
+
Project-URL: Source, https://github.com/blureshot/subpermits-python
|
|
10
|
+
Keywords: building permits,construction leads,commercial construction,subcontractor,api client
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# SubPermits Python SDK
|
|
23
|
+
|
|
24
|
+
Official Python client for the [SubPermits API](https://subpermits.com/docs/api/?utm_source=pypi&utm_campaign=subpermits-sdk): commercial building permits over $150,000 from official city open data in 10 US cities, classified into 12 specialty trades with estimated contract ranges.
|
|
25
|
+
|
|
26
|
+
Standard library only, Python 3.9+, typed.
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install subpermits
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Get a key
|
|
33
|
+
|
|
34
|
+
Create a free sandbox key in your account: <https://subpermits.com/account/?utm_source=pypi&utm_campaign=subpermits-sdk#api>. Keep keys on your server.
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
export SUBPERMITS_API_KEY=sp_test_...
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Quick start
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from subpermits import Client
|
|
44
|
+
|
|
45
|
+
sp = Client() # reads SUBPERMITS_API_KEY
|
|
46
|
+
|
|
47
|
+
for city in sp.cities():
|
|
48
|
+
print(city.slug, city.name, city.state)
|
|
49
|
+
|
|
50
|
+
page = sp.projects(city="austin", service_line="commercial-signage-leads", page_size=10)
|
|
51
|
+
for p in page.data:
|
|
52
|
+
print(p.issue_date, p.project_category, p.valuation_range_usd)
|
|
53
|
+
for m in p.service_lines:
|
|
54
|
+
print(" ", m.service_line, m.relevance_score, m.est_contract_min_usd, m.est_contract_max_usd)
|
|
55
|
+
|
|
56
|
+
print(page.rate_limit.remaining, "requests left today")
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Iterate over every page (each page is one request):
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
for p in sp.iter_projects(city="chicago", since="2026-11-01", min_valuation=500000, max_pages=5):
|
|
63
|
+
print(p.id, p.summary)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
One project:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
p = sp.project(48211)
|
|
70
|
+
print(p.raw) # the full JSON record
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Sandbox and live keys
|
|
74
|
+
|
|
75
|
+
| | Sandbox key (free) | Live key (paid plans) |
|
|
76
|
+
|---|---|---|
|
|
77
|
+
| Who gets it | Any account | City Pass, Multi-City, Exclusive Territory |
|
|
78
|
+
| Freshness | Permits older than 14 days | Same day |
|
|
79
|
+
| Fields | City, ZIP, area, project type, status, short description, value and size ranges, trade matches | Everything, including full address, permit number, exact value and size, contacts |
|
|
80
|
+
| Contacts | Only whether contacts exist and how many | General contractor, owner and applicant contacts |
|
|
81
|
+
| Requests | 100 a day, 25 records per page | 5000 a day, 100 records per page |
|
|
82
|
+
|
|
83
|
+
Sandbox records have `p.is_masked == True` and `p.contacts == {"available": True, "count": 2}`. Every sandbox response also carries `upgrade_url`. Plans and prices: <https://subpermits.com/pricing/?utm_source=pypi&utm_campaign=subpermits-sdk>.
|
|
84
|
+
|
|
85
|
+
## Errors
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from subpermits import PermissionDeniedError, RateLimitError
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
sp.projects(city="seattle")
|
|
92
|
+
except PermissionDeniedError as e: # 403: city or trade outside your plan
|
|
93
|
+
print(e.code, e.upgrade_url)
|
|
94
|
+
except RateLimitError as e: # 429: limit reached
|
|
95
|
+
print("resets at", e.rate_limit.reset)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
| Exception | Status |
|
|
99
|
+
|---|---|
|
|
100
|
+
| `BadRequestError` | 400, invalid parameter |
|
|
101
|
+
| `AuthenticationError` | 401, missing, invalid or revoked key |
|
|
102
|
+
| `PermissionDeniedError` | 403, outside your plan or no active plan |
|
|
103
|
+
| `NotFoundError` | 404 |
|
|
104
|
+
| `RateLimitError` | 429 |
|
|
105
|
+
| `APIError` | anything else, including network errors |
|
|
106
|
+
|
|
107
|
+
## Webhooks (paid plans)
|
|
108
|
+
|
|
109
|
+
After each daily refresh SubPermits can POST new projects in your plan to your https URL. Verify the `X-SubPermits-Signature` header with the raw body:
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from subpermits import verify_webhook
|
|
113
|
+
|
|
114
|
+
ok = verify_webhook(secret=WEBHOOK_SECRET, header=request.headers["X-SubPermits-Signature"], body=request.body)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Postman
|
|
118
|
+
|
|
119
|
+
A Postman collection and environment generated from the OpenAPI spec are in [`postman/`](https://github.com/blureshot/subpermits-python/tree/main/postman). Set `api_key` in the environment.
|
|
120
|
+
|
|
121
|
+
## Links
|
|
122
|
+
|
|
123
|
+
- API guide: <https://subpermits.com/docs/api/?utm_source=pypi&utm_campaign=subpermits-sdk>
|
|
124
|
+
- OpenAPI 3.1 spec: <https://subpermits.com/api/v1/openapi.yaml>
|
|
125
|
+
- Terms and acceptable use: <https://subpermits.com/acceptable-use/>
|
|
126
|
+
|
|
127
|
+
Use of the API follows the SubPermits Terms of Service. Outreach must follow CAN-SPAM, the TCPA and Do Not Call rules.
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
subpermits/__init__.py,sha256=9e99oOKmwis18w4iLmpIOmCXf6z4eGfu49WnxTLedy4,813
|
|
2
|
+
subpermits/client.py,sha256=fqLi3js7OpFCUpeJV8svP5Y_c-wHjwiz9FAK5VDsZRU,5998
|
|
3
|
+
subpermits/errors.py,sha256=XKeHCkWOQqGzBryLTTI4Kvi6JYkZDOmYC7ezn3zHbFI,1609
|
|
4
|
+
subpermits/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
subpermits/types.py,sha256=sldTkLiIoXiljDQNAewRz5ix2XPdNLIhcXbyH9Kit0Y,3933
|
|
6
|
+
subpermits/webhooks.py,sha256=J0XBYFnwGMYkh-Ckp5359kV9eTwRyd2ESxyr97nrTu4,1110
|
|
7
|
+
subpermits-1.0.0.dist-info/licenses/LICENSE,sha256=GKNEkkhoa4t2CETs4V52V3yMR8TqviL1Vopt-CGdZR4,1068
|
|
8
|
+
subpermits-1.0.0.dist-info/METADATA,sha256=Pge92gRIX_rgMIDgrJrdw-nZZI9HkWSjMzp_9W3JZa0,4826
|
|
9
|
+
subpermits-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
subpermits-1.0.0.dist-info/top_level.txt,sha256=_KRzU7SAifThpjExI2JpWHK7MgXlutVMiyyGF9831jk,11
|
|
11
|
+
subpermits-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BUILDTM LLC
|
|
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
|
+
subpermits
|