inboundr 0.1.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.
inboundr/__init__.py ADDED
@@ -0,0 +1,65 @@
1
+ """Python SDK for the Inboundr API.
2
+
3
+ ::
4
+
5
+ from inboundr import Inboundr, verify_webhook
6
+
7
+ client = Inboundr() # reads INBOUNDR_API_KEY
8
+ page = client.emails.list({"direction": "inbound", "limit": 20})
9
+ """
10
+
11
+ from ._async_client import AsyncInboundr
12
+ from ._base import API_KEY_ENV_VAR, DEFAULT_BASE_URL
13
+ from ._client import Inboundr
14
+ from ._errors import (
15
+ InboundrAPIError,
16
+ InboundrError,
17
+ InboundrRateLimitError,
18
+ InboundrSignatureError,
19
+ SignatureFailureReason,
20
+ )
21
+ from ._types import * # noqa: F403
22
+ from ._types import __all__ as _types_all
23
+ from ._version import __version__
24
+ from ._webhooks import (
25
+ DEFAULT_TOLERANCE_SECONDS,
26
+ DELIVERY_ID_HEADER,
27
+ EMAIL_ID_HEADER,
28
+ EVENT_HEADER,
29
+ ID_SIGNATURE_HEADER,
30
+ LEGACY_DELIVERY_ID_HEADER,
31
+ LEGACY_SIGNATURE_HEADER,
32
+ SIGNATURE_HEADER,
33
+ WebhookHeaders,
34
+ WebhookIds,
35
+ read_webhook_headers,
36
+ verify_webhook,
37
+ verify_webhook_ids,
38
+ )
39
+
40
+ __all__ = [
41
+ "API_KEY_ENV_VAR",
42
+ "AsyncInboundr",
43
+ "DEFAULT_BASE_URL",
44
+ "DEFAULT_TOLERANCE_SECONDS",
45
+ "DELIVERY_ID_HEADER",
46
+ "EMAIL_ID_HEADER",
47
+ "EVENT_HEADER",
48
+ "ID_SIGNATURE_HEADER",
49
+ "Inboundr",
50
+ "InboundrAPIError",
51
+ "InboundrError",
52
+ "InboundrRateLimitError",
53
+ "InboundrSignatureError",
54
+ "LEGACY_DELIVERY_ID_HEADER",
55
+ "LEGACY_SIGNATURE_HEADER",
56
+ "SIGNATURE_HEADER",
57
+ "SignatureFailureReason",
58
+ "WebhookHeaders",
59
+ "WebhookIds",
60
+ "__version__",
61
+ "read_webhook_headers",
62
+ "verify_webhook",
63
+ "verify_webhook_ids",
64
+ *_types_all,
65
+ ]
@@ -0,0 +1,338 @@
1
+ """The async client. `_client.py` is generated from this file by
2
+ scripts/unasync.py; edit this one and regenerate."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import AsyncIterator, Sequence
7
+ from typing import Any, Literal, cast
8
+
9
+ import httpx
10
+
11
+ from . import _base
12
+ from ._types import (
13
+ Address,
14
+ AttachmentUrl,
15
+ CreateAddressParams,
16
+ CreatedAddress,
17
+ CreateDomainParams,
18
+ CreateEndpointParams,
19
+ CreateForwardDestinationParams,
20
+ CreateShieldRuleParams,
21
+ CreateSuppressionParams,
22
+ Delivery,
23
+ Domain,
24
+ DomainDetail,
25
+ Email,
26
+ EmailSummary,
27
+ Endpoint,
28
+ EndpointTestResult,
29
+ EndpointWithSecret,
30
+ ForwardDestination,
31
+ ForwardDestinationRequest,
32
+ List,
33
+ ListDeliveriesParams,
34
+ ListEmailsParams,
35
+ Page,
36
+ ReplaceShieldRuleParams,
37
+ ReplyParams,
38
+ RetryResult,
39
+ Sender,
40
+ SendEmailParams,
41
+ SentEmail,
42
+ ShieldRule,
43
+ ShieldRuleOrder,
44
+ SuppressedAddress,
45
+ Suppression,
46
+ Thread,
47
+ UpdateAddressParams,
48
+ UpdatedDomain,
49
+ UpdateDomainParams,
50
+ UpdateEndpointParams,
51
+ )
52
+
53
+ __all__ = ["AsyncInboundr"]
54
+
55
+ _seg = _base.segment
56
+
57
+
58
+ class AsyncInboundr:
59
+ """Client for the Inboundr API.
60
+
61
+ ::
62
+
63
+ client = AsyncInboundr() # reads INBOUNDR_API_KEY
64
+ client = AsyncInboundr("inb_...")
65
+ """
66
+
67
+ def __init__(
68
+ self,
69
+ api_key: str | None = None,
70
+ *,
71
+ base_url: str = _base.DEFAULT_BASE_URL,
72
+ timeout: float | None = _base.DEFAULT_TIMEOUT,
73
+ http_client: httpx.AsyncClient | None = None,
74
+ ) -> None:
75
+ key = _base.resolve_api_key(api_key)
76
+ self.base_url = base_url.rstrip("/")
77
+ self._timeout = timeout
78
+ self._owns_client = http_client is None
79
+ self._http = http_client or httpx.AsyncClient(timeout=timeout)
80
+ self._url = _base.base_api_url(self.base_url)
81
+ self._headers = _base.default_headers(key)
82
+
83
+ self.emails = AsyncEmails(self)
84
+ self.threads = AsyncThreads(self)
85
+ self.domains = AsyncDomains(self)
86
+ self.addresses = AsyncAddresses(self)
87
+ self.endpoints = AsyncEndpoints(self)
88
+ self.shield_rules = AsyncShieldRules(self)
89
+ self.senders = AsyncSenders(self)
90
+ self.suppressions = AsyncSuppressions(self)
91
+ self.forward_destinations = AsyncForwardDestinations(self)
92
+
93
+ async def _request(
94
+ self,
95
+ method: str,
96
+ path: str,
97
+ *,
98
+ query: Any = None,
99
+ body: Any = None,
100
+ raw: bool = False,
101
+ ) -> Any:
102
+ try:
103
+ response = await self._http.request(
104
+ method,
105
+ self._url + path,
106
+ params=_base.clean_query(query),
107
+ json=body,
108
+ headers=self._headers,
109
+ timeout=self._timeout,
110
+ )
111
+ except httpx.HTTPError as exc:
112
+ raise _base.transport_error(method, path, exc, self._timeout) from exc
113
+ return _base.handle_response(response, raw=raw)
114
+
115
+ async def close(self) -> None:
116
+ if self._owns_client:
117
+ await self._http.aclose()
118
+
119
+ async def __aenter__(self) -> AsyncInboundr:
120
+ return self
121
+
122
+ async def __aexit__(self, *exc: object) -> None:
123
+ await self.close()
124
+
125
+
126
+ class _AsyncResource:
127
+ def __init__(self, client: AsyncInboundr) -> None:
128
+ self._client = client
129
+
130
+
131
+ class AsyncEmails(_AsyncResource):
132
+ async def list(self, params: ListEmailsParams | None = None) -> Page[EmailSummary]:
133
+ """One page of emails, newest first. Bodies are omitted; use `get`."""
134
+ return cast(Page[EmailSummary], await self._client._request("GET", "/emails", query=params))
135
+
136
+ async def list_all(self, params: ListEmailsParams | None = None) -> AsyncIterator[EmailSummary]:
137
+ """Every matching email, newest first, fetching pages as you iterate."""
138
+ query: dict[str, Any] = dict(params or {})
139
+ while True:
140
+ page = await self.list(cast(ListEmailsParams, query))
141
+ for item in page["data"]:
142
+ yield item
143
+ if not page["nextCursor"]:
144
+ return
145
+ query["cursor"] = page["nextCursor"]
146
+
147
+ async def get(self, id: str) -> Email:
148
+ return cast(Email, await self._client._request("GET", f"/emails/{_seg(id)}"))
149
+
150
+ async def send(self, params: SendEmailParams) -> SentEmail:
151
+ """Send an email. Not idempotent: retrying after a timeout can send it twice."""
152
+ return cast(SentEmail, await self._client._request("POST", "/emails", body=params))
153
+
154
+ async def reply(self, id: str, params: ReplyParams) -> SentEmail:
155
+ """Reply to a received email. Recipients and threading come from the stored message."""
156
+ return cast(SentEmail, await self._client._request("POST", f"/emails/{_seg(id)}/reply", body=params))
157
+
158
+ async def delete(self, id: str) -> None:
159
+ await self._client._request("DELETE", f"/emails/{_seg(id)}")
160
+
161
+ async def retry(self, id: str) -> RetryResult:
162
+ """Retry this email's failed webhook deliveries."""
163
+ return cast(RetryResult, await self._client._request("POST", f"/emails/{_seg(id)}/retry"))
164
+
165
+ async def attachment_url(self, email_id: str, index: int) -> AttachmentUrl:
166
+ """A signed download URL for one attachment, valid for 15 minutes."""
167
+ return cast(
168
+ AttachmentUrl,
169
+ await self._client._request("GET", f"/emails/{_seg(email_id)}/attachments/{int(index)}"),
170
+ )
171
+
172
+ async def download_attachment(self, email_id: str, index: int) -> bytes:
173
+ """The attachment's bytes, streamed through the API."""
174
+ return cast(
175
+ bytes,
176
+ await self._client._request(
177
+ "GET",
178
+ f"/emails/{_seg(email_id)}/attachments/{int(index)}",
179
+ query={"download": "1"},
180
+ raw=True,
181
+ ),
182
+ )
183
+
184
+
185
+ class AsyncThreads(_AsyncResource):
186
+ async def get(self, id: str) -> Thread:
187
+ """Every message in a thread, oldest first."""
188
+ return cast(Thread, await self._client._request("GET", f"/threads/{_seg(id)}"))
189
+
190
+
191
+ class AsyncDomains(_AsyncResource):
192
+ async def list(self) -> List[Domain]:
193
+ return cast(List[Domain], await self._client._request("GET", "/domains"))
194
+
195
+ async def create(self, params: CreateDomainParams) -> DomainDetail:
196
+ """Register a domain. Publish the returned `dnsRecords`, then poll `get`."""
197
+ return cast(DomainDetail, await self._client._request("POST", "/domains", body=params))
198
+
199
+ async def get(self, id: str) -> DomainDetail:
200
+ """Fetch a domain and re-check its verification."""
201
+ return cast(DomainDetail, await self._client._request("GET", f"/domains/{_seg(id)}"))
202
+
203
+ async def update(self, id: str, params: UpdateDomainParams) -> UpdatedDomain:
204
+ """Set the catch-all endpoints. An empty list turns the catch-all off."""
205
+ return cast(UpdatedDomain, await self._client._request("PATCH", f"/domains/{_seg(id)}", body=params))
206
+
207
+ async def delete(self, id: str) -> None:
208
+ await self._client._request("DELETE", f"/domains/{_seg(id)}")
209
+
210
+
211
+ class AsyncAddresses(_AsyncResource):
212
+ async def list(self) -> List[Address]:
213
+ return cast(List[Address], await self._client._request("GET", "/addresses"))
214
+
215
+ async def create(self, params: CreateAddressParams) -> CreatedAddress:
216
+ """With no `endpointIds` the address is store-only."""
217
+ return cast(CreatedAddress, await self._client._request("POST", "/addresses", body=params))
218
+
219
+ async def get(self, id: str) -> Address:
220
+ return cast(Address, await self._client._request("GET", f"/addresses/{_seg(id)}"))
221
+
222
+ async def update(self, id: str, params: UpdateAddressParams) -> Address:
223
+ """`endpointIds` replaces the whole set; an empty list makes the address store-only."""
224
+ return cast(Address, await self._client._request("PATCH", f"/addresses/{_seg(id)}", body=params))
225
+
226
+ async def delete(self, id: str) -> None:
227
+ await self._client._request("DELETE", f"/addresses/{_seg(id)}")
228
+
229
+
230
+ class AsyncEndpoints(_AsyncResource):
231
+ async def list(self) -> List[Endpoint]:
232
+ return cast(List[Endpoint], await self._client._request("GET", "/endpoints"))
233
+
234
+ async def create(self, params: CreateEndpointParams) -> EndpointWithSecret:
235
+ """Create an endpoint. The response is the only time `secret` is returned."""
236
+ return cast(EndpointWithSecret, await self._client._request("POST", "/endpoints", body=params))
237
+
238
+ async def get(self, id: str) -> Endpoint:
239
+ return cast(Endpoint, await self._client._request("GET", f"/endpoints/{_seg(id)}"))
240
+
241
+ async def update(self, id: str, params: UpdateEndpointParams) -> Endpoint:
242
+ """A partial update: send only the fields you are changing."""
243
+ return cast(Endpoint, await self._client._request("PATCH", f"/endpoints/{_seg(id)}", body=params))
244
+
245
+ async def delete(self, id: str) -> None:
246
+ await self._client._request("DELETE", f"/endpoints/{_seg(id)}")
247
+
248
+ async def test(self, id: str) -> EndpointTestResult:
249
+ """Send a signed sample delivery and report the outcome."""
250
+ return cast(EndpointTestResult, await self._client._request("POST", f"/endpoints/{_seg(id)}/test"))
251
+
252
+ async def deliveries(self, id: str, params: ListDeliveriesParams | None = None) -> Page[Delivery]:
253
+ """One page of this endpoint's deliveries, newest first."""
254
+ return cast(
255
+ Page[Delivery],
256
+ await self._client._request("GET", f"/endpoints/{_seg(id)}/deliveries", query=params),
257
+ )
258
+
259
+ async def list_all_deliveries(
260
+ self, id: str, params: ListDeliveriesParams | None = None
261
+ ) -> AsyncIterator[Delivery]:
262
+ """Every matching delivery, newest first, fetching pages as you iterate."""
263
+ query: dict[str, Any] = dict(params or {})
264
+ while True:
265
+ page = await self.deliveries(id, cast(ListDeliveriesParams, query))
266
+ for item in page["data"]:
267
+ yield item
268
+ if not page["nextCursor"]:
269
+ return
270
+ query["cursor"] = page["nextCursor"]
271
+
272
+
273
+ class AsyncShieldRules(_AsyncResource):
274
+ async def list(self) -> List[ShieldRule]:
275
+ """Rules in evaluation order. The first match wins."""
276
+ return cast(List[ShieldRule], await self._client._request("GET", "/shield-rules"))
277
+
278
+ async def create(self, params: CreateShieldRuleParams) -> ShieldRule:
279
+ """Create a rule. It goes last in the order."""
280
+ return cast(ShieldRule, await self._client._request("POST", "/shield-rules", body=params))
281
+
282
+ async def get(self, id: str) -> ShieldRule:
283
+ return cast(ShieldRule, await self._client._request("GET", f"/shield-rules/{_seg(id)}"))
284
+
285
+ async def update(self, id: str, params: ReplaceShieldRuleParams | ShieldRule) -> ShieldRule:
286
+ """Replace a rule. A rule from `get` can be passed back with changes;
287
+ the API ignores its read-only fields (id, priority, scope, createdAt)::
288
+
289
+ rule = client.shield_rules.get(rule_id)
290
+ client.shield_rules.update(rule_id, {**rule, "enabled": False})
291
+ """
292
+ return cast(ShieldRule, await self._client._request("PUT", f"/shield-rules/{_seg(id)}", body=params))
293
+
294
+ async def delete(self, id: str) -> None:
295
+ await self._client._request("DELETE", f"/shield-rules/{_seg(id)}")
296
+
297
+ async def move(self, id: str, direction: Literal["up", "down"]) -> ShieldRuleOrder:
298
+ """Swap the rule with its neighbour. Returns the new order."""
299
+ return cast(
300
+ ShieldRuleOrder,
301
+ await self._client._request("POST", f"/shield-rules/{_seg(id)}/move", body={"direction": direction}),
302
+ )
303
+
304
+ async def reorder(self, order: Sequence[str]) -> ShieldRuleOrder:
305
+ """Set the whole order. `order` must name every rule exactly once."""
306
+ return cast(ShieldRuleOrder, await self._client._request("PUT", "/shield-rules", body={"order": [*order]}))
307
+
308
+
309
+ class AsyncSenders(_AsyncResource):
310
+ async def list(self) -> List[Sender]:
311
+ """Senders connected in the console."""
312
+ return cast(List[Sender], await self._client._request("GET", "/senders"))
313
+
314
+
315
+ class AsyncSuppressions(_AsyncResource):
316
+ async def list(self) -> List[Suppression]:
317
+ return cast(List[Suppression], await self._client._request("GET", "/suppressions"))
318
+
319
+ async def create(self, params: CreateSuppressionParams) -> SuppressedAddress:
320
+ return cast(SuppressedAddress, await self._client._request("POST", "/suppressions", body=params))
321
+
322
+ async def delete(self, address: str) -> None:
323
+ await self._client._request("DELETE", f"/suppressions/{_seg(address)}")
324
+
325
+
326
+ class AsyncForwardDestinations(_AsyncResource):
327
+ async def list(self) -> List[ForwardDestination]:
328
+ return cast(List[ForwardDestination], await self._client._request("GET", "/forward-destinations"))
329
+
330
+ async def create(self, params: CreateForwardDestinationParams) -> ForwardDestinationRequest:
331
+ """Ask an address to confirm it will accept forwarded mail."""
332
+ return cast(
333
+ ForwardDestinationRequest,
334
+ await self._client._request("POST", "/forward-destinations", body=params),
335
+ )
336
+
337
+ async def delete(self, address: str) -> None:
338
+ await self._client._request("DELETE", f"/forward-destinations/{_seg(address)}")
inboundr/_base.py ADDED
@@ -0,0 +1,97 @@
1
+ """Request building and response handling shared by the sync and async clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from typing import Any
8
+ from urllib.parse import quote
9
+
10
+ import httpx
11
+
12
+ from ._errors import InboundrAPIError, InboundrError, InboundrRateLimitError
13
+ from ._version import __version__
14
+
15
+ DEFAULT_BASE_URL = "https://inboundr.net"
16
+ API_KEY_ENV_VAR = "INBOUNDR_API_KEY"
17
+ DEFAULT_TIMEOUT = 30.0
18
+
19
+
20
+ def resolve_api_key(api_key: str | None) -> str:
21
+ key = api_key or os.environ.get(API_KEY_ENV_VAR)
22
+ if not key:
23
+ raise InboundrError(
24
+ f"No API key. Pass Inboundr(api_key=...) or set {API_KEY_ENV_VAR}. "
25
+ "Create a key in the console under API keys."
26
+ )
27
+ return key
28
+
29
+
30
+ def base_api_url(base_url: str) -> str:
31
+ return base_url.rstrip("/") + "/api/v1"
32
+
33
+
34
+ def default_headers(api_key: str) -> dict[str, str]:
35
+ return {
36
+ "authorization": f"Bearer {api_key}",
37
+ "accept": "application/json",
38
+ "user-agent": f"inboundr-python/{__version__}",
39
+ }
40
+
41
+
42
+ def segment(value: str | int) -> str:
43
+ """Percent-encode one path segment. Ids are safe; email addresses are not."""
44
+ return quote(str(value), safe="")
45
+
46
+
47
+ def clean_query(params: Any) -> dict[str, Any] | None:
48
+ if not params:
49
+ return None
50
+ return {k: v for k, v in dict(params).items() if v is not None}
51
+
52
+
53
+ def _message(status: int, body: Any) -> str:
54
+ if isinstance(body, dict) and "error" in body:
55
+ error = body["error"]
56
+ return error if isinstance(error, str) else f"{status} {json.dumps(error)}"
57
+ if isinstance(body, str) and body.strip():
58
+ return f"{status} {body}"
59
+ return f"Request failed with status {status}"
60
+
61
+
62
+ def handle_response(response: httpx.Response, *, raw: bool = False) -> Any:
63
+ request_id = response.headers.get("x-request-id")
64
+ if response.is_success:
65
+ if raw:
66
+ return response.content
67
+ if response.status_code == 204 or not response.content:
68
+ return None
69
+ try:
70
+ return response.json()
71
+ except ValueError:
72
+ return response.text
73
+
74
+ try:
75
+ body: Any = response.json()
76
+ except ValueError:
77
+ body = response.text
78
+
79
+ message = _message(response.status_code, body)
80
+ if response.status_code == 429:
81
+ header = response.headers.get("retry-after")
82
+ try:
83
+ retry_after: float | None = float(header) if header is not None else None
84
+ except ValueError:
85
+ retry_after = None
86
+ if retry_after is not None and retry_after < 0:
87
+ retry_after = None
88
+ raise InboundrRateLimitError(
89
+ message, status=429, body=body, request_id=request_id, retry_after_seconds=retry_after
90
+ )
91
+ raise InboundrAPIError(message, status=response.status_code, body=body, request_id=request_id)
92
+
93
+
94
+ def transport_error(method: str, path: str, exc: Exception, timeout: float | None) -> InboundrError:
95
+ if isinstance(exc, httpx.TimeoutException):
96
+ return InboundrError(f"{method} {path} timed out after {timeout}s.")
97
+ return InboundrError(f"{method} {path} failed: {exc}")