leadwebia 0.2.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.
leadwebia/__init__.py ADDED
@@ -0,0 +1,41 @@
1
+ """LeadWebia — find local businesses and their contacts from Python.
2
+
3
+ Official client for the LeadWebia API v1: Google Maps lead searches by niche
4
+ and city, leads with emails and website audits, CRM status, CSV exports,
5
+ prospect reports, website tools and signed webhooks.
6
+ Docs: https://leadwebia.com/docs/api
7
+ """
8
+ from ._version import __version__
9
+ from .client import DEFAULT_BASE_URL, LeadWebia
10
+ from .errors import (
11
+ APIConnectionError,
12
+ AuthenticationError,
13
+ ConflictError,
14
+ InsufficientCreditsError,
15
+ LeadWebiaError,
16
+ NotFoundError,
17
+ PermissionDeniedError,
18
+ RateLimitError,
19
+ ServerError,
20
+ ValidationError,
21
+ )
22
+ from .webhooks import SIGNATURE_HEADER, compute_signature, verify_signature
23
+
24
+ __all__ = [
25
+ "LeadWebia",
26
+ "DEFAULT_BASE_URL",
27
+ "verify_signature",
28
+ "compute_signature",
29
+ "SIGNATURE_HEADER",
30
+ "LeadWebiaError",
31
+ "APIConnectionError",
32
+ "AuthenticationError",
33
+ "InsufficientCreditsError",
34
+ "PermissionDeniedError",
35
+ "NotFoundError",
36
+ "ConflictError",
37
+ "ValidationError",
38
+ "RateLimitError",
39
+ "ServerError",
40
+ "__version__",
41
+ ]
leadwebia/__main__.py ADDED
@@ -0,0 +1,68 @@
1
+ """Command line (reads the key from LEADWEBIA_API_KEY), prints JSON:
2
+
3
+ leadwebia me
4
+ leadwebia locations "Austin" --state TX
5
+ leadwebia website-check example.com [--pagespeed]
6
+ leadwebia emails example.com
7
+ leadwebia leads [--search-id 123]
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import sys
14
+ from typing import Any, List, Optional
15
+
16
+ from . import __version__
17
+ from .client import LeadWebia
18
+ from .errors import LeadWebiaError
19
+
20
+
21
+ def _parser() -> argparse.ArgumentParser:
22
+ parser = argparse.ArgumentParser(prog="leadwebia", description="LeadWebia API v1 from the command line.")
23
+ parser.add_argument("--version", action="version", version=f"leadwebia {__version__}")
24
+ sub = parser.add_subparsers(dest="command", required=True)
25
+ sub.add_parser("me", help="plan and credits of your key's account")
26
+ p = sub.add_parser("locations", help="areas (area_id) of a city")
27
+ p.add_argument("city")
28
+ p.add_argument("--country", default="US")
29
+ p.add_argument("--state")
30
+ p = sub.add_parser("website-check", help="CMS, tech stack, SSL (and PageSpeed) of a website")
31
+ p.add_argument("url")
32
+ p.add_argument("--pagespeed", action="store_true")
33
+ p = sub.add_parser("emails", help="emails, phones and socials published on a website")
34
+ p.add_argument("url")
35
+ p = sub.add_parser("leads", help="your latest leads")
36
+ p.add_argument("--search-id", type=int)
37
+ p.add_argument("--limit", type=int, default=25)
38
+ return parser
39
+
40
+
41
+ def _run(client: LeadWebia, args: argparse.Namespace) -> Any:
42
+ if args.command == "me":
43
+ return client.me()
44
+ if args.command == "locations":
45
+ return client.locations(args.city, country=args.country, state=args.state)
46
+ if args.command == "website-check":
47
+ return client.tools.website_check(args.url, include_pagespeed=args.pagespeed)
48
+ if args.command == "emails":
49
+ return client.tools.emails(args.url)
50
+ return client.leads.list(search_id=args.search_id, limit=args.limit)
51
+
52
+
53
+ def main(argv: Optional[List[str]] = None, client: Optional[LeadWebia] = None) -> int:
54
+ args = _parser().parse_args(argv)
55
+ try:
56
+ result = _run(client or LeadWebia(), args)
57
+ except ValueError as e:
58
+ print(f"error: {e}", file=sys.stderr)
59
+ return 2
60
+ except LeadWebiaError as e:
61
+ print(f"error: {e.code or e.status}: {e}", file=sys.stderr)
62
+ return 1
63
+ print(json.dumps(result, indent=2, ensure_ascii=False))
64
+ return 0
65
+
66
+
67
+ if __name__ == "__main__": # pragma: no cover
68
+ sys.exit(main())
leadwebia/_http.py ADDED
@@ -0,0 +1,129 @@
1
+ """Transport: auth header, JSON, typed errors and retries."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import random
6
+ import socket
7
+ import time
8
+ import urllib.error
9
+ import urllib.parse
10
+ import urllib.request
11
+ from typing import Any, Callable, Dict, Mapping, Optional
12
+
13
+ from ._version import __version__
14
+ from .errors import APIConnectionError, LeadWebiaError, error_class
15
+
16
+ RETRY_STATUSES = (429, 502, 503)
17
+ MAX_RETRY_AFTER = 60.0
18
+
19
+
20
+ class Transport:
21
+ def __init__(
22
+ self,
23
+ api_key: str,
24
+ base_url: str,
25
+ timeout: float,
26
+ max_retries: int,
27
+ user_agent: Optional[str] = None,
28
+ sleep: Callable[[float], None] = time.sleep,
29
+ ) -> None:
30
+ self.api_key = api_key
31
+ self.base_url = base_url.rstrip("/")
32
+ self.timeout = timeout
33
+ self.max_retries = max_retries
34
+ self.user_agent = user_agent or f"leadwebia-python/{__version__}"
35
+ self._sleep = sleep
36
+
37
+ def request(
38
+ self,
39
+ method: str,
40
+ path: str,
41
+ *,
42
+ params: Optional[Mapping[str, Any]] = None,
43
+ json_body: Any = None,
44
+ headers: Optional[Mapping[str, str]] = None,
45
+ ) -> Any:
46
+ url = self.base_url + path
47
+ query = _query(params)
48
+ if query:
49
+ url += "?" + query
50
+ data = None if json_body is None else json.dumps(json_body).encode("utf-8")
51
+ all_headers = {
52
+ "Authorization": f"Bearer {self.api_key}",
53
+ "Accept": "application/json",
54
+ "User-Agent": self.user_agent,
55
+ }
56
+ if data is not None:
57
+ all_headers["Content-Type"] = "application/json"
58
+ all_headers.update(headers or {})
59
+
60
+ attempt = 0
61
+ while True:
62
+ try:
63
+ return self._send(method, url, data, all_headers)
64
+ except LeadWebiaError as e:
65
+ retryable = e.status in RETRY_STATUSES or isinstance(e, APIConnectionError)
66
+ if not retryable or attempt >= self.max_retries:
67
+ raise
68
+ self._sleep(_delay(attempt, e.retry_after))
69
+ attempt += 1
70
+
71
+ def _send(self, method: str, url: str, data: Optional[bytes], headers: Dict[str, str]) -> Any:
72
+ req = urllib.request.Request(url, data=data, method=method, headers=headers)
73
+ try:
74
+ with urllib.request.urlopen(req, timeout=self.timeout) as response:
75
+ raw = response.read()
76
+ return json.loads(raw.decode("utf-8")) if raw else None
77
+ except urllib.error.HTTPError as e:
78
+ raise _api_error(e) from None
79
+ except (urllib.error.URLError, socket.timeout, TimeoutError, ConnectionError) as e:
80
+ reason = getattr(e, "reason", e)
81
+ raise APIConnectionError(f"Could not reach LeadWebia: {reason}") from None
82
+
83
+
84
+ def _query(params: Optional[Mapping[str, Any]]) -> str:
85
+ if not params:
86
+ return ""
87
+ pairs = []
88
+ for key, value in params.items():
89
+ if value is None:
90
+ continue
91
+ if isinstance(value, bool):
92
+ value = "true" if value else "false"
93
+ pairs.append((key, str(value)))
94
+ return urllib.parse.urlencode(pairs)
95
+
96
+
97
+ def _delay(attempt: int, retry_after: Optional[float]) -> float:
98
+ if retry_after is not None:
99
+ return min(max(retry_after, 0.0), MAX_RETRY_AFTER)
100
+ return min(0.5 * (2 ** attempt), 8.0) + random.uniform(0, 0.25)
101
+
102
+
103
+ def _retry_after(value: Optional[str]) -> Optional[float]:
104
+ if not value:
105
+ return None
106
+ try:
107
+ return float(value)
108
+ except ValueError:
109
+ return None
110
+
111
+
112
+ def _api_error(e: urllib.error.HTTPError) -> LeadWebiaError:
113
+ body: Dict[str, Any] = {}
114
+ try:
115
+ payload = json.loads(e.read().decode("utf-8"))
116
+ if isinstance(payload, dict) and isinstance(payload.get("error"), dict):
117
+ body = payload["error"]
118
+ except Exception:
119
+ pass
120
+ cls = error_class(e.code)
121
+ return cls(
122
+ body.get("message") or f"HTTP {e.code}",
123
+ code=body.get("code"),
124
+ status=e.code,
125
+ request_id=body.get("request_id") or e.headers.get("X-Request-Id"),
126
+ docs_url=body.get("docs_url"),
127
+ details=body.get("details"),
128
+ retry_after=_retry_after(e.headers.get("Retry-After")),
129
+ )
leadwebia/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
leadwebia/client.py ADDED
@@ -0,0 +1,340 @@
1
+ """LeadWebia API v1 client. Reference: https://api.leadwebia.com/api/v1/openapi.json"""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import time
6
+ import uuid
7
+ from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence
8
+ from urllib.parse import quote
9
+
10
+ from ._http import Transport
11
+
12
+ DEFAULT_BASE_URL = "https://api.leadwebia.com/api/v1"
13
+ DEFAULT_TIMEOUT = 90.0 # website checks with PageSpeed can take ~60 s
14
+ DEFAULT_MAX_RETRIES = 3
15
+ FINISHED_SEARCH_STATUSES = ("delivered", "completed", "failed", "cancelled")
16
+
17
+ JSON = Dict[str, Any]
18
+
19
+
20
+ def _p(value: Any) -> str:
21
+ return quote(str(value), safe="")
22
+
23
+
24
+ def _drop_none(**fields: Any) -> JSON:
25
+ return {k: v for k, v in fields.items() if v is not None}
26
+
27
+
28
+ class _Resource:
29
+ def __init__(self, client: "LeadWebia") -> None:
30
+ self._client = client
31
+
32
+ def _req(self, method: str, path: str, **kwargs: Any) -> Any:
33
+ return self._client._transport.request(method, path, **kwargs)
34
+
35
+
36
+ class Searches(_Resource):
37
+ """Google Maps lead searches. Starting one spends credits (1 per business delivered)."""
38
+
39
+ def create(
40
+ self,
41
+ niches: Sequence[str],
42
+ area_ids: Sequence[str],
43
+ max_leads: int,
44
+ *,
45
+ only_without_website: bool = False,
46
+ only_with_email: bool = False,
47
+ include_pagespeed: bool = False,
48
+ language: str = "en",
49
+ idempotency_key: Optional[str] = None,
50
+ ) -> JSON:
51
+ """Start a search: 1–5 niches in 1–20 areas (``area_id`` from :meth:`LeadWebia.locations`).
52
+
53
+ Reserves ``max_leads`` credits; unused credits return when it ends.
54
+ An ``Idempotency-Key`` is generated when you don't pass one, and reused
55
+ on automatic retries, so a retry never starts (or charges) twice.
56
+ """
57
+ body = {
58
+ "niches": list(niches),
59
+ "area_ids": list(area_ids),
60
+ "max_leads": max_leads,
61
+ "only_without_website": only_without_website,
62
+ "only_with_email": only_with_email,
63
+ "include_pagespeed": include_pagespeed,
64
+ "language": language,
65
+ }
66
+ return self._req("POST", "/searches", json_body=body,
67
+ headers={"Idempotency-Key": idempotency_key or str(uuid.uuid4())})
68
+
69
+ def list(self, *, limit: int = 25, offset: int = 0, status: Optional[str] = None) -> JSON:
70
+ """``{data, total, offset, next_offset, has_more}``, newest first."""
71
+ return self._req("GET", "/searches", params={"limit": limit, "offset": offset, "status": status})
72
+
73
+ def updates(self, updated_since: str = "0") -> JSON:
74
+ """Cursor feed of changed searches: ``{data, next_cursor, has_more}``."""
75
+ return self._req("GET", "/searches", params={"updated_since": updated_since})
76
+
77
+ def get(self, search_id: int) -> JSON:
78
+ return self._req("GET", f"/searches/{_p(search_id)}")
79
+
80
+ def runs(self, search_id: int) -> JSON:
81
+ return self._req("GET", f"/searches/{_p(search_id)}/runs")
82
+
83
+ def more(
84
+ self,
85
+ search_id: int,
86
+ max_leads: int,
87
+ *,
88
+ only_without_website: bool = False,
89
+ include_pagespeed: bool = False,
90
+ language: str = "en",
91
+ idempotency_key: Optional[str] = None,
92
+ ) -> JSON:
93
+ """Load more results of a search in the same area (spends credits like :meth:`create`).
94
+ ``ConflictError`` with code ``search_exhausted`` when the area is used up."""
95
+ body = {
96
+ "max_leads": max_leads,
97
+ "only_without_website": only_without_website,
98
+ "include_pagespeed": include_pagespeed,
99
+ "language": language,
100
+ }
101
+ return self._req("POST", f"/searches/{_p(search_id)}/more", json_body=body,
102
+ headers={"Idempotency-Key": idempotency_key or str(uuid.uuid4())})
103
+
104
+ def remaining(self, search_id: int) -> JSON:
105
+ return self._req("GET", f"/searches/{_p(search_id)}/remaining")
106
+
107
+ def wait(self, search_id: int, *, poll_interval: float = 10.0, timeout: float = 1800.0,
108
+ sleep: Callable[[float], None] = time.sleep) -> JSON:
109
+ """Poll :meth:`get` until the search is ``delivered``, ``completed`` or ``failed``."""
110
+ deadline = time.monotonic() + timeout
111
+ while True:
112
+ search = self.get(search_id)
113
+ if search.get("status") in FINISHED_SEARCH_STATUSES:
114
+ return search
115
+ if time.monotonic() >= deadline:
116
+ raise TimeoutError(f"search {search_id} still {search.get('status')} after {timeout:.0f}s")
117
+ sleep(poll_interval)
118
+
119
+
120
+ class Leads(_Resource):
121
+ """Saved leads (businesses) and their CRM status."""
122
+
123
+ def list(
124
+ self,
125
+ *,
126
+ search_id: Optional[int] = None,
127
+ website: Optional[str] = None,
128
+ status: Optional[str] = None,
129
+ q: Optional[str] = None,
130
+ cms: Optional[str] = None,
131
+ cms_outdated: Optional[bool] = None,
132
+ uses_ads: Optional[bool] = None,
133
+ has_email: Optional[bool] = None,
134
+ sort: Optional[str] = None,
135
+ limit: int = 25,
136
+ offset: int = 0,
137
+ ) -> JSON:
138
+ """Filtered page: ``{data, total, offset, next_offset, has_more}``.
139
+ ``website``: ``any`` | ``without`` | ``with`` | ``social_or_directory``."""
140
+ return self._req("GET", "/leads", params=_drop_none(
141
+ search_id=search_id, website=website, status=status, q=q, cms=cms,
142
+ cms_outdated=cms_outdated, uses_ads=uses_ads, has_email=has_email,
143
+ sort=sort, limit=limit, offset=offset))
144
+
145
+ def feed(self, since: str = "0", *, search_id: Optional[int] = None, q: Optional[str] = None,
146
+ limit: Optional[int] = None) -> JSON:
147
+ """One page of the polling feed: ``{data, next_cursor, has_more}``.
148
+ ``since``: ``"0"`` = everything, ``"now"`` = from now on, or a stored ``next_cursor``."""
149
+ return self._req("GET", "/leads", params=_drop_none(since=since, search_id=search_id, q=q, limit=limit))
150
+
151
+ def iter(self, since: str = "0", *, search_id: Optional[int] = None, q: Optional[str] = None,
152
+ on_cursor: Optional[Callable[[str], None]] = None) -> Iterator[JSON]:
153
+ """Every lead after ``since``, oldest first, following ``next_cursor`` until
154
+ ``has_more`` is false. ``on_cursor`` receives each new cursor: store the
155
+ last one and pass it as ``since`` next time to get only new leads."""
156
+ cursor = since
157
+ while True:
158
+ page = self.feed(cursor, search_id=search_id, q=q)
159
+ for lead in page.get("data") or []:
160
+ yield lead
161
+ cursor = page.get("next_cursor") or cursor
162
+ if on_cursor:
163
+ on_cursor(cursor)
164
+ if not page.get("has_more"):
165
+ return
166
+
167
+ def get(self, place_id: str) -> JSON:
168
+ return self._req("GET", f"/leads/{_p(place_id)}")
169
+
170
+ def set_status(self, place_id: str, status: Optional[str]) -> JSON:
171
+ """CRM status title or id (see :meth:`LeadWebia.lead_statuses`); None clears it."""
172
+ return self._req("PATCH", f"/leads/{_p(place_id)}", json_body={"status": status})
173
+
174
+ def bulk_status(self, status: Optional[str], *, place_ids: Optional[Sequence[str]] = None,
175
+ search_id: Optional[int] = None) -> JSON:
176
+ """Up to 500 ``place_ids``, or every lead of ``search_id``. Returns ``{count}``."""
177
+ body = _drop_none(place_ids=list(place_ids) if place_ids is not None else None, search_id=search_id)
178
+ body["status"] = status
179
+ return self._req("POST", "/leads/status", json_body=body)
180
+
181
+ def delete(self, place_id: str) -> JSON:
182
+ return self._req("DELETE", f"/leads/{_p(place_id)}")
183
+
184
+ def bulk_delete(self, place_ids: Sequence[str]) -> JSON:
185
+ return self._req("POST", "/leads/delete", json_body={"place_ids": list(place_ids)})
186
+
187
+ def outreach_message(self, place_id: str, *, language: Optional[str] = None,
188
+ sender_name: Optional[str] = None, agency_name: Optional[str] = None) -> JSON:
189
+ """AI-written cold email for this lead (no credits; daily cap)."""
190
+ return self._req("POST", f"/leads/{_p(place_id)}/outreach-message",
191
+ json_body=_drop_none(language=language, sender_name=sender_name, agency_name=agency_name))
192
+
193
+
194
+ class Exports(_Resource):
195
+ def create(self, *, place_ids: Optional[Sequence[str]] = None, search_id: Optional[int] = None,
196
+ website: str = "any") -> JSON:
197
+ """CSV of up to 5,000 leads: ``{count, url, filename, expires_at}``. Paid plans."""
198
+ body = _drop_none(place_ids=list(place_ids) if place_ids is not None else None, search_id=search_id)
199
+ body["website"] = website
200
+ return self._req("POST", "/exports", json_body=body)
201
+
202
+
203
+ class Integrations(_Resource):
204
+ """Push leads to tools already connected in the app (Instantly, Google Sheets, webhook)."""
205
+
206
+ def list(self) -> JSON:
207
+ return self._req("GET", "/integrations")
208
+
209
+ def targets(self, kind: str) -> JSON:
210
+ return self._req("GET", f"/integrations/{_p(kind)}/targets")
211
+
212
+ def send(self, kind: str, *, place_ids: Optional[Sequence[str]] = None, search_id: Optional[int] = None,
213
+ campaign_id: Optional[str] = None, spreadsheet_id: Optional[str] = None,
214
+ new_spreadsheet_name: Optional[str] = None) -> JSON:
215
+ return self._req("POST", f"/integrations/{_p(kind)}/send", json_body=_drop_none(
216
+ place_ids=list(place_ids) if place_ids is not None else None, search_id=search_id,
217
+ campaign_id=campaign_id, spreadsheet_id=spreadsheet_id, new_spreadsheet_name=new_spreadsheet_name))
218
+
219
+ def send_status(self, task_id: str) -> JSON:
220
+ return self._req("GET", f"/integrations/sends/{_p(task_id)}")
221
+
222
+
223
+ class Reports(_Resource):
224
+ """Prospect reports (online presence audit of one business)."""
225
+
226
+ def lookup(self, name: str, city: str, *, country: str = "US", keyword: Optional[str] = None) -> JSON:
227
+ """Find a business on Google Maps by name + city (no credits; daily cap)."""
228
+ return self._req("POST", "/reports/lookup",
229
+ json_body=_drop_none(name=name, city=city, country=country, keyword=keyword))
230
+
231
+ def create(self, place_id: str, *, lookup_id: Optional[str] = None, refresh: bool = False) -> JSON:
232
+ """Start a report (20 credits when a new run is needed; an existing report is free)."""
233
+ return self._req("POST", "/reports",
234
+ json_body=_drop_none(place_id=place_id, lookup_id=lookup_id, refresh=refresh))
235
+
236
+ def get(self, place_id: str, *, full: bool = False) -> JSON:
237
+ return self._req("GET", f"/reports/{_p(place_id)}", params={"full": full} if full else None)
238
+
239
+ def share(self, place_id: str, *, format: str = "link", language: str = "en") -> JSON:
240
+ return self._req("POST", f"/reports/{_p(place_id)}/share",
241
+ json_body={"format": format, "language": language})
242
+
243
+ def pdf(self, place_id: str) -> JSON:
244
+ return self._req("GET", f"/reports/{_p(place_id)}/pdf")
245
+
246
+
247
+ class Tools(_Resource):
248
+ """Website tools for any URL (no credits)."""
249
+
250
+ def website_check(self, url: str, *, include_pagespeed: bool = False) -> JSON:
251
+ """CMS and version, tech stack, ad pixels, SSL certificate and (optionally,
252
+ slower) Google PageSpeed scores and Core Web Vitals."""
253
+ return self._req("POST", "/tools/website-check", json_body={"url": url, "include_pagespeed": include_pagespeed})
254
+
255
+ def emails(self, url: str) -> JSON:
256
+ """Emails, phones and social profiles published on the website (20 websites/hour)."""
257
+ return self._req("POST", "/tools/emails", json_body={"url": url})
258
+
259
+
260
+ class Webhooks(_Resource):
261
+ """Event subscriptions (paid plans). Verify deliveries with :func:`leadwebia.verify_signature`."""
262
+
263
+ def list(self) -> JSON:
264
+ return self._req("GET", "/webhooks")
265
+
266
+ def create(self, url: str, events: Sequence[str], *, description: Optional[str] = None) -> JSON:
267
+ """Events: ``lead.created``, ``search.completed``, ``search.failed``, ``report.ready``,
268
+ ``report.failed``. The answer's ``signing_secret`` is shown only once: store it."""
269
+ return self._req("POST", "/webhooks",
270
+ json_body=_drop_none(url=url, events=list(events), description=description))
271
+
272
+ def get(self, webhook_id: str) -> JSON:
273
+ return self._req("GET", f"/webhooks/{_p(webhook_id)}")
274
+
275
+ def update(self, webhook_id: str, *, url: Optional[str] = None, events: Optional[Sequence[str]] = None,
276
+ description: Optional[str] = None, enabled: Optional[bool] = None) -> JSON:
277
+ return self._req("PATCH", f"/webhooks/{_p(webhook_id)}", json_body=_drop_none(
278
+ url=url, events=list(events) if events is not None else None, description=description, enabled=enabled))
279
+
280
+ def delete(self, webhook_id: str) -> None:
281
+ self._req("DELETE", f"/webhooks/{_p(webhook_id)}")
282
+
283
+ def test(self, webhook_id: str) -> JSON:
284
+ """Send a signed ``ping`` event now; returns the receiver's answer."""
285
+ return self._req("POST", f"/webhooks/{_p(webhook_id)}/test")
286
+
287
+ def deliveries(self, webhook_id: str) -> JSON:
288
+ return self._req("GET", f"/webhooks/{_p(webhook_id)}/deliveries")
289
+
290
+
291
+ class LeadWebia:
292
+ """Client for the LeadWebia API v1.
293
+
294
+ >>> from leadwebia import LeadWebia
295
+ >>> client = LeadWebia(api_key="lw_live_...") # or set LEADWEBIA_API_KEY
296
+ >>> client.me()["credits"] # doctest: +SKIP
297
+
298
+ Create a key in the app: https://leadwebia.com/api
299
+ """
300
+
301
+ def __init__(
302
+ self,
303
+ api_key: Optional[str] = None,
304
+ *,
305
+ base_url: str = DEFAULT_BASE_URL,
306
+ timeout: float = DEFAULT_TIMEOUT,
307
+ max_retries: int = DEFAULT_MAX_RETRIES,
308
+ user_agent: Optional[str] = None,
309
+ _sleep: Optional[Callable[[float], None]] = None,
310
+ ) -> None:
311
+ key = api_key or os.environ.get("LEADWEBIA_API_KEY")
312
+ if not key:
313
+ raise ValueError("Pass api_key or set LEADWEBIA_API_KEY (create a key at https://leadwebia.com/api)")
314
+ kwargs = {"sleep": _sleep} if _sleep else {}
315
+ self._transport = Transport(key, base_url, timeout, max_retries, user_agent, **kwargs)
316
+ self.searches = Searches(self)
317
+ self.leads = Leads(self)
318
+ self.exports = Exports(self)
319
+ self.integrations = Integrations(self)
320
+ self.reports = Reports(self)
321
+ self.tools = Tools(self)
322
+ self.webhooks = Webhooks(self)
323
+
324
+ # Account
325
+ def me(self) -> JSON:
326
+ """Plan, credits and ``paid_features`` of the key's account (also a credential test)."""
327
+ return self._transport.request("GET", "/me")
328
+
329
+ def lead_statuses(self) -> List[JSON]:
330
+ """The account's CRM statuses, in order."""
331
+ return self._transport.request("GET", "/lead-statuses")
332
+
333
+ # Locations
334
+ def locations(self, city: str, *, country: str = "US", state: Optional[str] = None) -> JSON:
335
+ """Areas matching a city: ``{data: [{area_id, name, state, country, population, points}]}``."""
336
+ return self._transport.request("GET", "/locations", params=_drop_none(city=city, country=country, state=state))
337
+
338
+ def iter_leads(self, since: str = "0", **kwargs: Any) -> Iterator[JSON]:
339
+ """Shortcut for :meth:`Leads.iter`."""
340
+ return self.leads.iter(since, **kwargs)
leadwebia/errors.py ADDED
@@ -0,0 +1,89 @@
1
+ """Exceptions raised by the LeadWebia client.
2
+
3
+ Every API error carries the fields of the v1 error envelope
4
+ (``{"error": {"code", "message", "status", "request_id", "docs_url"}}``).
5
+ Branch on ``error.code`` (e.g. ``"insufficient_credits"``) or on the subclass.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, Dict, Optional, Type
10
+
11
+
12
+ class LeadWebiaError(Exception):
13
+ """Base class. ``status`` is None when the API could not be reached."""
14
+
15
+ def __init__(
16
+ self,
17
+ message: str,
18
+ *,
19
+ code: Optional[str] = None,
20
+ status: Optional[int] = None,
21
+ request_id: Optional[str] = None,
22
+ docs_url: Optional[str] = None,
23
+ details: Any = None,
24
+ retry_after: Optional[float] = None,
25
+ ) -> None:
26
+ super().__init__(message)
27
+ self.message = message
28
+ self.code = code
29
+ self.status = status
30
+ self.request_id = request_id
31
+ self.docs_url = docs_url
32
+ self.details = details
33
+ self.retry_after = retry_after
34
+
35
+ def __repr__(self) -> str:
36
+ return f"{type(self).__name__}(code={self.code!r}, status={self.status!r}, message={self.message!r})"
37
+
38
+
39
+ class APIConnectionError(LeadWebiaError):
40
+ """Network error or timeout: the request never got an answer."""
41
+
42
+
43
+ class AuthenticationError(LeadWebiaError):
44
+ """401 ``invalid_api_key``: missing, unknown or revoked key."""
45
+
46
+
47
+ class InsufficientCreditsError(LeadWebiaError):
48
+ """402 ``insufficient_credits``: not enough credits for this search or report."""
49
+
50
+
51
+ class PermissionDeniedError(LeadWebiaError):
52
+ """403 ``paid_plan_required`` / ``professional_plan_required``."""
53
+
54
+
55
+ class NotFoundError(LeadWebiaError):
56
+ """404 ``not_found``, ``search_not_found``, ``lead_not_found``, ``report_not_found``."""
57
+
58
+
59
+ class ConflictError(LeadWebiaError):
60
+ """409 ``search_exhausted``, ``idempotency_conflict``, ``report_not_ready``, ``integration_not_connected``…"""
61
+
62
+
63
+ class ValidationError(LeadWebiaError):
64
+ """422 ``validation_error``; ``details`` lists the invalid fields."""
65
+
66
+
67
+ class RateLimitError(LeadWebiaError):
68
+ """429 ``rate_limited`` or another limit; ``retry_after`` is in seconds."""
69
+
70
+
71
+ class ServerError(LeadWebiaError):
72
+ """5xx: ``upstream_error``, ``website_unreadable``, ``internal_error``…"""
73
+
74
+
75
+ _BY_STATUS: Dict[int, Type[LeadWebiaError]] = {
76
+ 401: AuthenticationError,
77
+ 402: InsufficientCreditsError,
78
+ 403: PermissionDeniedError,
79
+ 404: NotFoundError,
80
+ 409: ConflictError,
81
+ 422: ValidationError,
82
+ 429: RateLimitError,
83
+ }
84
+
85
+
86
+ def error_class(status: int) -> Type[LeadWebiaError]:
87
+ if status in _BY_STATUS:
88
+ return _BY_STATUS[status]
89
+ return ServerError if status >= 500 else LeadWebiaError
leadwebia/py.typed ADDED
File without changes
leadwebia/webhooks.py ADDED
@@ -0,0 +1,27 @@
1
+ """Webhook signature verification."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import hmac
6
+ from typing import Optional, Union
7
+
8
+ SIGNATURE_HEADER = "X-LeadWebia-Signature"
9
+
10
+
11
+ def compute_signature(raw_body: Union[bytes, str], secret: str) -> str:
12
+ """``sha256=<hex HMAC-SHA256 of the raw body>``, as LeadWebia sends it."""
13
+ body = raw_body.encode("utf-8") if isinstance(raw_body, str) else raw_body
14
+ return "sha256=" + hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
15
+
16
+
17
+ def verify_signature(raw_body: Union[bytes, str], header: Optional[str], secret: str) -> bool:
18
+ """True when ``header`` (the ``X-LeadWebia-Signature`` value) matches the
19
+ raw request body signed with the webhook's ``signing_secret``.
20
+
21
+ Pass the body exactly as received (bytes), before any JSON parsing.
22
+ The comparison is constant-time.
23
+ """
24
+ if not header or not secret:
25
+ return False
26
+ expected = compute_signature(raw_body, secret)
27
+ return hmac.compare_digest(expected.encode("utf-8"), header.strip().encode("utf-8"))
@@ -0,0 +1,202 @@
1
+ Metadata-Version: 2.5
2
+ Name: leadwebia
3
+ Version: 0.2.0
4
+ Summary: Official LeadWebia API client: find local businesses on Google Maps by niche and city, their emails and website audits, CRM status, exports, reports and signed webhooks.
5
+ Project-URL: Homepage, https://leadwebia.com
6
+ Project-URL: Documentation, https://leadwebia.com/docs/api
7
+ Project-URL: API reference, https://api.leadwebia.com/api/v1/docs
8
+ Project-URL: Free tools, https://leadwebia.com/tools
9
+ Project-URL: Source, https://github.com/leadwebia/leadwebia-sdk
10
+ Project-URL: Issues, https://github.com/leadwebia/leadwebia-sdk/issues
11
+ Author: LeadWebia
12
+ License-Expression: MIT
13
+ License-File: LICENSE
14
+ Keywords: api client,b2b leads,email finder,google maps leads,lead generation,leadwebia,local business,webhooks,website audit
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Topic :: Internet :: WWW/HTTP
20
+ Classifier: Topic :: Office/Business
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.8
24
+ Description-Content-Type: text/markdown
25
+
26
+ # LeadWebia for Python
27
+
28
+ Official Python client for the [LeadWebia API](https://leadwebia.com/docs/api). Find local businesses on Google Maps by niche and city, get their emails, phones and website audit, manage them as leads, and push them to your tools or receive them by webhook.
29
+
30
+ [LeadWebia](https://leadwebia.com) is a lead generation tool for web designers, agencies and anyone who sells to local businesses: it finds businesses with or without a website, their contact details and what their current website is missing. The API does with an API key what you do in the app.
31
+
32
+ - Zero dependencies (standard library only), Python 3.8+, typed.
33
+ - Automatic `Idempotency-Key` on searches, so a retry never charges twice.
34
+ - Retries on `429` (honouring `Retry-After`), `502`, `503` and network errors.
35
+ - Typed errors per `error.code`, cursor iteration over new leads, webhook signature check.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install leadwebia
41
+ ```
42
+
43
+ ## Authentication
44
+
45
+ Create an API key in the app: [leadwebia.com/api](https://leadwebia.com/api) (Integrations → API). Pass it to the client or set `LEADWEBIA_API_KEY`.
46
+
47
+ ```python
48
+ from leadwebia import LeadWebia
49
+
50
+ client = LeadWebia(api_key="lw_live_...") # or LeadWebia() with LEADWEBIA_API_KEY set
51
+ print(client.me()["credits"])
52
+ ```
53
+
54
+ Keep the key on your server: it spends your account's credits.
55
+
56
+ ## Find leads
57
+
58
+ ```python
59
+ from leadwebia import LeadWebia
60
+
61
+ client = LeadWebia()
62
+
63
+ # 1. Pick the area
64
+ area = client.locations("Austin", state="TX")["data"][0]
65
+
66
+ # 2. Start a search: plumbers and roofers without a website, up to 50 businesses
67
+ search = client.searches.create(
68
+ niches=["plumber", "roofing contractor"],
69
+ area_ids=[area["area_id"]],
70
+ max_leads=50,
71
+ only_without_website=True,
72
+ )
73
+
74
+ # 3. Wait for it and read the leads
75
+ client.searches.wait(search["search_id"])
76
+ page = client.leads.list(search_id=search["search_id"], limit=100)
77
+ for lead in page["data"]:
78
+ print(lead["name"], lead.get("phone"), lead.get("emails"))
79
+ ```
80
+
81
+ A search reserves `max_leads` credits and charges 1 per business delivered (with `only_with_email=True`, 1 per business delivered with an email); unused credits return. `client.searches.more(search_id, max_leads=50)` loads more in the same area.
82
+
83
+ ## New leads as they arrive
84
+
85
+ `iter_leads` follows the polling cursor. Store the last cursor and pass it next time to get only new leads:
86
+
87
+ ```python
88
+ cursor = load_cursor() or "0" # "0" = everything, "now" = from now on
89
+ for lead in client.iter_leads(since=cursor, on_cursor=save_cursor):
90
+ add_to_crm(lead)
91
+ ```
92
+
93
+ ## Resources
94
+
95
+ | Group | Methods |
96
+ | --- | --- |
97
+ | Account | `me()`, `lead_statuses()` |
98
+ | Locations | `locations(city, country="US", state=None)` |
99
+ | Searches | `searches.create`, `.list`, `.updates(updated_since)`, `.get`, `.runs`, `.more`, `.remaining`, `.wait` |
100
+ | Leads | `leads.list(**filters)`, `.feed(since)`, `.iter(since)`, `.get`, `.set_status`, `.bulk_status`, `.delete`, `.bulk_delete`, `.outreach_message` |
101
+ | Exports | `exports.create(search_id=… or place_ids=…, website="any")` → CSV URL (paid plans) |
102
+ | Integrations | `integrations.list`, `.targets(kind)`, `.send(kind, …)`, `.send_status(task_id)` |
103
+ | Reports | `reports.lookup(name, city)`, `.create(place_id)`, `.get`, `.share`, `.pdf` |
104
+ | Tools | `tools.website_check(url, include_pagespeed=False)`, `tools.emails(url)` |
105
+ | Webhooks | `webhooks.create(url, events)`, `.list`, `.get`, `.update`, `.delete`, `.test`, `.deliveries` |
106
+
107
+ Lead filters: `search_id`, `website` (`any`, `without`, `with`, `social_or_directory`), `status`, `q`, `cms`, `cms_outdated`, `uses_ads`, `has_email`, `sort`, `limit`, `offset`. The full reference, with every field, is the [OpenAPI document](https://api.leadwebia.com/api/v1/docs).
108
+
109
+ ## Website tools
110
+
111
+ ```python
112
+ site = client.tools.website_check("joesplumbing.com", include_pagespeed=True)
113
+ contacts = client.tools.emails("joesplumbing.com")
114
+ print(site["technologies"].get("cms"), site["ssl"].get("days_remaining"), contacts["emails"])
115
+ ```
116
+
117
+ The same checks power LeadWebia's free [website tools](https://leadwebia.com/tools).
118
+
119
+ ## Webhooks
120
+
121
+ ```python
122
+ hook = client.webhooks.create("https://example.com/leadwebia", ["lead.created", "search.completed"])
123
+ secret = hook["signing_secret"] # shown only once: store it
124
+ ```
125
+
126
+ Verify each delivery with the raw body (before parsing JSON). Flask example:
127
+
128
+ ```python
129
+ from flask import Flask, request, abort
130
+ from leadwebia import verify_signature
131
+
132
+ app = Flask(__name__)
133
+
134
+ @app.post("/leadwebia")
135
+ def leadwebia_webhook():
136
+ if not verify_signature(request.get_data(), request.headers.get("X-LeadWebia-Signature"), SECRET):
137
+ abort(401)
138
+ event = request.get_json()
139
+ if event["type"] == "lead.created":
140
+ add_to_crm(event["data"])
141
+ return "", 204
142
+ ```
143
+
144
+ Webhooks need a paid plan.
145
+
146
+ ## Errors
147
+
148
+ Every API error is a `LeadWebiaError` with `code`, `message`, `status`, `request_id` and `docs_url`, raised as a subclass you can catch:
149
+
150
+ ```python
151
+ from leadwebia import InsufficientCreditsError, ConflictError, RateLimitError, LeadWebiaError
152
+
153
+ try:
154
+ client.searches.more(search_id, max_leads=100)
155
+ except InsufficientCreditsError as e:
156
+ print("Top up:", e.message)
157
+ except ConflictError as e:
158
+ if e.code == "search_exhausted":
159
+ print("This area is used up, search a new one")
160
+ except RateLimitError as e:
161
+ print("Retry in", e.retry_after, "s")
162
+ except LeadWebiaError as e:
163
+ print(e.code, e.message, e.request_id)
164
+ ```
165
+
166
+ | Exception | Status | Codes |
167
+ | --- | --- | --- |
168
+ | `AuthenticationError` | 401 | `invalid_api_key` |
169
+ | `InsufficientCreditsError` | 402 | `insufficient_credits` |
170
+ | `PermissionDeniedError` | 403 | `paid_plan_required`, `professional_plan_required` |
171
+ | `NotFoundError` | 404 | `not_found`, `search_not_found`, `lead_not_found`, `report_not_found` |
172
+ | `ConflictError` | 409 | `search_exhausted`, `idempotency_conflict`, `report_not_ready`, `integration_not_connected`, … |
173
+ | `ValidationError` | 422 | `validation_error` (`details` lists the fields) |
174
+ | `RateLimitError` | 429 | `rate_limited`, `email_lookup_limit`, `lookup_limit`, `message_limit`, `queue_full` |
175
+ | `ServerError` | 5xx | `upstream_error`, `website_unreadable`, `internal_error` |
176
+ | `APIConnectionError` | — | network error or timeout |
177
+
178
+ Limits: 60 requests/min per key, 120 per account, 10 credit-spending calls/min.
179
+
180
+ ## Command line
181
+
182
+ ```bash
183
+ export LEADWEBIA_API_KEY=lw_live_...
184
+ leadwebia me
185
+ leadwebia locations Austin --state TX
186
+ leadwebia website-check example.com --pagespeed
187
+ leadwebia emails example.com
188
+ leadwebia leads --search-id 123
189
+ ```
190
+
191
+ ## Development
192
+
193
+ ```bash
194
+ pip install -e .
195
+ python -m unittest discover -s tests -v
196
+ ```
197
+
198
+ The integration tests in `tests/test_live.py` run only with `LEADWEBIA_API_KEY` set (or a git-ignored `sdk/.env.test`); `LEADWEBIA_LIVE_SPEND=1..5` also runs one real search.
199
+
200
+ ## License
201
+
202
+ MIT
@@ -0,0 +1,13 @@
1
+ leadwebia/__init__.py,sha256=cFmHJ076aarepLTX25r24DDhA5P83qKJM5wC-9k8dhM,1151
2
+ leadwebia/__main__.py,sha256=mjCMndtnxqCzH6ly3WJDKmFVTNfiwUe8Y2luGCjKGzU,2609
3
+ leadwebia/_http.py,sha256=LwQ96sbRD7mLnyByJ7ZreTXFwWEjDII0b7hFs5rC_7M,4381
4
+ leadwebia/_version.py,sha256=0D6srYi9ejPUnwpjVmDoJB-oMuBqPSiP50LPRoM8G0I,23
5
+ leadwebia/client.py,sha256=goi3sChunYgWn-OmU62AKkFhV-hD3kJkpH_KXl2U_lg,15716
6
+ leadwebia/errors.py,sha256=Ii9gH5TIU2qeuVnFWRKTmW1omFig1jVyLdJLtFmcMe8,2805
7
+ leadwebia/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ leadwebia/webhooks.py,sha256=HCsd1ewRIQyzNNyV-CZjVEj40OXqVvLUTlHRpy4lQ44,1083
9
+ leadwebia-0.2.0.dist-info/METADATA,sha256=ZdGuwvqxoVF_neYbsclvAOkSoNiJBQ5F52F7Bso1NAo,8039
10
+ leadwebia-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ leadwebia-0.2.0.dist-info/entry_points.txt,sha256=EBZEvlSvtv54UPNU14N0dJcxhwpAQnz2ilCUO67e0Dc,54
12
+ leadwebia-0.2.0.dist-info/licenses/LICENSE,sha256=296WwTOY8EKFWK6RzSTCMS8RS0S3CCF4_ZalBbLR3h8,1087
13
+ leadwebia-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ leadwebia = leadwebia.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LeadWebia
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.