"""Server-side, read-only Zabalist API client. Python 3.10+, standard library.""" from __future__ import annotations import json from collections.abc import Iterator from typing import Any, Literal, NamedTuple, TypedDict, overload from urllib.error import HTTPError from urllib.parse import quote, urlencode from urllib.request import HTTPRedirectHandler, Request, build_opener _BASE = "https://www.zabalist.com/api/public/v1" _USER_AGENT = "Zabalist-Python/1.2.1 (+https://www.zabalist.com/developers/docs/signals)" Resource = Literal["projects", "permits", "bids", "plats"] Dataset = Literal["projects", "permits", "bids"] class SourceEvidence(TypedDict): source: str reference: str url: str | None class RecordDetail(TypedDict): record: dict[str, Any] evidence: list[SourceEvidence] history_url: str | None class SourceCoverage(TypedDict): source: str status: Literal["ok", "review", "unknown"] record_count: int | None last_checked_at: str | None last_synced_at: str | None latest_source_date: str | None last_check_age_days: int | None latest_filing_age_days: int | None class SignalCoverage(TypedDict): kind: str published_count: int latest_published_at: str | None class Coverage(TypedDict): captured_at: str sources: list[SourceCoverage] signals: list[SignalCoverage] def _text_field(value: Any) -> str | None: return value if isinstance(value, str) and value else None class ZabalistAPIError(RuntimeError): """A structured HTTP failure. The client never retries an API call automatically.""" def __init__(self, status: int, code: str, request_id: str | None, retry_after: str | None, error: dict[str, Any] | None = None): error = error or {} self.status = status self.code = code self.request_id = request_id self.retry_after = retry_after self.api_message = _text_field(error.get("message")) self.hint = _text_field(error.get("hint")) self.details = error.get("details") self.docs = _text_field(error.get("docs")) self.upgrade_url = _text_field(error.get("upgrade_url")) summary = f"Zabalist HTTP {status}, {code}, request {request_id or 'unknown'}, retry-after {retry_after or 'unspecified'}" super().__init__("\n".join(text for text in (summary, self.api_message, self.hint) if text)) class _NoRedirect(HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def _read(api_key: str, path: str, query: dict[str, Any] | None = None) -> Any: if not api_key: raise ValueError("A Zabalist API key is required") params = {k: v for k, v in (query or {}).items() if v is not None} req = Request(_BASE + path + ("?" + urlencode(params) if params else ""), headers={ "Authorization": "Bearer " + api_key, "Accept": "application/json", "User-Agent": _USER_AGENT, }) try: with build_opener(_NoRedirect()).open(req, timeout=15) as response: return json.load(response) except HTTPError as exc: with exc: try: body = json.load(exc) except ValueError: body = None error = body.get("error") if isinstance(body, dict) else None if not isinstance(error, dict): error = {} code = _text_field(error.get("code")) or "http_error" request_id = exc.headers.get("X-Request-Id") or _text_field(error.get("request_id")) raise ZabalistAPIError(exc.code, code, request_id, exc.headers.get("Retry-After"), error) from exc class SignalPage(NamedTuple): signals: list[dict] next_after: str has_more: bool def signal_page(api_key: str, *, kind=None, subject_id=None, county=None, issuer=None, after=None, limit=25) -> SignalPage: page = _read(api_key, "/signals", {"kind": kind, "subject_id": subject_id, "county": county, "issuer": issuer, "after": after, "limit": _bound(limit, 100, "limit")}) return SignalPage(page["data"], page["meta"]["next_after"], bool(page["meta"].get("has_more"))) def list_signals(api_key: str, *, kind=None, subject_id=None, county=None, issuer=None, after=None, limit=25) -> tuple[list[dict], str]: """Read one page as (signals, next_after). Save the checkpoint after committing the page.""" page = signal_page(api_key, kind=kind, subject_id=subject_id, county=county, issuer=issuer, after=after, limit=limit) return page.signals, page.next_after def _bound(value: int, maximum: int, name: str) -> int: if type(value) is not int or not 1 <= value <= maximum: raise ValueError(f"{name} must be an integer from 1 through {maximum}") return value def signal_pages(api_key: str, *, max_pages: int = 10, after: str | None = None, **filters) -> Iterator[SignalPage]: """Read up to max_pages pages (1–100). Restart from the last committed next_after.""" for _ in range(_bound(max_pages, 100, "max_pages")): page = signal_page(api_key, after=after, **filters) if (page.has_more and not page.signals) or (page.signals and int(page.next_after) <= int(after or "0")): raise ValueError("The signal page did not advance its checkpoint") yield page if not page.has_more: return after = page.next_after def _resource_id(record_id: str | int, *, allow_slash: bool = False) -> str: value = str(record_id) if not value or value in (".", "..") or ("/" in value and not allow_slash) or "\\" in value or len(value) > 220: raise ValueError("Supply one published record ID") return quote(value, safe="") class ObjectMeta(TypedDict, total=False): notes: list[str] test_mode: Literal[True] class CoverageResponse(TypedDict): data: Coverage meta: ObjectMeta @overload def get_record_response(api_key: str, resource: Literal["projects"], record_id: str | int) -> ProjectResponse: ... @overload def get_record_response(api_key: str, resource: Literal["permits"], record_id: str | int) -> PermitResponse: ... @overload def get_record_response(api_key: str, resource: Literal["bids"], record_id: str | int) -> BidResponse: ... @overload def get_record_response(api_key: str, resource: Literal["plats"], record_id: str | int) -> PlatResponse: ... def get_record_response(api_key: str, resource: Resource, record_id: str | int) -> ( ProjectResponse | PermitResponse | BidResponse | PlatResponse ): """Read one record with its analysis, source evidence and sample/delay metadata.""" if resource not in ("projects", "permits", "bids", "plats"): raise ValueError("Unsupported record type") return _read(api_key, "/" + resource + "/" + _resource_id(record_id, allow_slash=resource in ("bids", "plats"))) @overload def get_record(api_key: str, resource: Literal["projects"], record_id: str | int) -> ProjectDetail: ... @overload def get_record(api_key: str, resource: Literal["permits"], record_id: str | int) -> PermitDetail: ... @overload def get_record(api_key: str, resource: Literal["bids"], record_id: str | int) -> BidDetail: ... @overload def get_record(api_key: str, resource: Literal["plats"], record_id: str | int) -> PlatDetail: ... def get_record(api_key: str, resource: Resource, record_id: str | int) -> RecordDetail: """Read one record with its analysis and source evidence.""" return get_record_response(api_key, resource, record_id)["data"] def get_coverage_response(api_key: str) -> CoverageResponse: """Read dated source coverage, publication counts and sample metadata.""" return _read(api_key, "/coverage") def get_coverage(api_key: str) -> Coverage: return get_coverage_response(api_key)["data"] def list_records(api_key: str, dataset: Dataset, **filters) -> dict: """Read one list envelope and preserve its metadata and next_cursor.""" if dataset not in ("projects", "permits", "bids"): raise ValueError("Unsupported list dataset") if dataset == "projects" and "trade" in filters: raise ValueError("Use project_type to filter projects") if dataset == "bids" and isinstance(filters.get("construction_only"), bool): filters["construction_only"] = "true" if filters["construction_only"] else "false" return _read(api_key, "/" + dataset, filters) class _VerifyPage(TypedDict): data: list[VerifyMatch] meta: dict[str, Any] class VerifyResult(_VerifyPage, total=False): match: VerifyMatch | None alternates: list[dict[str, Any]] usage: dict[str, Any] def resolve_contractor(api_key: str, **filters) -> VerifyResult: return _read(api_key, "/contractors/verify", filters) def contractor_history(api_key: str, contractor_id: str, **filters) -> dict: return _read(api_key, "/contractors/" + _resource_id(contractor_id) + "/history", filters) def _cursor_pages(fetch_page, max_pages: int, filters: dict) -> Iterator[dict]: query = dict(filters) seen = {query.get("cursor")} _bound(query.get("limit", 25), 100, "limit") for _ in range(_bound(max_pages, 100, "max_pages")): page = fetch_page(**query) cursor = page["meta"].get("next_cursor") if cursor and (cursor in seen or not page["data"]): raise ValueError("The result page did not advance its cursor") yield page if not cursor: return seen.add(cursor) query.pop("offset", None) query["cursor"] = cursor def record_pages(api_key: str, dataset: Dataset, *, max_pages: int = 10, **filters) -> Iterator[dict]: return _cursor_pages(lambda **query: list_records(api_key, dataset, **query), max_pages, filters) def contractor_history_pages(api_key: str, contractor_id: str, *, max_pages: int = 10, **filters) -> Iterator[dict]: return _cursor_pages(lambda **query: contractor_history(api_key, contractor_id, **query), max_pages, filters) # Analytical result types from OpenAPI. Regenerate with scripts/developer-tools/sync-types.py. class ContractorFilingEvidenceBySource(TypedDict): permit: int site_plan: int subdivision: int tdlr: int class ContractorFilingEvidenceRolesItem(TypedDict): role: str filings: int class ContractorFilingEvidenceCitationsItem(TypedDict): source: Literal['permit', 'site_plan', 'subdivision', 'tdlr'] reference: str filing_date: str | None role: str | None class ContractorFilingEvidence(TypedDict): method: Literal['eligible-government-filings/v1'] scope: Literal['complete', 'bounded'] distinct_filings: int dated_filings: int first_filing_date: str | None last_filing_date: str | None pattern: Literal['none_observed', 'single_filing', 'multiple_filings_one_date', 'multiple_filing_dates', 'dates_incomplete'] by_source: ContractorFilingEvidenceBySource roles: list[ContractorFilingEvidenceRolesItem] citations: list[ContractorFilingEvidenceCitationsItem] class VerifyMatchEntity(TypedDict, total=False): id: str slug: str | None name: str | None canonical_name: str | None types: list[str] business_type: str | None city: str | None county: str | None state: str reported_state: str | None zip: str | None name_variants_merged: int | None class VerifyMatchTdlr(TypedDict, total=False): registered_projects: int last_registered_project_date: str | None activity_status: Literal['active', 'dormant', 'unknown'] license_verified: Literal[False] license_note: str registry_url: str class VerifyMatchWorkHistoryTopCountiesItem(TypedDict, total=False): county: str | None project_count: int last_project_date: str | None class VerifyMatchWorkHistoryBySource(TypedDict, total=False): permit: int site_plan: int subdivision: int tdlr: int class VerifyMatchWorkHistoryByRole(TypedDict, total=False): owner: int design_firm: int contractor: int developer: int class VerifyMatchWorkHistory(TypedDict, total=False): project_count: int verified_project_count: int active_projects: int total_value: float | None first_activity_date: str | None last_activity_date: str | None counties_active: int counties: list[str] top_counties: list[VerifyMatchWorkHistoryTopCountiesItem] by_source: VerifyMatchWorkHistoryBySource by_role: VerifyMatchWorkHistoryByRole class VerifyMatchGovcon(TypedDict, total=False): sam_registered: bool reported_sam_registered: bool | None uei: str | None certifications: list[str] primary_naics: str | None naics_codes: list[str] class VerifyMatchRequired(TypedDict): filing_evidence: ContractorFilingEvidence class VerifyMatch(VerifyMatchRequired, total=False): confidence: float risk_flags: list[Literal['dormant', 'no_verified_work', 'name_churn']] licenses: list[Any] entity: VerifyMatchEntity matched_on: Literal['name', 'license'] matched_value: str tdlr: VerifyMatchTdlr work_history: VerifyMatchWorkHistory govcon: VerifyMatchGovcon provenance: list[str] history_url: str class ProjectFilingInsightSourceCounts(TypedDict): tdlr: int permit: int site_plan: int subdivision: int class ProjectFilingInsightLatestFilingVariant1(TypedDict): source: Literal['tdlr', 'permit', 'site_plan', 'subdivision'] reference: str date: str date_basis: Literal['tdlr_registration', 'permit_issue', 'application_start'] class ProjectFilingInsightValuationVariant1LargestFiledEstimateVariant1(TypedDict): source: Literal['tdlr', 'permit'] reference: str amount_usd: float class ProjectFilingInsightValuationVariant1(TypedDict): positive_estimate_count: int repeated_across_sources: bool largest_filed_estimate: ProjectFilingInsightValuationVariant1LargestFiledEstimateVariant1 | None class ProjectFilingInsightRegistrationToPermitVariant1Registration(TypedDict): source: Literal['tdlr', 'permit', 'site_plan', 'subdivision'] reference: str date: str date_basis: Literal['tdlr_registration', 'permit_issue', 'application_start'] class ProjectFilingInsightRegistrationToPermitVariant1Permit(TypedDict): source: Literal['tdlr', 'permit', 'site_plan', 'subdivision'] reference: str date: str date_basis: Literal['tdlr_registration', 'permit_issue', 'application_start'] class ProjectFilingInsightRegistrationToPermitVariant1(TypedDict): registration: ProjectFilingInsightRegistrationToPermitVariant1Registration permit: ProjectFilingInsightRegistrationToPermitVariant1Permit days_between: int class ProjectFilingInsight(TypedDict): method: Literal['project_filing_activity/v1'] coverage: Literal['complete_link_scan', 'recent_100_links'] verified_filing_count: int source_counts: ProjectFilingInsightSourceCounts permit_evidence: Literal['issued_permit_observed', 'permit_record_without_issue_date', 'no_permit_record_observed'] latest_filing: ProjectFilingInsightLatestFilingVariant1 | None valuation: ProjectFilingInsightValuationVariant1 | None registration_to_permit: ProjectFilingInsightRegistrationToPermitVariant1 | None class ProjectDetail(RecordDetail): insight: ProjectFilingInsight class ProjectResponse(TypedDict): data: ProjectDetail meta: ObjectMeta class PermitProjectInsightLinkedRegistrationRegistration(TypedDict): reference: str date: str days_to_permit: int class PermitProjectInsightLinkedRegistration(TypedDict): method: Literal['permit_project_filing/v1'] status: Literal['linked_registration'] project_id: str registration: PermitProjectInsightLinkedRegistrationRegistration class PermitProjectInsightProjectOnly(TypedDict): method: Literal['permit_project_filing/v1'] status: Literal['project_only'] project_id: str registration: None class PermitProjectInsightVariant3(TypedDict): method: Literal['permit_project_filing/v1'] status: Literal['no_supported_link', 'issuer_not_covered'] project_id: None registration: None PermitProjectInsight = PermitProjectInsightLinkedRegistration | PermitProjectInsightProjectOnly | PermitProjectInsightVariant3 class PermitDetail(RecordDetail): insight: PermitProjectInsight class PermitResponse(TypedDict): data: PermitDetail meta: ObjectMeta class BidInsightPrecedentExamplesItem(TypedDict): id: str posting_date: str shared_nigp_codes: list[str] source_url: str | None class BidInsightPrecedent(TypedDict): state: Literal['matched', 'no_match', 'insufficient_basis'] window_start: str | None before: str | None matched_notice_count: int | None examples: list[BidInsightPrecedentExamplesItem] class BidInsight(TypedDict): response_window: Literal['upcoming', 'due_today_confirm_time', 'past_due_still_posted', 'agency_closed', 'not_a_response_notice', 'verify_source'] response_window_verification_reason: Literal['no_response_date', 'posting_date_conflict', 'status_unconfirmed', 'source_clock_unavailable', 'source_clock_stale', 'issuer_time_zone_unconfirmed', 'no_observation_after_deadline'] | None as_of_date: str source_checked_at: str | None days_until_due: int | None precedent: BidInsightPrecedent class BidDetail(RecordDetail): insight: BidInsight class BidResponse(TypedDict): data: BidDetail meta: ObjectMeta class PlatBenchmarkAvailable(TypedDict): method: Literal['same_edition_county_cohort_v1'] minimum_peers: Literal[10] status: Literal['available'] county: str peer_plat_count: int peer_q1_appraised_psf: int peer_median_appraised_psf: int peer_q3_appraised_psf: int difference_from_peer_median_psf: int position: Literal['below_middle_half', 'within_middle_half', 'above_middle_half'] class PlatBenchmarkUnavailable(TypedDict): method: Literal['same_edition_county_cohort_v1'] minimum_peers: Literal[10] status: Literal['unavailable'] county: str | None peer_plat_count: int reason: Literal['county_unreported', 'insufficient_peers'] PlatBenchmark = PlatBenchmarkAvailable | PlatBenchmarkUnavailable class PlatDetail(RecordDetail): insight: PlatBenchmark class PlatResponse(TypedDict): data: PlatDetail meta: ObjectMeta