byebouncer 0.1.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,56 @@
1
+ # Binaries
2
+ /bin/
3
+ /dist/
4
+ /server
5
+ server.exe
6
+ *.exe
7
+ *.dll
8
+ *.so
9
+ *.dylib
10
+
11
+ # Test binaries
12
+ *.test
13
+ *.out
14
+
15
+ # Go
16
+ vendor/
17
+ coverage.out
18
+ coverage.html
19
+
20
+ # Env / secrets
21
+ .env
22
+ .env.local
23
+ .env.*.local
24
+ .env.example
25
+ *.pem
26
+ *.key
27
+
28
+ # IDE
29
+ .claude/
30
+ .vscode/
31
+ .idea/
32
+ *.swp
33
+ *.swo
34
+ .DS_Store
35
+
36
+ # Node / Next.js (web/)
37
+ web/node_modules/
38
+ sdks/node/node_modules/
39
+ sdks/node/dist/
40
+ sdks/node/dist-cjs/
41
+ web/.next/
42
+ web/out/
43
+ web/.turbo/
44
+ web/.vercel/
45
+
46
+ # Logs
47
+ *.log
48
+ logs/
49
+
50
+ # Data files that are downloaded at build/run time
51
+ data/disposable_domains_downloaded.txt
52
+ sdks/python/.venv/
53
+ sdks/python/**/__pycache__/
54
+ sdks/python/**/*.egg-info/
55
+ sdks/python/.pytest_cache/
56
+ sdks/python/dist/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ByeBouncer
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,194 @@
1
+ Metadata-Version: 2.5
2
+ Name: byebouncer
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the ByeBouncer email verification API.
5
+ Project-URL: Homepage, https://byebouncer.com
6
+ Project-URL: Documentation, https://byebouncer.com/docs
7
+ Project-URL: Repository, https://github.com/fidelp27/byebouncer
8
+ Project-URL: Issues, https://github.com/fidelp27/byebouncer/issues
9
+ Author-email: ByeBouncer <hello@byebouncer.com>
10
+ License: MIT License
11
+
12
+ Copyright (c) 2026 ByeBouncer
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ License-File: LICENSE
32
+ Keywords: bounce,email,email-validation,smtp,verification
33
+ Classifier: Development Status :: 4 - Beta
34
+ Classifier: Intended Audience :: Developers
35
+ Classifier: License :: OSI Approved :: MIT License
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3.9
38
+ Classifier: Programming Language :: Python :: 3.10
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Programming Language :: Python :: 3.13
42
+ Classifier: Topic :: Communications :: Email
43
+ Requires-Python: >=3.9
44
+ Requires-Dist: httpx>=0.25
45
+ Provides-Extra: dev
46
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
47
+ Requires-Dist: pytest>=7; extra == 'dev'
48
+ Requires-Dist: respx>=0.21; extra == 'dev'
49
+ Requires-Dist: ruff>=0.6; extra == 'dev'
50
+ Description-Content-Type: text/markdown
51
+
52
+ # byebouncer
53
+
54
+ Official Python SDK for the [ByeBouncer](https://byebouncer.com) email verification API.
55
+
56
+ Sync and async clients, real-time single-email verification, bulk CSV verification (up to 50k emails per job), HMAC-signed webhooks.
57
+
58
+ ## Install
59
+
60
+ ```bash
61
+ pip install byebouncer
62
+ ```
63
+
64
+ Requires Python 3.9+.
65
+
66
+ ## Quickstart
67
+
68
+ ```python
69
+ import os
70
+ from byebouncer import ByeBouncer
71
+
72
+ with ByeBouncer(api_key=os.environ["BB_API_KEY"]) as client:
73
+ result = client.verify("user@gmail.com")
74
+ print(result.status) # "deliverable" | "undeliverable" | "risky" | "unknown"
75
+ print(result.action) # "allow" | "review" | "block"
76
+ print(result.signals) # ["valid_syntax", "mx_found", ...]
77
+ print(result.credits_remaining)
78
+ ```
79
+
80
+ Get your `BB_API_KEY` from https://byebouncer.com/dashboard (format `bb_live_...`).
81
+
82
+ ## Async
83
+
84
+ ```python
85
+ import asyncio
86
+ from byebouncer import AsyncByeBouncer
87
+
88
+ async def main():
89
+ async with AsyncByeBouncer(api_key="bb_live_...") as client:
90
+ result = await client.verify("user@gmail.com")
91
+ print(result.status)
92
+
93
+ asyncio.run(main())
94
+ ```
95
+
96
+ ## Bulk verification
97
+
98
+ ```python
99
+ created = client.bulk(
100
+ emails=["a@gmail.com", "b@outlook.com"], # up to 50.000
101
+ filename="my_list.csv",
102
+ webhook_url="https://api.myapp.com/hooks/byebouncer", # optional
103
+ )
104
+ job = created.job
105
+ print(f"Job {job.id}, {job.total_emails} emails")
106
+ print(f"Estimated duration: {created.estimated_seconds}s")
107
+
108
+ # Present when webhook_url is supplied (generated or supplied).
109
+ # Store it now: it is never returned by later job reads.
110
+ webhook_secret = created.webhook_secret
111
+ ```
112
+
113
+ ### Polling for completion
114
+
115
+ ```python
116
+ final = client.bulk_wait_for_completion(
117
+ job.id,
118
+ interval_seconds=3,
119
+ on_progress=lambda j: print(f"{j.processed}/{j.total_emails}"),
120
+ )
121
+
122
+ if final.status == "completed":
123
+ download = client.bulk_download_url(final.id)
124
+ csv = httpx.get(download.url).text
125
+ open("results.csv", "w").write(csv)
126
+ ```
127
+
128
+ ### Webhooks (recommended for large jobs)
129
+
130
+ Prefer webhooks over polling. On completion ByeBouncer POSTs to your URL with:
131
+
132
+ ```
133
+ X-ByeBouncer-Event: bulk.completed
134
+ X-ByeBouncer-Signature: <hex HMAC-SHA256(body, webhook_secret)>
135
+ ```
136
+
137
+ Attach or rotate the webhook after creating the job:
138
+
139
+ ```python
140
+ result = client.bulk_set_webhook(
141
+ job.id,
142
+ webhook_url="https://api.myapp.com/hooks/byebouncer",
143
+ )
144
+ webhook_secret = result.webhook_secret # store it NOW, returned only once
145
+ ```
146
+
147
+ ### Cancel
148
+
149
+ ```python
150
+ cancelled = client.bulk_cancel(job.id)
151
+ print(f"Refunded {cancelled.credits_refunded} credits")
152
+ ```
153
+
154
+ ## Error handling
155
+
156
+ Non-2xx responses raise `ByeBouncerError` or a subclass with `code`, `status`, `detail`.
157
+
158
+ ```python
159
+ from byebouncer import InsufficientCreditsError, RateLimitError, ByeBouncer
160
+
161
+ with ByeBouncer(api_key="bb_live_...") as client:
162
+ try:
163
+ client.verify("user@gmail.com")
164
+ except InsufficientCreditsError as e:
165
+ print(f"Out of credits (remaining: {e.credits_remaining})")
166
+ except RateLimitError as e:
167
+ print(f"Rate limited, retry after {e.retry_after_seconds}s")
168
+ ```
169
+
170
+ ## API reference
171
+
172
+ Every method mirrors the [OpenAPI spec](https://github.com/fidelp27/byebouncer/blob/master/docs/api/openapi.yaml).
173
+
174
+ | Method | Endpoint | Description |
175
+ |--------|----------|-------------|
176
+ | `verify(email)` | `POST /verify` | Verify a single email |
177
+ | `credits()` | `GET /credits` | Get balance |
178
+ | `bulk(emails, ...)` | `POST /bulk` | Enqueue a bulk job |
179
+ | `bulk_status(job_id)` | `GET /bulk/{id}` | Fetch job |
180
+ | `bulk_cancel(job_id)` | `DELETE /bulk/{id}` | Cancel |
181
+ | `bulk_download_url(job_id)` | `GET /bulk/{id}/download` | Signed CSV URL |
182
+ | `bulk_set_webhook(job_id, ...)` | `POST /bulk/{id}/webhook` | Attach/rotate webhook |
183
+ | `bulk_wait_for_completion(job_id, ...)` | polls | Convenience helper |
184
+ | `bulk_and_wait(emails, ...)` | create+poll+download | Available in sync and async clients |
185
+
186
+ ## Support
187
+
188
+ - Docs: https://byebouncer.com/docs
189
+ - Email: hello@byebouncer.com
190
+ - Issues: https://github.com/fidelp27/byebouncer/issues
191
+
192
+ ## License
193
+
194
+ MIT © ByeBouncer
@@ -0,0 +1,143 @@
1
+ # byebouncer
2
+
3
+ Official Python SDK for the [ByeBouncer](https://byebouncer.com) email verification API.
4
+
5
+ Sync and async clients, real-time single-email verification, bulk CSV verification (up to 50k emails per job), HMAC-signed webhooks.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install byebouncer
11
+ ```
12
+
13
+ Requires Python 3.9+.
14
+
15
+ ## Quickstart
16
+
17
+ ```python
18
+ import os
19
+ from byebouncer import ByeBouncer
20
+
21
+ with ByeBouncer(api_key=os.environ["BB_API_KEY"]) as client:
22
+ result = client.verify("user@gmail.com")
23
+ print(result.status) # "deliverable" | "undeliverable" | "risky" | "unknown"
24
+ print(result.action) # "allow" | "review" | "block"
25
+ print(result.signals) # ["valid_syntax", "mx_found", ...]
26
+ print(result.credits_remaining)
27
+ ```
28
+
29
+ Get your `BB_API_KEY` from https://byebouncer.com/dashboard (format `bb_live_...`).
30
+
31
+ ## Async
32
+
33
+ ```python
34
+ import asyncio
35
+ from byebouncer import AsyncByeBouncer
36
+
37
+ async def main():
38
+ async with AsyncByeBouncer(api_key="bb_live_...") as client:
39
+ result = await client.verify("user@gmail.com")
40
+ print(result.status)
41
+
42
+ asyncio.run(main())
43
+ ```
44
+
45
+ ## Bulk verification
46
+
47
+ ```python
48
+ created = client.bulk(
49
+ emails=["a@gmail.com", "b@outlook.com"], # up to 50.000
50
+ filename="my_list.csv",
51
+ webhook_url="https://api.myapp.com/hooks/byebouncer", # optional
52
+ )
53
+ job = created.job
54
+ print(f"Job {job.id}, {job.total_emails} emails")
55
+ print(f"Estimated duration: {created.estimated_seconds}s")
56
+
57
+ # Present when webhook_url is supplied (generated or supplied).
58
+ # Store it now: it is never returned by later job reads.
59
+ webhook_secret = created.webhook_secret
60
+ ```
61
+
62
+ ### Polling for completion
63
+
64
+ ```python
65
+ final = client.bulk_wait_for_completion(
66
+ job.id,
67
+ interval_seconds=3,
68
+ on_progress=lambda j: print(f"{j.processed}/{j.total_emails}"),
69
+ )
70
+
71
+ if final.status == "completed":
72
+ download = client.bulk_download_url(final.id)
73
+ csv = httpx.get(download.url).text
74
+ open("results.csv", "w").write(csv)
75
+ ```
76
+
77
+ ### Webhooks (recommended for large jobs)
78
+
79
+ Prefer webhooks over polling. On completion ByeBouncer POSTs to your URL with:
80
+
81
+ ```
82
+ X-ByeBouncer-Event: bulk.completed
83
+ X-ByeBouncer-Signature: <hex HMAC-SHA256(body, webhook_secret)>
84
+ ```
85
+
86
+ Attach or rotate the webhook after creating the job:
87
+
88
+ ```python
89
+ result = client.bulk_set_webhook(
90
+ job.id,
91
+ webhook_url="https://api.myapp.com/hooks/byebouncer",
92
+ )
93
+ webhook_secret = result.webhook_secret # store it NOW, returned only once
94
+ ```
95
+
96
+ ### Cancel
97
+
98
+ ```python
99
+ cancelled = client.bulk_cancel(job.id)
100
+ print(f"Refunded {cancelled.credits_refunded} credits")
101
+ ```
102
+
103
+ ## Error handling
104
+
105
+ Non-2xx responses raise `ByeBouncerError` or a subclass with `code`, `status`, `detail`.
106
+
107
+ ```python
108
+ from byebouncer import InsufficientCreditsError, RateLimitError, ByeBouncer
109
+
110
+ with ByeBouncer(api_key="bb_live_...") as client:
111
+ try:
112
+ client.verify("user@gmail.com")
113
+ except InsufficientCreditsError as e:
114
+ print(f"Out of credits (remaining: {e.credits_remaining})")
115
+ except RateLimitError as e:
116
+ print(f"Rate limited, retry after {e.retry_after_seconds}s")
117
+ ```
118
+
119
+ ## API reference
120
+
121
+ Every method mirrors the [OpenAPI spec](https://github.com/fidelp27/byebouncer/blob/master/docs/api/openapi.yaml).
122
+
123
+ | Method | Endpoint | Description |
124
+ |--------|----------|-------------|
125
+ | `verify(email)` | `POST /verify` | Verify a single email |
126
+ | `credits()` | `GET /credits` | Get balance |
127
+ | `bulk(emails, ...)` | `POST /bulk` | Enqueue a bulk job |
128
+ | `bulk_status(job_id)` | `GET /bulk/{id}` | Fetch job |
129
+ | `bulk_cancel(job_id)` | `DELETE /bulk/{id}` | Cancel |
130
+ | `bulk_download_url(job_id)` | `GET /bulk/{id}/download` | Signed CSV URL |
131
+ | `bulk_set_webhook(job_id, ...)` | `POST /bulk/{id}/webhook` | Attach/rotate webhook |
132
+ | `bulk_wait_for_completion(job_id, ...)` | polls | Convenience helper |
133
+ | `bulk_and_wait(emails, ...)` | create+poll+download | Available in sync and async clients |
134
+
135
+ ## Support
136
+
137
+ - Docs: https://byebouncer.com/docs
138
+ - Email: hello@byebouncer.com
139
+ - Issues: https://github.com/fidelp27/byebouncer/issues
140
+
141
+ ## License
142
+
143
+ MIT © ByeBouncer
@@ -0,0 +1,38 @@
1
+ """Official Python SDK for the ByeBouncer email verification API."""
2
+
3
+ from .client import AsyncByeBouncer, ByeBouncer
4
+ from .errors import (
5
+ ByeBouncerError,
6
+ InsufficientCreditsError,
7
+ RateLimitError,
8
+ UnauthorizedError,
9
+ )
10
+ from .models import (
11
+ BulkJob,
12
+ BulkJobStatus,
13
+ CreateBulkResponse,
14
+ CreditsInfo,
15
+ DomainInfo,
16
+ DownloadResponse,
17
+ SetWebhookResponse,
18
+ VerifyResult,
19
+ )
20
+
21
+ __version__ = "0.1.0"
22
+
23
+ __all__ = [
24
+ "AsyncByeBouncer",
25
+ "BulkJob",
26
+ "BulkJobStatus",
27
+ "ByeBouncer",
28
+ "ByeBouncerError",
29
+ "CreateBulkResponse",
30
+ "CreditsInfo",
31
+ "DomainInfo",
32
+ "DownloadResponse",
33
+ "InsufficientCreditsError",
34
+ "RateLimitError",
35
+ "SetWebhookResponse",
36
+ "UnauthorizedError",
37
+ "VerifyResult",
38
+ ]
@@ -0,0 +1,371 @@
1
+ """Sync and async clients for the ByeBouncer API.
2
+
3
+ Same surface as the Node SDK. `ByeBouncer` is sync, `AsyncByeBouncer` is async;
4
+ they share `_request` semantics and error translation via helpers.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import time
11
+ from json import JSONDecodeError
12
+ from typing import Any, Callable, Optional
13
+ from urllib.parse import quote
14
+
15
+ import httpx
16
+
17
+ from .errors import (
18
+ ByeBouncerError,
19
+ InsufficientCreditsError,
20
+ RateLimitError,
21
+ UnauthorizedError,
22
+ )
23
+ from .models import (
24
+ TERMINAL_STATUSES,
25
+ BulkJob,
26
+ CreateBulkResponse,
27
+ CreditsInfo,
28
+ DownloadResponse,
29
+ SetWebhookResponse,
30
+ VerifyResult,
31
+ )
32
+
33
+ DEFAULT_BASE_URL = "https://api.byebouncer.com"
34
+ DEFAULT_TIMEOUT = 30.0
35
+ USER_AGENT = "byebouncer-python/0.1.0"
36
+
37
+
38
+ def _parse_error(response: httpx.Response) -> ByeBouncerError:
39
+ payload: dict[str, Any] = {}
40
+ try:
41
+ payload = response.json()
42
+ except (JSONDecodeError, ValueError):
43
+ payload = {}
44
+ code = payload.get("error") or f"http_{response.status_code}"
45
+ detail = payload.get("detail")
46
+ status = response.status_code
47
+ if status == 401:
48
+ return UnauthorizedError(detail=detail, response=payload)
49
+ if status == 402:
50
+ return InsufficientCreditsError(
51
+ detail=detail,
52
+ response=payload,
53
+ credits_remaining=payload.get("credits_remaining"),
54
+ )
55
+ if status == 429:
56
+ ra = response.headers.get("retry-after")
57
+ return RateLimitError(
58
+ detail=detail,
59
+ response=payload,
60
+ retry_after_seconds=int(ra) if ra and ra.isdigit() else None,
61
+ )
62
+ return ByeBouncerError(code=code, status=status, detail=detail, response=payload)
63
+
64
+
65
+ class ByeBouncer:
66
+ """Synchronous client. For high-throughput usage prefer `AsyncByeBouncer`."""
67
+
68
+ def __init__(
69
+ self,
70
+ api_key: str,
71
+ *,
72
+ base_url: str = DEFAULT_BASE_URL,
73
+ timeout: float = DEFAULT_TIMEOUT,
74
+ client: Optional[httpx.Client] = None,
75
+ ) -> None:
76
+ if not api_key:
77
+ raise ValueError("api_key is required")
78
+ self._api_key = api_key
79
+ self._base_url = base_url.rstrip("/")
80
+ self._owns_client = client is None
81
+ self._client = client or httpx.Client(timeout=timeout)
82
+
83
+ def close(self) -> None:
84
+ if self._owns_client:
85
+ self._client.close()
86
+
87
+ def __enter__(self) -> "ByeBouncer":
88
+ return self
89
+
90
+ def __exit__(self, *_: object) -> None:
91
+ self.close()
92
+
93
+ # ─── Endpoints ────────────────────────────────────────────
94
+
95
+ def verify(self, email: str) -> VerifyResult:
96
+ data = self._request("POST", "/api/v1/verify", json={"email": email})
97
+ return VerifyResult.from_dict(data)
98
+
99
+ def credits(self) -> CreditsInfo:
100
+ return CreditsInfo.from_dict(self._request("GET", "/api/v1/credits"))
101
+
102
+ def bulk(
103
+ self,
104
+ emails: list[str],
105
+ *,
106
+ filename: Optional[str] = None,
107
+ webhook_url: Optional[str] = None,
108
+ webhook_secret: Optional[str] = None,
109
+ ) -> CreateBulkResponse:
110
+ body: dict[str, Any] = {"emails": emails}
111
+ if filename:
112
+ body["filename"] = filename
113
+ if webhook_url:
114
+ body["webhook_url"] = webhook_url
115
+ if webhook_secret:
116
+ body["webhook_secret"] = webhook_secret
117
+ data = self._request("POST", "/api/v1/bulk", json=body)
118
+ return CreateBulkResponse.from_dict(data)
119
+
120
+ def bulk_status(self, job_id: str) -> BulkJob:
121
+ data = self._request("GET", f"/api/v1/bulk/{quote(job_id, safe='')}")
122
+ return BulkJob.from_dict(data["job"])
123
+
124
+ def bulk_cancel(self, job_id: str) -> BulkJob:
125
+ data = self._request("DELETE", f"/api/v1/bulk/{quote(job_id, safe='')}")
126
+ return BulkJob.from_dict(data["job"])
127
+
128
+ def bulk_download_url(self, job_id: str) -> DownloadResponse:
129
+ return DownloadResponse.from_dict(
130
+ self._request("GET", f"/api/v1/bulk/{quote(job_id, safe='')}/download")
131
+ )
132
+
133
+ def bulk_set_webhook(
134
+ self, job_id: str, *, webhook_url: str, webhook_secret: Optional[str] = None
135
+ ) -> SetWebhookResponse:
136
+ body: dict[str, Any] = {"webhook_url": webhook_url}
137
+ if webhook_secret:
138
+ body["webhook_secret"] = webhook_secret
139
+ data = self._request(
140
+ "POST", f"/api/v1/bulk/{quote(job_id, safe='')}/webhook", json=body
141
+ )
142
+ return SetWebhookResponse.from_dict(data)
143
+
144
+ def bulk_wait_for_completion(
145
+ self,
146
+ job_id: str,
147
+ *,
148
+ interval_seconds: float = 3.0,
149
+ timeout_seconds: Optional[float] = None,
150
+ on_progress: Optional[Callable[[BulkJob], None]] = None,
151
+ ) -> BulkJob:
152
+ deadline = time.monotonic() + timeout_seconds if timeout_seconds else None
153
+ while True:
154
+ job = self.bulk_status(job_id)
155
+ if on_progress:
156
+ on_progress(job)
157
+ if job.status in TERMINAL_STATUSES:
158
+ return job
159
+ if deadline and time.monotonic() + interval_seconds > deadline:
160
+ raise TimeoutError(
161
+ f"bulk_wait_for_completion timed out after {timeout_seconds}s"
162
+ )
163
+ time.sleep(interval_seconds)
164
+
165
+ def bulk_and_wait(
166
+ self,
167
+ emails: list[str],
168
+ *,
169
+ filename: Optional[str] = None,
170
+ webhook_url: Optional[str] = None,
171
+ interval_seconds: float = 3.0,
172
+ timeout_seconds: Optional[float] = None,
173
+ on_progress: Optional[Callable[[BulkJob], None]] = None,
174
+ ) -> tuple[BulkJob, str]:
175
+ created = self.bulk(emails=emails, filename=filename, webhook_url=webhook_url)
176
+ job = created.job
177
+ final = self.bulk_wait_for_completion(
178
+ job.id,
179
+ interval_seconds=interval_seconds,
180
+ timeout_seconds=timeout_seconds,
181
+ on_progress=on_progress,
182
+ )
183
+ if final.status != "completed" or not final.result_available:
184
+ raise ByeBouncerError(
185
+ code="bulk_not_completed", status=0, detail=f"status={final.status}"
186
+ )
187
+ download = self.bulk_download_url(final.id)
188
+ csv_res = self._client.get(download.url)
189
+ if csv_res.status_code >= 300:
190
+ raise ByeBouncerError(
191
+ code="csv_download_failed",
192
+ status=csv_res.status_code,
193
+ detail=csv_res.text[:200],
194
+ )
195
+ return final, csv_res.text
196
+
197
+ # ─── Internal ────────────────────────────────────────────
198
+
199
+ def _headers(self, has_body: bool) -> dict[str, str]:
200
+ h = {
201
+ "Accept": "application/json",
202
+ "Authorization": f"Bearer {self._api_key}",
203
+ "User-Agent": USER_AGENT,
204
+ }
205
+ if has_body:
206
+ h["Content-Type"] = "application/json"
207
+ return h
208
+
209
+ def _request(self, method: str, path: str, *, json: Any = None) -> dict[str, Any]:
210
+ url = f"{self._base_url}{path}"
211
+ res = self._client.request(
212
+ method, url, headers=self._headers(json is not None), json=json
213
+ )
214
+ if res.status_code >= 300:
215
+ raise _parse_error(res)
216
+ if not res.content:
217
+ return {}
218
+ return res.json()
219
+
220
+
221
+ class AsyncByeBouncer:
222
+ """Async client using httpx.AsyncClient."""
223
+
224
+ def __init__(
225
+ self,
226
+ api_key: str,
227
+ *,
228
+ base_url: str = DEFAULT_BASE_URL,
229
+ timeout: float = DEFAULT_TIMEOUT,
230
+ client: Optional[httpx.AsyncClient] = None,
231
+ ) -> None:
232
+ if not api_key:
233
+ raise ValueError("api_key is required")
234
+ self._api_key = api_key
235
+ self._base_url = base_url.rstrip("/")
236
+ self._owns_client = client is None
237
+ self._client = client or httpx.AsyncClient(timeout=timeout)
238
+
239
+ async def aclose(self) -> None:
240
+ if self._owns_client:
241
+ await self._client.aclose()
242
+
243
+ async def __aenter__(self) -> "AsyncByeBouncer":
244
+ return self
245
+
246
+ async def __aexit__(self, *_: object) -> None:
247
+ await self.aclose()
248
+
249
+ async def verify(self, email: str) -> VerifyResult:
250
+ data = await self._request("POST", "/api/v1/verify", json={"email": email})
251
+ return VerifyResult.from_dict(data)
252
+
253
+ async def credits(self) -> CreditsInfo:
254
+ return CreditsInfo.from_dict(await self._request("GET", "/api/v1/credits"))
255
+
256
+ async def bulk(
257
+ self,
258
+ emails: list[str],
259
+ *,
260
+ filename: Optional[str] = None,
261
+ webhook_url: Optional[str] = None,
262
+ webhook_secret: Optional[str] = None,
263
+ ) -> CreateBulkResponse:
264
+ body: dict[str, Any] = {"emails": emails}
265
+ if filename:
266
+ body["filename"] = filename
267
+ if webhook_url:
268
+ body["webhook_url"] = webhook_url
269
+ if webhook_secret:
270
+ body["webhook_secret"] = webhook_secret
271
+ data = await self._request("POST", "/api/v1/bulk", json=body)
272
+ return CreateBulkResponse.from_dict(data)
273
+
274
+ async def bulk_status(self, job_id: str) -> BulkJob:
275
+ data = await self._request("GET", f"/api/v1/bulk/{quote(job_id, safe='')}")
276
+ return BulkJob.from_dict(data["job"])
277
+
278
+ async def bulk_cancel(self, job_id: str) -> BulkJob:
279
+ data = await self._request("DELETE", f"/api/v1/bulk/{quote(job_id, safe='')}")
280
+ return BulkJob.from_dict(data["job"])
281
+
282
+ async def bulk_download_url(self, job_id: str) -> DownloadResponse:
283
+ return DownloadResponse.from_dict(
284
+ await self._request("GET", f"/api/v1/bulk/{quote(job_id, safe='')}/download")
285
+ )
286
+
287
+ async def bulk_set_webhook(
288
+ self, job_id: str, *, webhook_url: str, webhook_secret: Optional[str] = None
289
+ ) -> SetWebhookResponse:
290
+ body: dict[str, Any] = {"webhook_url": webhook_url}
291
+ if webhook_secret:
292
+ body["webhook_secret"] = webhook_secret
293
+ data = await self._request(
294
+ "POST", f"/api/v1/bulk/{quote(job_id, safe='')}/webhook", json=body
295
+ )
296
+ return SetWebhookResponse.from_dict(data)
297
+
298
+ async def bulk_wait_for_completion(
299
+ self,
300
+ job_id: str,
301
+ *,
302
+ interval_seconds: float = 3.0,
303
+ timeout_seconds: Optional[float] = None,
304
+ on_progress: Optional[Callable[[BulkJob], None]] = None,
305
+ ) -> BulkJob:
306
+ deadline = time.monotonic() + timeout_seconds if timeout_seconds else None
307
+ while True:
308
+ job = await self.bulk_status(job_id)
309
+ if on_progress:
310
+ on_progress(job)
311
+ if job.status in TERMINAL_STATUSES:
312
+ return job
313
+ if deadline and time.monotonic() + interval_seconds > deadline:
314
+ raise TimeoutError(
315
+ f"bulk_wait_for_completion timed out after {timeout_seconds}s"
316
+ )
317
+ await asyncio.sleep(interval_seconds)
318
+
319
+ async def bulk_and_wait(
320
+ self,
321
+ emails: list[str],
322
+ *,
323
+ filename: Optional[str] = None,
324
+ webhook_url: Optional[str] = None,
325
+ interval_seconds: float = 3.0,
326
+ timeout_seconds: Optional[float] = None,
327
+ on_progress: Optional[Callable[[BulkJob], None]] = None,
328
+ ) -> tuple[BulkJob, str]:
329
+ created = await self.bulk(
330
+ emails=emails, filename=filename, webhook_url=webhook_url
331
+ )
332
+ final = await self.bulk_wait_for_completion(
333
+ created.job.id,
334
+ interval_seconds=interval_seconds,
335
+ timeout_seconds=timeout_seconds,
336
+ on_progress=on_progress,
337
+ )
338
+ if final.status != "completed" or not final.result_available:
339
+ raise ByeBouncerError(
340
+ code="bulk_not_completed", status=0, detail=f"status={final.status}"
341
+ )
342
+ download = await self.bulk_download_url(final.id)
343
+ csv_res = await self._client.get(download.url)
344
+ if csv_res.status_code >= 300:
345
+ raise ByeBouncerError(
346
+ code="csv_download_failed",
347
+ status=csv_res.status_code,
348
+ detail=csv_res.text[:200],
349
+ )
350
+ return final, csv_res.text
351
+
352
+ def _headers(self, has_body: bool) -> dict[str, str]:
353
+ h = {
354
+ "Accept": "application/json",
355
+ "Authorization": f"Bearer {self._api_key}",
356
+ "User-Agent": USER_AGENT,
357
+ }
358
+ if has_body:
359
+ h["Content-Type"] = "application/json"
360
+ return h
361
+
362
+ async def _request(self, method: str, path: str, *, json: Any = None) -> dict[str, Any]:
363
+ url = f"{self._base_url}{path}"
364
+ res = await self._client.request(
365
+ method, url, headers=self._headers(json is not None), json=json
366
+ )
367
+ if res.status_code >= 300:
368
+ raise _parse_error(res)
369
+ if not res.content:
370
+ return {}
371
+ return res.json()
@@ -0,0 +1,55 @@
1
+ """Exceptions raised by the SDK on non-2xx responses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+
8
+ class ByeBouncerError(Exception):
9
+ """Base error. Access `code`, `status`, and `detail`."""
10
+
11
+ def __init__(
12
+ self,
13
+ code: str,
14
+ status: int,
15
+ detail: Optional[str] = None,
16
+ response: Optional[Any] = None,
17
+ ) -> None:
18
+ super().__init__(detail or code)
19
+ self.code = code
20
+ self.status = status
21
+ self.detail = detail
22
+ self.response = response
23
+
24
+
25
+ class UnauthorizedError(ByeBouncerError):
26
+ """Raised on HTTP 401."""
27
+
28
+ def __init__(self, detail: Optional[str] = None, response: Optional[Any] = None) -> None:
29
+ super().__init__("invalid_api_key", 401, detail, response)
30
+
31
+
32
+ class InsufficientCreditsError(ByeBouncerError):
33
+ """Raised on HTTP 402."""
34
+
35
+ def __init__(
36
+ self,
37
+ detail: Optional[str] = None,
38
+ response: Optional[Any] = None,
39
+ credits_remaining: Optional[int] = None,
40
+ ) -> None:
41
+ super().__init__("insufficient_credits", 402, detail, response)
42
+ self.credits_remaining = credits_remaining
43
+
44
+
45
+ class RateLimitError(ByeBouncerError):
46
+ """Raised on HTTP 429."""
47
+
48
+ def __init__(
49
+ self,
50
+ detail: Optional[str] = None,
51
+ response: Optional[Any] = None,
52
+ retry_after_seconds: Optional[int] = None,
53
+ ) -> None:
54
+ super().__init__("rate_limited", 429, detail, response)
55
+ self.retry_after_seconds = retry_after_seconds
@@ -0,0 +1,179 @@
1
+ """Response models mirroring docs/api/openapi.yaml.
2
+
3
+ We keep them as plain dataclasses so the SDK stays dependency-light and Pydantic
4
+ version conflicts don't affect users. All fields are populated from the parsed
5
+ JSON response dict.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Literal, Optional
12
+
13
+ VerifyStatus = Literal["deliverable", "undeliverable", "risky", "unknown"]
14
+ VerifyAction = Literal["allow", "review", "block"]
15
+ DomainType = Literal["business", "free", "disposable", "education", "unknown"]
16
+ BulkJobStatus = Literal[
17
+ "pending", "processing", "completed", "failed", "cancelled", "expired"
18
+ ]
19
+
20
+
21
+ @dataclass
22
+ class DomainInfo:
23
+ name: str
24
+ type: DomainType
25
+ disposable: bool
26
+ free_provider: bool
27
+ has_mx: bool
28
+
29
+ @classmethod
30
+ def from_dict(cls, d: dict[str, Any]) -> "DomainInfo":
31
+ return cls(
32
+ name=d["name"],
33
+ type=d["type"],
34
+ disposable=d["disposable"],
35
+ free_provider=d["free_provider"],
36
+ has_mx=d["has_mx"],
37
+ )
38
+
39
+
40
+ @dataclass
41
+ class VerifyResult:
42
+ email: str
43
+ status: VerifyStatus
44
+ action: VerifyAction
45
+ flagged: bool
46
+ signals: list[str]
47
+ domain: DomainInfo
48
+ cached: bool
49
+ response_time_ms: int
50
+ verified_at: str
51
+ credits_remaining: int
52
+ suggestion: Optional[str] = None
53
+
54
+ @classmethod
55
+ def from_dict(cls, d: dict[str, Any]) -> "VerifyResult":
56
+ return cls(
57
+ email=d["email"],
58
+ status=d["status"],
59
+ action=d["action"],
60
+ flagged=d["flagged"],
61
+ signals=list(d.get("signals") or []),
62
+ domain=DomainInfo.from_dict(d["domain"]),
63
+ cached=d["cached"],
64
+ response_time_ms=d["response_time_ms"],
65
+ verified_at=d["verified_at"],
66
+ credits_remaining=d["credits_remaining"],
67
+ suggestion=d.get("suggestion"),
68
+ )
69
+
70
+
71
+ @dataclass
72
+ class CreditsInfo:
73
+ api_key_id: str
74
+ key_prefix: str
75
+ credits: int
76
+ auto_topup: bool
77
+
78
+ @classmethod
79
+ def from_dict(cls, d: dict[str, Any]) -> "CreditsInfo":
80
+ return cls(
81
+ api_key_id=d["api_key_id"],
82
+ key_prefix=d["key_prefix"],
83
+ credits=d["credits"],
84
+ auto_topup=d["auto_topup"],
85
+ )
86
+
87
+
88
+ @dataclass
89
+ class BulkJob:
90
+ id: str
91
+ source: Literal["api", "dashboard"]
92
+ status: BulkJobStatus
93
+ total_emails: int
94
+ processed: int
95
+ valid: int
96
+ invalid: int
97
+ unknown: int
98
+ credits_debited: int
99
+ credits_refunded: int
100
+ result_available: bool
101
+ created_at: str
102
+ expires_at: str
103
+ filename: Optional[str] = None
104
+ webhook_url: Optional[str] = None
105
+ error_message: Optional[str] = None
106
+ started_at: Optional[str] = None
107
+ completed_at: Optional[str] = None
108
+ estimated_seconds_remaining: Optional[int] = None
109
+ raw: dict[str, Any] = field(default_factory=dict, repr=False)
110
+
111
+ @classmethod
112
+ def from_dict(cls, d: dict[str, Any]) -> "BulkJob":
113
+ return cls(
114
+ id=d["id"],
115
+ source=d["source"],
116
+ status=d["status"],
117
+ total_emails=d["total_emails"],
118
+ processed=d["processed"],
119
+ valid=d["valid"],
120
+ invalid=d["invalid"],
121
+ unknown=d["unknown"],
122
+ credits_debited=d["credits_debited"],
123
+ credits_refunded=d["credits_refunded"],
124
+ result_available=d["result_available"],
125
+ created_at=d["created_at"],
126
+ expires_at=d["expires_at"],
127
+ filename=d.get("filename"),
128
+ webhook_url=d.get("webhook_url"),
129
+ error_message=d.get("error_message"),
130
+ started_at=d.get("started_at"),
131
+ completed_at=d.get("completed_at"),
132
+ estimated_seconds_remaining=d.get("estimated_seconds_remaining"),
133
+ raw=d,
134
+ )
135
+
136
+
137
+ @dataclass
138
+ class DownloadResponse:
139
+ url: str
140
+ expires_in_seconds: int
141
+
142
+ @classmethod
143
+ def from_dict(cls, d: dict[str, Any]) -> "DownloadResponse":
144
+ return cls(url=d["url"], expires_in_seconds=d["expires_in_seconds"])
145
+
146
+
147
+ @dataclass
148
+ class CreateBulkResponse:
149
+ job: BulkJob
150
+ estimated_seconds: int
151
+ webhook_secret: Optional[str] = None
152
+
153
+ @classmethod
154
+ def from_dict(cls, d: dict[str, Any]) -> "CreateBulkResponse":
155
+ return cls(
156
+ job=BulkJob.from_dict(d["job"]),
157
+ estimated_seconds=d["estimated_seconds"],
158
+ webhook_secret=d.get("webhook_secret"),
159
+ )
160
+
161
+
162
+ @dataclass
163
+ class SetWebhookResponse:
164
+ job_id: str
165
+ webhook_url: str
166
+ webhook_secret: str
167
+
168
+ @classmethod
169
+ def from_dict(cls, d: dict[str, Any]) -> "SetWebhookResponse":
170
+ return cls(
171
+ job_id=d["job_id"],
172
+ webhook_url=d["webhook_url"],
173
+ webhook_secret=d["webhook_secret"],
174
+ )
175
+
176
+
177
+ TERMINAL_STATUSES: frozenset[BulkJobStatus] = frozenset(
178
+ {"completed", "failed", "cancelled", "expired"}
179
+ )
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,35 @@
1
+ """Async bulk verification example.
2
+ Run: BB_API_KEY=bb_live_... python examples/bulk_async.py"""
3
+
4
+ import asyncio
5
+ import os
6
+
7
+ from byebouncer import AsyncByeBouncer
8
+
9
+
10
+ async def main() -> None:
11
+ async with AsyncByeBouncer(api_key=os.environ["BB_API_KEY"]) as client:
12
+ created = await client.bulk(
13
+ emails=["a@gmail.com", "b@outlook.com", "invalid@nomxexists.tld"],
14
+ filename="sdk_example.csv",
15
+ )
16
+ job = created.job
17
+ print(f"Job {job.id} enqueued, {job.total_emails} emails")
18
+
19
+ final = await client.bulk_wait_for_completion(
20
+ job.id,
21
+ interval_seconds=3,
22
+ on_progress=lambda j: print(
23
+ f"[{j.status}] {j.processed}/{j.total_emails}"
24
+ ),
25
+ )
26
+ print(
27
+ f"Done: valid={final.valid} invalid={final.invalid} unknown={final.unknown}"
28
+ )
29
+
30
+ if final.status == "completed":
31
+ download = await client.bulk_download_url(final.id)
32
+ print(f"Download URL (valid {download.expires_in_seconds}s): {download.url}")
33
+
34
+
35
+ asyncio.run(main())
@@ -0,0 +1,12 @@
1
+ """Single-email verification example.
2
+ Run: BB_API_KEY=bb_live_... python examples/verify.py"""
3
+
4
+ import os
5
+
6
+ from byebouncer import ByeBouncer
7
+
8
+ with ByeBouncer(api_key=os.environ["BB_API_KEY"]) as client:
9
+ result = client.verify("user@gmail.com")
10
+ print(f"{result.email} → {result.status} ({result.action})")
11
+ print(f"Signals: {', '.join(result.signals)}")
12
+ print(f"Credits left: {result.credits_remaining}")
@@ -0,0 +1,60 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "byebouncer"
7
+ version = "0.1.0"
8
+ description = "Official Python SDK for the ByeBouncer email verification API."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { file = "LICENSE" }
12
+ authors = [{ name = "ByeBouncer", email = "hello@byebouncer.com" }]
13
+ keywords = ["email", "verification", "bounce", "smtp", "email-validation"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.9",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Communications :: Email",
25
+ ]
26
+ dependencies = [
27
+ "httpx>=0.25",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ dev = [
32
+ "pytest>=7",
33
+ "pytest-asyncio>=0.23",
34
+ "respx>=0.21",
35
+ "ruff>=0.6",
36
+ ]
37
+
38
+ [project.urls]
39
+ Homepage = "https://byebouncer.com"
40
+ Documentation = "https://byebouncer.com/docs"
41
+ Repository = "https://github.com/fidelp27/byebouncer"
42
+ Issues = "https://github.com/fidelp27/byebouncer/issues"
43
+
44
+ [tool.hatch.build.targets.wheel]
45
+ packages = ["byebouncer"]
46
+
47
+ [tool.hatch.build.targets.sdist]
48
+ include = ["byebouncer", "tests", "examples", "README.md", "LICENSE", "pyproject.toml"]
49
+
50
+ [tool.pytest.ini_options]
51
+ asyncio_mode = "auto"
52
+ testpaths = ["tests"]
53
+
54
+ [tool.ruff]
55
+ line-length = 100
56
+ target-version = "py39"
57
+
58
+ [tool.ruff.lint]
59
+ select = ["E4", "E7", "E9", "F", "I", "B", "SIM"]
60
+ ignore = ["SIM117"] # Nested context managers preserve Python 3.9 syntax compatibility.
@@ -0,0 +1,197 @@
1
+ """Tests for the sync + async clients using respx mocks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import httpx
6
+ import pytest
7
+ import respx
8
+
9
+ from byebouncer import (
10
+ AsyncByeBouncer,
11
+ ByeBouncer,
12
+ InsufficientCreditsError,
13
+ UnauthorizedError,
14
+ )
15
+
16
+ BASE = "https://api.example.com"
17
+
18
+
19
+ def _verify_payload() -> dict:
20
+ return {
21
+ "email": "jane@gmail.com",
22
+ "status": "deliverable",
23
+ "action": "allow",
24
+ "flagged": False,
25
+ "signals": ["valid_syntax"],
26
+ "domain": {
27
+ "name": "gmail.com",
28
+ "type": "free",
29
+ "disposable": False,
30
+ "free_provider": True,
31
+ "has_mx": True,
32
+ },
33
+ "cached": False,
34
+ "response_time_ms": 184,
35
+ "verified_at": "2026-09-05T23:30:00Z",
36
+ "credits_remaining": 4999,
37
+ }
38
+
39
+
40
+ def _bulk_job_payload(*, status: str = "pending", result_available: bool = False) -> dict:
41
+ return {
42
+ "id": "job_1",
43
+ "source": "api",
44
+ "status": status,
45
+ "total_emails": 2,
46
+ "processed": 2 if status == "completed" else 0,
47
+ "valid": 2 if status == "completed" else 0,
48
+ "invalid": 0,
49
+ "unknown": 0,
50
+ "credits_debited": 2,
51
+ "credits_refunded": 0,
52
+ "result_available": result_available,
53
+ "created_at": "2026-09-05T00:00:00Z",
54
+ "expires_at": "2026-09-12T00:00:00Z",
55
+ }
56
+
57
+
58
+ @respx.mock
59
+ def test_verify_returns_result():
60
+ respx.post(f"{BASE}/api/v1/verify").mock(
61
+ return_value=httpx.Response(200, json=_verify_payload())
62
+ )
63
+ with ByeBouncer(api_key="bb_live_test", base_url=BASE) as client:
64
+ result = client.verify("jane@gmail.com")
65
+ assert result.status == "deliverable"
66
+ assert result.credits_remaining == 4999
67
+ assert result.domain.free_provider is True
68
+
69
+
70
+ @respx.mock
71
+ def test_verify_401_raises_unauthorized():
72
+ respx.post(f"{BASE}/api/v1/verify").mock(
73
+ return_value=httpx.Response(401, json={"error": "invalid_api_key"})
74
+ )
75
+ with ByeBouncer(api_key="bb_live_bad", base_url=BASE) as client:
76
+ with pytest.raises(UnauthorizedError):
77
+ client.verify("x@y.com")
78
+
79
+
80
+ @respx.mock
81
+ def test_verify_402_raises_insufficient_credits():
82
+ respx.post(f"{BASE}/api/v1/verify").mock(
83
+ return_value=httpx.Response(
84
+ 402, json={"error": "insufficient_credits", "credits_remaining": 0}
85
+ )
86
+ )
87
+ with ByeBouncer(api_key="bb_live_test", base_url=BASE) as client:
88
+ with pytest.raises(InsufficientCreditsError) as excinfo:
89
+ client.verify("x@y.com")
90
+ assert excinfo.value.credits_remaining == 0
91
+
92
+
93
+ @respx.mock
94
+ def test_bulk_returns_job():
95
+ respx.post(f"{BASE}/api/v1/bulk").mock(
96
+ return_value=httpx.Response(
97
+ 202,
98
+ json={
99
+ "job": _bulk_job_payload(),
100
+ "estimated_seconds": 5,
101
+ "webhook_secret": "generated-secret",
102
+ },
103
+ )
104
+ )
105
+ with ByeBouncer(api_key="bb_live_test", base_url=BASE) as client:
106
+ created = client.bulk(
107
+ emails=["a@x.com", "b@y.com"],
108
+ webhook_url="https://example.com/webhook",
109
+ )
110
+ assert created.job.id == "job_1"
111
+ assert created.job.status == "pending"
112
+ assert created.estimated_seconds == 5
113
+ assert created.webhook_secret == "generated-secret"
114
+
115
+
116
+ @respx.mock
117
+ def test_bulk_set_webhook_returns_typed_secret():
118
+ respx.post(f"{BASE}/api/v1/bulk/job_1/webhook").mock(
119
+ return_value=httpx.Response(
120
+ 200,
121
+ json={
122
+ "job_id": "job_1",
123
+ "webhook_url": "https://example.com/webhook",
124
+ "webhook_secret": "generated-secret",
125
+ },
126
+ )
127
+ )
128
+ with ByeBouncer(api_key="bb_live_test", base_url=BASE) as client:
129
+ webhook = client.bulk_set_webhook(
130
+ "job_1", webhook_url="https://example.com/webhook"
131
+ )
132
+ assert webhook.job_id == "job_1"
133
+ assert webhook.webhook_secret == "generated-secret"
134
+
135
+
136
+ @respx.mock
137
+ async def test_async_verify():
138
+ respx.post(f"{BASE}/api/v1/verify").mock(
139
+ return_value=httpx.Response(200, json=_verify_payload())
140
+ )
141
+ async with AsyncByeBouncer(api_key="bb_live_test", base_url=BASE) as client:
142
+ result = await client.verify("jane@gmail.com")
143
+ assert result.status == "deliverable"
144
+
145
+
146
+ @respx.mock
147
+ async def test_async_bulk_exposes_generated_webhook_secret():
148
+ respx.post(f"{BASE}/api/v1/bulk").mock(
149
+ return_value=httpx.Response(
150
+ 202,
151
+ json={
152
+ "job": _bulk_job_payload(),
153
+ "estimated_seconds": 5,
154
+ "webhook_secret": "generated-secret",
155
+ },
156
+ )
157
+ )
158
+ async with AsyncByeBouncer(api_key="bb_live_test", base_url=BASE) as client:
159
+ created = await client.bulk(
160
+ emails=["a@x.com", "b@y.com"],
161
+ webhook_url="https://example.com/webhook",
162
+ )
163
+ assert created.job.id == "job_1"
164
+ assert created.webhook_secret == "generated-secret"
165
+
166
+
167
+ @respx.mock
168
+ async def test_async_bulk_and_wait_downloads_csv():
169
+ respx.post(f"{BASE}/api/v1/bulk").mock(
170
+ return_value=httpx.Response(
171
+ 202,
172
+ json={"job": _bulk_job_payload(), "estimated_seconds": 5},
173
+ )
174
+ )
175
+ respx.get(f"{BASE}/api/v1/bulk/job_1").mock(
176
+ return_value=httpx.Response(
177
+ 200,
178
+ json={"job": _bulk_job_payload(status="completed", result_available=True)},
179
+ )
180
+ )
181
+ respx.get(f"{BASE}/api/v1/bulk/job_1/download").mock(
182
+ return_value=httpx.Response(
183
+ 200,
184
+ json={"url": "https://storage.example.com/result.csv", "expires_in_seconds": 86400},
185
+ )
186
+ )
187
+ respx.get("https://storage.example.com/result.csv").mock(
188
+ return_value=httpx.Response(200, text="email,status\na@x.com,deliverable\n")
189
+ )
190
+
191
+ async with AsyncByeBouncer(api_key="bb_live_test", base_url=BASE) as client:
192
+ job, csv = await client.bulk_and_wait(
193
+ emails=["a@x.com", "b@y.com"], interval_seconds=0.001
194
+ )
195
+
196
+ assert job.status == "completed"
197
+ assert "a@x.com,deliverable" in csv