subpermits 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,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,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,110 @@
1
+ # SubPermits Python SDK
2
+
3
+ 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.
4
+
5
+ Standard library only, Python 3.9+, typed.
6
+
7
+ ```bash
8
+ pip install subpermits
9
+ ```
10
+
11
+ ## Get a key
12
+
13
+ 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.
14
+
15
+ ```bash
16
+ export SUBPERMITS_API_KEY=sp_test_...
17
+ ```
18
+
19
+ ## Quick start
20
+
21
+ ```python
22
+ from subpermits import Client
23
+
24
+ sp = Client() # reads SUBPERMITS_API_KEY
25
+
26
+ for city in sp.cities():
27
+ print(city.slug, city.name, city.state)
28
+
29
+ page = sp.projects(city="austin", service_line="commercial-signage-leads", page_size=10)
30
+ for p in page.data:
31
+ print(p.issue_date, p.project_category, p.valuation_range_usd)
32
+ for m in p.service_lines:
33
+ print(" ", m.service_line, m.relevance_score, m.est_contract_min_usd, m.est_contract_max_usd)
34
+
35
+ print(page.rate_limit.remaining, "requests left today")
36
+ ```
37
+
38
+ Iterate over every page (each page is one request):
39
+
40
+ ```python
41
+ for p in sp.iter_projects(city="chicago", since="2026-11-01", min_valuation=500000, max_pages=5):
42
+ print(p.id, p.summary)
43
+ ```
44
+
45
+ One project:
46
+
47
+ ```python
48
+ p = sp.project(48211)
49
+ print(p.raw) # the full JSON record
50
+ ```
51
+
52
+ ## Sandbox and live keys
53
+
54
+ | | Sandbox key (free) | Live key (paid plans) |
55
+ |---|---|---|
56
+ | Who gets it | Any account | City Pass, Multi-City, Exclusive Territory |
57
+ | Freshness | Permits older than 14 days | Same day |
58
+ | 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 |
59
+ | Contacts | Only whether contacts exist and how many | General contractor, owner and applicant contacts |
60
+ | Requests | 100 a day, 25 records per page | 5000 a day, 100 records per page |
61
+
62
+ 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>.
63
+
64
+ ## Errors
65
+
66
+ ```python
67
+ from subpermits import PermissionDeniedError, RateLimitError
68
+
69
+ try:
70
+ sp.projects(city="seattle")
71
+ except PermissionDeniedError as e: # 403: city or trade outside your plan
72
+ print(e.code, e.upgrade_url)
73
+ except RateLimitError as e: # 429: limit reached
74
+ print("resets at", e.rate_limit.reset)
75
+ ```
76
+
77
+ | Exception | Status |
78
+ |---|---|
79
+ | `BadRequestError` | 400, invalid parameter |
80
+ | `AuthenticationError` | 401, missing, invalid or revoked key |
81
+ | `PermissionDeniedError` | 403, outside your plan or no active plan |
82
+ | `NotFoundError` | 404 |
83
+ | `RateLimitError` | 429 |
84
+ | `APIError` | anything else, including network errors |
85
+
86
+ ## Webhooks (paid plans)
87
+
88
+ 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:
89
+
90
+ ```python
91
+ from subpermits import verify_webhook
92
+
93
+ ok = verify_webhook(secret=WEBHOOK_SECRET, header=request.headers["X-SubPermits-Signature"], body=request.body)
94
+ ```
95
+
96
+ ## Postman
97
+
98
+ 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.
99
+
100
+ ## Links
101
+
102
+ - API guide: <https://subpermits.com/docs/api/?utm_source=pypi&utm_campaign=subpermits-sdk>
103
+ - OpenAPI 3.1 spec: <https://subpermits.com/api/v1/openapi.yaml>
104
+ - Terms and acceptable use: <https://subpermits.com/acceptable-use/>
105
+
106
+ Use of the API follows the SubPermits Terms of Service. Outreach must follow CAN-SPAM, the TCPA and Do Not Call rules.
107
+
108
+ ## License
109
+
110
+ MIT
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "subpermits"
7
+ version = "1.0.0"
8
+ description = "Official Python client for the SubPermits API: commercial building permits matched to specialty trades"
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.9"
12
+ authors = [{name = "BUILDTM LLC", email = "support@subpermits.com"}]
13
+ keywords = ["building permits", "construction leads", "commercial construction", "subcontractor", "api client"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ "Intended Audience :: Developers",
19
+ "Topic :: Software Development :: Libraries",
20
+ "Typing :: Typed",
21
+ ]
22
+ dependencies = []
23
+
24
+ [project.urls]
25
+ Homepage = "https://subpermits.com/?utm_source=pypi&utm_campaign=subpermits-sdk"
26
+ Documentation = "https://subpermits.com/docs/api/?utm_source=pypi&utm_campaign=subpermits-sdk"
27
+ Source = "https://github.com/blureshot/subpermits-python"
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["src"]
31
+
32
+ [tool.setuptools.package-data]
33
+ subpermits = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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__"]
@@ -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 {})
@@ -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)
File without changes
@@ -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)
@@ -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,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/subpermits/__init__.py
5
+ src/subpermits/client.py
6
+ src/subpermits/errors.py
7
+ src/subpermits/py.typed
8
+ src/subpermits/types.py
9
+ src/subpermits/webhooks.py
10
+ src/subpermits.egg-info/PKG-INFO
11
+ src/subpermits.egg-info/SOURCES.txt
12
+ src/subpermits.egg-info/dependency_links.txt
13
+ src/subpermits.egg-info/top_level.txt
14
+ tests/test_client.py
@@ -0,0 +1 @@
1
+ subpermits
@@ -0,0 +1,149 @@
1
+ import hashlib
2
+ import hmac
3
+ import json
4
+ import time
5
+ import unittest
6
+ from urllib.parse import parse_qs, urlparse
7
+
8
+ import subpermits
9
+ from subpermits import (AuthenticationError, Client, NotFoundError, PermissionDeniedError, RateLimitError,
10
+ verify_webhook)
11
+
12
+ RL = {"X-RateLimit-Limit": "100", "X-RateLimit-Remaining": "97", "X-RateLimit-Reset": "1767225600"}
13
+
14
+
15
+ def project(i):
16
+ return {"id": i, "city": {"slug": "austin", "name": "Austin", "state": "TX"}, "issue_date": "2026-11-12",
17
+ "project_category": "Restaurant", "summary": "Interior finish out", "address": "#### S***** C*****",
18
+ "valuation_usd": None, "valuation_range_usd": "500k-1M", "permit_number": None,
19
+ "service_lines": [{"service_line": "commercial-signage-leads", "relevance_score": 85,
20
+ "est_contract_min_usd": 9000, "est_contract_max_usd": 18000}],
21
+ "contacts": {"available": True, "count": 2}}
22
+
23
+
24
+ class FakeTransport:
25
+ def __init__(self, responses):
26
+ self.responses = list(responses)
27
+ self.calls = []
28
+
29
+ def __call__(self, method, url, headers, timeout):
30
+ self.calls.append((method, url, headers))
31
+ status, body = self.responses.pop(0)
32
+ return status, dict(RL), json.dumps(body).encode()
33
+
34
+
35
+ class ClientTests(unittest.TestCase):
36
+ def client(self, *responses):
37
+ t = FakeTransport(responses)
38
+ return Client(api_key="sp_test_abc", transport=t), t
39
+
40
+ def test_requires_key(self):
41
+ import os
42
+ old = os.environ.pop("SUBPERMITS_API_KEY", None)
43
+ try:
44
+ with self.assertRaises(AuthenticationError):
45
+ Client()
46
+ finally:
47
+ if old is not None:
48
+ os.environ["SUBPERMITS_API_KEY"] = old
49
+
50
+ def test_env_key_and_auth_header(self):
51
+ import os
52
+ os.environ["SUBPERMITS_API_KEY"] = "sp_live_xyz"
53
+ try:
54
+ t = FakeTransport([(200, {"sandbox": False, "data": []})])
55
+ c = Client(transport=t)
56
+ c.cities()
57
+ self.assertEqual(t.calls[0][2]["Authorization"], "Bearer sp_live_xyz")
58
+ self.assertFalse(c.is_sandbox)
59
+ finally:
60
+ del os.environ["SUBPERMITS_API_KEY"]
61
+
62
+ def test_cities_and_service_lines(self):
63
+ c, t = self.client((200, {"sandbox": True, "data": [{"slug": "austin", "name": "Austin", "state": "TX"}]}),
64
+ (200, {"sandbox": True, "data": [{"slug": "commercial-roofing-leads", "name": "Roofing"}]}))
65
+ self.assertEqual(c.cities()[0].slug, "austin")
66
+ self.assertEqual(c.service_lines()[0].slug, "commercial-roofing-leads")
67
+ self.assertTrue(t.calls[0][1].endswith("/api/v1/cities"))
68
+ self.assertTrue(t.calls[1][1].endswith("/api/v1/service-lines"))
69
+ self.assertEqual(c.last_rate_limit.remaining, 97)
70
+
71
+ def test_projects_params_and_parsing(self):
72
+ c, t = self.client((200, {"sandbox": True, "upgrade_url": "https://subpermits.com/pricing/",
73
+ "data": [project(1)], "page": 1, "page_size": 25, "has_more": True,
74
+ "next_page": 2}))
75
+ page = c.projects(city="austin", since="2026-10-01", min_valuation=500000)
76
+ q = parse_qs(urlparse(t.calls[0][1]).query)
77
+ self.assertEqual(q["city"], ["austin"])
78
+ self.assertEqual(q["since"], ["2026-10-01"])
79
+ self.assertNotIn("service_line", q)
80
+ self.assertTrue(page.sandbox and page.has_more)
81
+ p = page.data[0]
82
+ self.assertTrue(p.is_masked)
83
+ self.assertIsNone(p.permit_number)
84
+ self.assertEqual(p.service_lines[0].relevance_score, 85)
85
+ self.assertEqual(page.rate_limit.limit, 100)
86
+
87
+ def test_iter_projects_follows_pages(self):
88
+ c, t = self.client((200, {"sandbox": True, "data": [project(1)], "has_more": True, "next_page": 2}),
89
+ (200, {"sandbox": True, "data": [project(2)], "has_more": True, "next_page": 3}),
90
+ (200, {"sandbox": True, "data": [project(3)], "has_more": False, "next_page": None}))
91
+ self.assertEqual([p.id for p in c.iter_projects(city="austin")], [1, 2, 3])
92
+ self.assertIn("page=3", t.calls[2][1])
93
+
94
+ def test_iter_projects_max_pages(self):
95
+ c, t = self.client((200, {"sandbox": True, "data": [project(1)], "has_more": True, "next_page": 2}),
96
+ (200, {"sandbox": True, "data": [project(2)], "has_more": True, "next_page": 3}))
97
+ self.assertEqual(len(list(c.iter_projects(max_pages=2))), 2)
98
+ self.assertEqual(len(t.calls), 2)
99
+
100
+ def test_project_detail(self):
101
+ c, _ = self.client((200, {"sandbox": True, "data": project(7)}))
102
+ self.assertEqual(c.project(7).id, 7)
103
+
104
+ def test_errors(self):
105
+ c, _ = self.client(
106
+ (401, {"error": {"code": "unauthorized", "message": "Missing or invalid API key."}}),
107
+ (403, {"error": {"code": "outside_plan", "message": "Not in plan",
108
+ "upgrade_url": "https://subpermits.com/pricing/"}}),
109
+ (404, {"error": {"code": "not_found", "message": "Not found"}}),
110
+ (429, {"error": {"code": "rate_limited", "message": "Daily limit reached"}}))
111
+ with self.assertRaises(AuthenticationError):
112
+ c.cities()
113
+ with self.assertRaises(PermissionDeniedError) as e:
114
+ c.projects(city="chicago")
115
+ self.assertEqual(e.exception.code, "outside_plan")
116
+ self.assertEqual(e.exception.upgrade_url, "https://subpermits.com/pricing/")
117
+ with self.assertRaises(NotFoundError):
118
+ c.project(1)
119
+ with self.assertRaises(RateLimitError) as e:
120
+ c.cities()
121
+ self.assertEqual(e.exception.rate_limit.reset, 1767225600)
122
+
123
+ def test_network_error(self):
124
+ def boom(*a):
125
+ raise OSError("connection refused")
126
+ c = Client(api_key="sp_test_x", transport=boom)
127
+ with self.assertRaises(subpermits.APIError):
128
+ c.cities()
129
+
130
+
131
+ class WebhookTests(unittest.TestCase):
132
+ def sign(self, secret, body, ts):
133
+ return f"t={ts},v1=" + hmac.new(secret.encode(), f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
134
+
135
+ def test_valid(self):
136
+ body, ts = b'{"event":"projects.new","data":[]}', int(time.time())
137
+ self.assertTrue(verify_webhook("whsec", self.sign("whsec", body, ts), body))
138
+ self.assertTrue(verify_webhook("whsec", self.sign("whsec", body, ts), body.decode()))
139
+
140
+ def test_wrong_secret_body_old_and_garbage(self):
141
+ body, ts = b"{}", int(time.time())
142
+ self.assertFalse(verify_webhook("other", self.sign("whsec", body, ts), body))
143
+ self.assertFalse(verify_webhook("whsec", self.sign("whsec", body, ts), b"{ }"))
144
+ self.assertFalse(verify_webhook("whsec", self.sign("whsec", body, ts - 1000), body))
145
+ self.assertFalse(verify_webhook("whsec", "garbage", body))
146
+
147
+
148
+ if __name__ == "__main__":
149
+ unittest.main()