zapiack 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.
zapiack/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """The official Zapiack SDK for Python."""
2
+
3
+ from ._http import RequestOptions, TransportRequest, TransportResponse
4
+ from ._version import VERSION
5
+ from .client import Zapiack
6
+ from .errors import ZapiackConfigError, ZapiackConnectionError, ZapiackError, ZapiackSignatureError
7
+ from .pagination import Page, PageMeta
8
+ from .resources.base import UploadFile
9
+ from .webhooks import Webhooks
10
+
11
+ __version__ = VERSION
12
+
13
+ __all__ = [
14
+ "Page",
15
+ "PageMeta",
16
+ "RequestOptions",
17
+ "TransportRequest",
18
+ "TransportResponse",
19
+ "UploadFile",
20
+ "VERSION",
21
+ "Webhooks",
22
+ "Zapiack",
23
+ "ZapiackConfigError",
24
+ "ZapiackConnectionError",
25
+ "ZapiackError",
26
+ "ZapiackSignatureError",
27
+ ]
zapiack/_http.py ADDED
@@ -0,0 +1,214 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import platform
5
+ import random
6
+ import time
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+ import uuid
11
+ from dataclasses import dataclass, field
12
+ from email.utils import parsedate_to_datetime
13
+ from typing import Any, Callable, Dict, Mapping, Optional
14
+
15
+ from ._version import VERSION
16
+ from .errors import ZapiackConnectionError, ZapiackError, error_from_response
17
+
18
+ RETRYABLE = {408, 429, 500, 502, 503, 504}
19
+ MAX_RETRY_AFTER_SECONDS = 30
20
+ BASE_DELAY_SECONDS = 0.5
21
+ MAX_DELAY_SECONDS = 8.0
22
+
23
+
24
+ @dataclass
25
+ class RequestOptions:
26
+ """Per-call settings. Every resource method takes one as its last argument."""
27
+
28
+ #: Overrides the key generated for a send. Reuse the same key to make a repeated request safe.
29
+ idempotency_key: Optional[str] = None
30
+ #: Seconds, for this request only.
31
+ timeout: Optional[float] = None
32
+ #: Retries after the first attempt, for this request only.
33
+ max_retries: Optional[int] = None
34
+ headers: Dict[str, str] = field(default_factory=dict)
35
+
36
+
37
+ @dataclass
38
+ class Call:
39
+ method: str
40
+ path: str
41
+ query: Optional[Mapping[str, Any]] = None
42
+ body: Any = None
43
+ #: A file upload, sent as multipart/form-data instead of JSON: (field name, filename, bytes, mime type, extra fields).
44
+ form: Optional["Form"] = None
45
+ #: A send: gets an idempotency key automatically, which is what makes retrying it safe.
46
+ send: bool = False
47
+
48
+
49
+ @dataclass
50
+ class Form:
51
+ filename: str
52
+ content: bytes
53
+ mime_type: str = "application/octet-stream"
54
+ fields: Dict[str, str] = field(default_factory=dict)
55
+
56
+
57
+ @dataclass
58
+ class TransportRequest:
59
+ method: str
60
+ url: str
61
+ headers: Dict[str, str]
62
+ body: Optional[bytes]
63
+ timeout: float
64
+
65
+
66
+ @dataclass
67
+ class TransportResponse:
68
+ status: int
69
+ headers: Dict[str, str]
70
+ body: bytes
71
+
72
+
73
+ Transport = Callable[[TransportRequest], TransportResponse]
74
+
75
+
76
+ def urllib_transport(request: TransportRequest) -> TransportResponse:
77
+ """The default transport: the standard library, so the SDK has no dependencies. Raises OSError (or TimeoutError) when the network fails."""
78
+ req = urllib.request.Request(request.url, data=request.body, method=request.method, headers=request.headers)
79
+ try:
80
+ with urllib.request.urlopen(req, timeout=request.timeout) as response: # noqa: S310 - the URL is the configured API address
81
+ return TransportResponse(response.status, {k.lower(): v for k, v in response.headers.items()}, response.read())
82
+ except urllib.error.HTTPError as error:
83
+ return TransportResponse(error.code, {k.lower(): v for k, v in error.headers.items()}, error.read())
84
+
85
+
86
+ def parse_retry_after(value: Optional[str], now: Optional[float] = None) -> Optional[float]:
87
+ if not value:
88
+ return None
89
+ try:
90
+ return max(0.0, float(value))
91
+ except ValueError:
92
+ pass
93
+ try:
94
+ when = parsedate_to_datetime(value).timestamp()
95
+ except (TypeError, ValueError):
96
+ return None
97
+ return max(0.0, when - (time.time() if now is None else now))
98
+
99
+
100
+ def backoff_seconds(attempt: int, retry_after: Optional[float] = None, rand: Callable[[], float] = random.random) -> float:
101
+ """Waits before attempt `attempt + 1`: half a second, doubling, with jitter; the API's own request to wait is a floor."""
102
+ base = min(BASE_DELAY_SECONDS * 2**attempt, MAX_DELAY_SECONDS)
103
+ jittered = base * (0.75 + rand() * 0.5)
104
+ return max(jittered, retry_after or 0.0)
105
+
106
+
107
+ def _multipart(form: Form) -> "tuple[bytes, str]":
108
+ boundary = "zapiack" + uuid.uuid4().hex
109
+ chunks = []
110
+ for key, value in form.fields.items():
111
+ chunks.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n{value}\r\n'.encode())
112
+ safe = form.filename.replace('"', "").replace("\r", "").replace("\n", "")
113
+ chunks.append(f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{safe}"\r\nContent-Type: {form.mime_type}\r\n\r\n'.encode())
114
+ chunks.append(form.content)
115
+ chunks.append(f"\r\n--{boundary}--\r\n".encode())
116
+ return b"".join(chunks), f"multipart/form-data; boundary={boundary}"
117
+
118
+
119
+ def build_url(base_url: str, path: str, query: Optional[Mapping[str, Any]] = None) -> str:
120
+ url = f"{base_url.rstrip('/')}/{path.lstrip('/')}"
121
+ pairs = []
122
+ for key, value in (query or {}).items():
123
+ if value is None or value == "":
124
+ continue
125
+ if isinstance(value, bool):
126
+ value = "true" if value else "false"
127
+ pairs.append((key, str(value)))
128
+ return f"{url}?{urllib.parse.urlencode(pairs)}" if pairs else url
129
+
130
+
131
+ class HttpClient:
132
+ def __init__(
133
+ self,
134
+ *,
135
+ api_key: str,
136
+ base_url: str,
137
+ timeout: float,
138
+ max_retries: int,
139
+ transport: Transport,
140
+ app_info: Optional[str] = None,
141
+ sleep: Callable[[float], None] = time.sleep,
142
+ ) -> None:
143
+ self.api_key = api_key
144
+ self.base_url = base_url
145
+ self.timeout = timeout
146
+ self.max_retries = max_retries
147
+ self.transport = transport
148
+ self.app_info = app_info
149
+ self.sleep = sleep
150
+
151
+ def _user_agent(self) -> str:
152
+ return f"zapiack-python/{VERSION} python/{platform.python_version()}" + (f" {self.app_info}" if self.app_info else "")
153
+
154
+ def request(self, call: Call, options: Optional[RequestOptions] = None) -> Any:
155
+ options = options or RequestOptions()
156
+ request_id = str(uuid.uuid4())
157
+ idempotency_key = (options.idempotency_key or str(uuid.uuid4())) if call.send else options.idempotency_key
158
+ # Repeating a request is only safe when it cannot happen twice: a read, or a send carrying an idempotency key.
159
+ safe_to_repeat = call.method in ("GET", "DELETE") or idempotency_key is not None
160
+ max_retries = (self.max_retries if options.max_retries is None else options.max_retries) if safe_to_repeat else 0
161
+ timeout = self.timeout if options.timeout is None else options.timeout
162
+ url = build_url(self.base_url, call.path, call.query)
163
+
164
+ headers: Dict[str, str] = {
165
+ "Authorization": f"Bearer {self.api_key}",
166
+ "Accept": "application/json",
167
+ "User-Agent": self._user_agent(),
168
+ "X-Request-Id": request_id,
169
+ }
170
+ body: Optional[bytes] = None
171
+ if call.form is not None:
172
+ body, headers["Content-Type"] = _multipart(call.form)
173
+ elif call.body is not None:
174
+ body = json.dumps(call.body).encode()
175
+ headers["Content-Type"] = "application/json"
176
+ if idempotency_key:
177
+ headers["Idempotency-Key"] = idempotency_key
178
+ headers.update(options.headers)
179
+
180
+ attempt = 0
181
+ while True:
182
+ try:
183
+ response = self.transport(TransportRequest(call.method, url, headers, body, timeout))
184
+ except ZapiackError:
185
+ raise
186
+ except (OSError, TimeoutError) as error:
187
+ timed_out = isinstance(error, TimeoutError) or "timed out" in str(error).lower()
188
+ if attempt < max_retries:
189
+ self.sleep(backoff_seconds(attempt))
190
+ attempt += 1
191
+ continue
192
+ raise ZapiackConnectionError(
193
+ f"The request timed out after {timeout:g} s" if timed_out else "The request could not reach Zapiack",
194
+ code="timeout" if timed_out else "connection_error",
195
+ request_id=request_id,
196
+ ) from error
197
+
198
+ text = response.body.decode("utf-8", errors="replace")
199
+ try:
200
+ parsed = json.loads(text) if text else None
201
+ except ValueError:
202
+ parsed = None
203
+
204
+ if 200 <= response.status < 300:
205
+ return parsed
206
+
207
+ retry_after = parse_retry_after(response.headers.get("retry-after"))
208
+ error_obj = error_from_response(response.status, parsed, response.headers.get("x-request-id") or request_id, retry_after)
209
+ may_wait = retry_after is None or retry_after <= MAX_RETRY_AFTER_SECONDS
210
+ if attempt < max_retries and response.status in RETRYABLE and may_wait:
211
+ self.sleep(backoff_seconds(attempt, retry_after))
212
+ attempt += 1
213
+ continue
214
+ raise error_obj
zapiack/_version.py ADDED
@@ -0,0 +1 @@
1
+ VERSION = "0.1.0"
zapiack/client.py ADDED
@@ -0,0 +1,56 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from typing import Callable, Optional
5
+
6
+ from ._http import HttpClient, Transport, urllib_transport
7
+ from .errors import ZapiackConfigError
8
+ from .resources.email import Email
9
+ from .resources.push import Push
10
+ from .resources.sms import Sms
11
+ from .resources.whatsapp import Whatsapp
12
+ from .webhooks import Webhooks
13
+
14
+ DEFAULT_BASE_URL = "https://api.zapiack.com/v1"
15
+
16
+
17
+ class Zapiack:
18
+ """The Zapiack client. Create one and reuse it.
19
+
20
+ >>> zapiack = Zapiack("zpk_...")
21
+ >>> zapiack.sms.send({"phone": "+2348012345678", "country": "NG", "message": "Hello"})
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ api_key: Optional[str] = None,
27
+ *,
28
+ base_url: str = DEFAULT_BASE_URL,
29
+ timeout: float = 30.0,
30
+ max_retries: int = 2,
31
+ app_info: Optional[str] = None,
32
+ transport: Optional[Transport] = None,
33
+ sleep: Optional[Callable[[float], None]] = None,
34
+ ) -> None:
35
+ key = api_key or os.environ.get("ZAPIACK_API_KEY")
36
+ if not key:
37
+ raise ZapiackConfigError("No API key. Pass it as the first argument or set ZAPIACK_API_KEY.")
38
+ if key.startswith("pk_"):
39
+ raise ZapiackConfigError("That is a public app key, which belongs inside an app. This client needs your secret API key.")
40
+
41
+ import time
42
+
43
+ http = HttpClient(
44
+ api_key=key,
45
+ base_url=base_url,
46
+ timeout=timeout,
47
+ max_retries=max_retries,
48
+ transport=transport or urllib_transport,
49
+ app_info=app_info,
50
+ sleep=sleep or time.sleep,
51
+ )
52
+ self.email = Email(http)
53
+ self.sms = Sms(http)
54
+ self.whatsapp = Whatsapp(http)
55
+ self.push = Push(http)
56
+ self.webhooks = Webhooks()
zapiack/errors.py ADDED
@@ -0,0 +1,105 @@
1
+ """Every failure is a ZapiackError with a stable `code`, the HTTP `status` and a `request_id`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any, Optional
7
+
8
+
9
+ class ZapiackError(Exception):
10
+ """Raised for every failed request.
11
+
12
+ `code` is stable and the same in every Zapiack SDK, `status` is the HTTP status (0 when no response was received), and
13
+ `request_id` identifies the request when you contact support.
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ message: str,
19
+ *,
20
+ status: int,
21
+ code: str,
22
+ request_id: 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.status = status
29
+ self.code = code
30
+ self.request_id = request_id
31
+ #: What the API said about each field that was wrong, when it said.
32
+ self.details = details
33
+ #: Seconds to wait before trying again, when the API asked for a pause.
34
+ self.retry_after = retry_after
35
+
36
+
37
+ class ZapiackConnectionError(ZapiackError):
38
+ """No response was received: the network failed or the request timed out."""
39
+
40
+ def __init__(self, message: str, *, code: str = "connection_error", request_id: Optional[str] = None) -> None:
41
+ super().__init__(message, status=0, code=code, request_id=request_id)
42
+
43
+
44
+ class ZapiackSignatureError(ZapiackError):
45
+ """A webhook did not carry a valid signature."""
46
+
47
+ def __init__(self, message: str) -> None:
48
+ super().__init__(message, status=400, code="invalid_signature")
49
+
50
+
51
+ class ZapiackConfigError(Exception):
52
+ """The client was set up wrongly, for example with no key or with a key that must not be used here."""
53
+
54
+
55
+ _BY_STATUS = {
56
+ 400: "invalid_request",
57
+ 401: "authentication_failed",
58
+ 402: "insufficient_balance",
59
+ 403: "permission_denied",
60
+ 404: "not_found",
61
+ 409: "conflict",
62
+ 422: "unprocessable",
63
+ 429: "rate_limited",
64
+ }
65
+
66
+ _GENERIC = re.compile(
67
+ r"^(bad request|unauthorized|forbidden|not found|conflict|unprocessable entity|too many requests|internal server error|"
68
+ r"payment required|service unavailable|bad gateway|gateway timeout)$",
69
+ re.IGNORECASE,
70
+ )
71
+ _NAME = re.compile(r"^[A-Za-z]+(?:[_ -]?[A-Za-z]+)*$")
72
+
73
+
74
+ def _snake(value: str) -> str:
75
+ value = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", value)
76
+ return re.sub(r"[\s-]+", "_", value).lower()
77
+
78
+
79
+ def _code_for(status: int, body: Any) -> str:
80
+ """A code the API chose itself (`credential_invalid`, `OverageCapReached`) is kept; a generic status name is replaced."""
81
+ named = body.get("error") if isinstance(body, dict) else None
82
+ if isinstance(named, str) and _NAME.match(named) and not _GENERIC.match(named):
83
+ return _snake(named)
84
+ if status >= 500:
85
+ return "server_error"
86
+ return _BY_STATUS.get(status, "invalid_request")
87
+
88
+
89
+ def _message_for(status: int, body: Any) -> "tuple[str, Any]":
90
+ if isinstance(body, dict):
91
+ message = body.get("message")
92
+ errors = body.get("errors")
93
+ details = errors if isinstance(errors, list) else message if isinstance(message, list) else None
94
+ if isinstance(message, str) and message:
95
+ return message, details
96
+ if isinstance(message, list) and message:
97
+ return "; ".join(str(m) for m in message), details
98
+ if isinstance(errors, list) and errors:
99
+ return "; ".join(str(e) for e in errors), details
100
+ return f"The request failed with status {status}", None
101
+
102
+
103
+ def error_from_response(status: int, body: Any, request_id: Optional[str], retry_after: Optional[float] = None) -> ZapiackError:
104
+ message, details = _message_for(status, body)
105
+ return ZapiackError(message, status=status, code=_code_for(status, body), request_id=request_id, details=details, retry_after=retry_after)
zapiack/pagination.py ADDED
@@ -0,0 +1,56 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Callable, Generic, Iterator, List, Mapping, Optional, TypeVar
5
+
6
+ T = TypeVar("T")
7
+
8
+
9
+ @dataclass
10
+ class PageMeta:
11
+ total: int
12
+ page: int
13
+ page_size: int
14
+ total_pages: int
15
+
16
+
17
+ def to_meta(raw: Optional[Mapping[str, Any]], count: int) -> PageMeta:
18
+ """Turns either list shape the API uses (`limit` or `pageSize`) into one."""
19
+ raw = raw or {}
20
+ total = raw.get("total", count)
21
+ page_size = raw.get("pageSize") or raw.get("limit") or (count or 1)
22
+ total_pages = raw.get("totalPages") or max(1, -(-total // page_size)) or 1
23
+ return PageMeta(total=total, page=raw.get("page", 1), page_size=page_size, total_pages=total_pages)
24
+
25
+
26
+ class Page(Generic[T]):
27
+ """One page of results.
28
+
29
+ `data` is this page's items. Iterating the page walks **every** item on **every** page, fetching the next page when it is
30
+ needed, so `for contact in client.email.contacts.list(): ...` visits all of them.
31
+ """
32
+
33
+ def __init__(self, data: List[T], meta: PageMeta, fetch_page: Callable[[int], "Page[T]"]) -> None:
34
+ self.data = data
35
+ self.meta = meta
36
+ self._fetch_page = fetch_page
37
+
38
+ def has_next_page(self) -> bool:
39
+ return self.meta.page < self.meta.total_pages
40
+
41
+ def next_page(self) -> "Page[T]":
42
+ if not self.has_next_page():
43
+ raise IndexError("There is no next page")
44
+ return self._fetch_page(self.meta.page + 1)
45
+
46
+ def iter_pages(self) -> Iterator["Page[T]"]:
47
+ page: Page[T] = self
48
+ while True:
49
+ yield page
50
+ if not page.has_next_page():
51
+ return
52
+ page = page.next_page()
53
+
54
+ def __iter__(self) -> Iterator[T]:
55
+ for page in self.iter_pages():
56
+ yield from page.data
zapiack/py.typed ADDED
File without changes
File without changes
@@ -0,0 +1,47 @@
1
+ from __future__ import annotations
2
+
3
+ import urllib.parse
4
+ from dataclasses import dataclass
5
+ from typing import Any, Callable, Dict, Mapping, Optional, Union
6
+
7
+ from .._http import Call, Form, HttpClient, RequestOptions
8
+ from ..pagination import Page, to_meta
9
+
10
+ Params = Mapping[str, Any]
11
+ Options = Optional[RequestOptions]
12
+
13
+
14
+ def quote(value: str) -> str:
15
+ """An id placed in a path: nothing in it can change where the request goes."""
16
+ return urllib.parse.quote(str(value), safe="")
17
+
18
+
19
+ @dataclass
20
+ class UploadFile:
21
+ """A file to upload: its bytes, the name to send it under, and its type (for example `image/png`)."""
22
+
23
+ content: bytes
24
+ filename: str
25
+ mime_type: str = "application/octet-stream"
26
+
27
+ def to_form(self, fields: Optional[Dict[str, Optional[str]]] = None) -> Form:
28
+ return Form(self.filename, bytes(self.content), self.mime_type, {k: v for k, v in (fields or {}).items() if v is not None})
29
+
30
+
31
+ class Resource:
32
+ def __init__(self, http: HttpClient) -> None:
33
+ self._http = http
34
+
35
+ def _call(self, method: str, path: str, *, query: Optional[Mapping[str, Any]] = None, body: Any = None, send: bool = False, form: Optional[Form] = None, options: Options = None) -> Any:
36
+ return self._http.request(Call(method=method, path=path, query=query, body=body, send=send, form=form), options)
37
+
38
+ def _paged(self, path: str, key: str, params: Optional[Params], options: Options, extra_query: Optional[Mapping[str, Any]] = None) -> Page:
39
+ """A list call: the first page now, and the rest as the page is iterated."""
40
+ params = dict(params or {})
41
+
42
+ def fetch(page: int) -> Page:
43
+ res = self._call("GET", path, query={**params, **(extra_query or {}), "page": page}, options=options)
44
+ items = res[key]
45
+ return Page(items, to_meta(res.get("meta"), len(items)), fetch)
46
+
47
+ return fetch(int(params.get("page", 1)))
@@ -0,0 +1,159 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ from ..pagination import Page
7
+ from .base import Options, Params, Resource, UploadFile, quote
8
+
9
+
10
+ def _to_base64(content: Any) -> str:
11
+ return content if isinstance(content, str) else base64.b64encode(bytes(content)).decode()
12
+
13
+
14
+ def _email_body(params: Params) -> Dict[str, Any]:
15
+ body = dict(params)
16
+ to = body.get("to")
17
+ body["to"] = list(to) if isinstance(to, (list, tuple)) else [to]
18
+ if body.get("attachments"):
19
+ body["attachments"] = [{"filename": a["filename"], "content": _to_base64(a["content"])} for a in body["attachments"]]
20
+ return body
21
+
22
+
23
+ class Contacts(Resource):
24
+ def list(self, params: Optional[Params] = None, options: Options = None) -> Page:
25
+ """Contacts, newest first. Filters: search, email, status, segmentId, sortBy, sortOrder, limit."""
26
+ return self._paged("email/contacts", "data", params, options)
27
+
28
+ def create(self, params: Params, options: Options = None) -> Any:
29
+ return self._call("POST", "email/contacts", body=params, options=options)
30
+
31
+ def create_many(self, params: Params, options: Options = None) -> Any:
32
+ return self._call("POST", "email/contacts/batch", body=params, options=options)
33
+
34
+ def get(self, id: str, options: Options = None) -> Any:
35
+ return self._call("GET", f"email/contacts/{quote(id)}", options=options)
36
+
37
+ def update(self, id: str, params: Params, options: Options = None) -> Any:
38
+ return self._call("PATCH", f"email/contacts/{quote(id)}", body=params, options=options)
39
+
40
+ def remove(self, id: str, options: Options = None) -> None:
41
+ self._call("DELETE", f"email/contacts/{quote(id)}", options=options)
42
+
43
+ def unsubscribe(self, id: str, options: Options = None) -> Any:
44
+ return self._call("POST", f"email/contacts/{quote(id)}/unsubscribe", options=options)
45
+
46
+ def resubscribe(self, id: str, options: Options = None) -> Any:
47
+ return self._call("POST", f"email/contacts/{quote(id)}/resubscribe", options=options)
48
+
49
+
50
+ class Segments(Resource):
51
+ def list(self, options: Options = None) -> List[Any]:
52
+ return self._call("GET", "email/segments", options=options)
53
+
54
+ def create(self, params: Params, options: Options = None) -> Any:
55
+ return self._call("POST", "email/segments", body=params, options=options)
56
+
57
+ def get(self, id: str, options: Options = None) -> Any:
58
+ return self._call("GET", f"email/segments/{quote(id)}", options=options)
59
+
60
+ def update(self, id: str, params: Params, options: Options = None) -> Any:
61
+ return self._call("PATCH", f"email/segments/{quote(id)}", body=params, options=options)
62
+
63
+ def remove(self, id: str, options: Options = None) -> None:
64
+ self._call("DELETE", f"email/segments/{quote(id)}", options=options)
65
+
66
+ def add_contacts(self, id: str, contact_ids: List[str], options: Options = None) -> Any:
67
+ return self._call("POST", f"email/segments/{quote(id)}/contacts", body={"contactIds": contact_ids}, options=options)
68
+
69
+ def remove_contacts(self, id: str, contact_ids: List[str], options: Options = None) -> Any:
70
+ return self._call("DELETE", f"email/segments/{quote(id)}/contacts", body={"contactIds": contact_ids}, options=options)
71
+
72
+
73
+ class Templates(Resource):
74
+ def list(self, options: Options = None) -> Any:
75
+ return self._call("GET", "email/templates", options=options)
76
+
77
+ def get(self, id: str, options: Options = None) -> Any:
78
+ return self._call("GET", f"email/templates/{quote(id)}", options=options)
79
+
80
+ def create(self, params: Params, options: Options = None) -> Any:
81
+ return self._call("POST", "email/templates", body=params, options=options)
82
+
83
+ def update(self, id: str, params: Params, options: Options = None) -> Any:
84
+ return self._call("PATCH", f"email/templates/{quote(id)}", body=params, options=options)
85
+
86
+ def replace_content(self, id: str, html: str, options: Options = None) -> Any:
87
+ return self._call("PUT", f"email/templates/{quote(id)}/content", body={"html": html}, options=options)
88
+
89
+ def duplicate(self, id: str, params: Optional[Params] = None, options: Options = None) -> Any:
90
+ return self._call("POST", f"email/templates/{quote(id)}/duplicate", body=dict(params or {}), options=options)
91
+
92
+ def submit(self, id: str, options: Options = None) -> Any:
93
+ return self._call("POST", f"email/templates/{quote(id)}/submit", options=options)
94
+
95
+ def remove(self, id: str, options: Options = None) -> None:
96
+ self._call("DELETE", f"email/templates/{quote(id)}", options=options)
97
+
98
+ def list_assets(self, id: str, options: Options = None) -> Any:
99
+ """The images a template uses."""
100
+ return self._call("GET", f"email/templates/{quote(id)}/assets", options=options)
101
+
102
+ def upload_asset(self, id: str, file: UploadFile, name: Optional[str] = None, options: Options = None) -> Any:
103
+ """Uploads an image (PNG, JPEG, GIF or WebP, up to 5 MB) for a template to use."""
104
+ return self._call("POST", f"email/templates/{quote(id)}/assets", form=file.to_form({"name": name}), options=options)
105
+
106
+ def add_asset_url(self, id: str, params: Params, options: Options = None) -> Any:
107
+ """Links an image that is already online."""
108
+ return self._call("POST", f"email/templates/{quote(id)}/assets/url", body=params, options=options)
109
+
110
+ def remove_asset(self, id: str, asset_id: str, options: Options = None) -> None:
111
+ self._call("DELETE", f"email/templates/{quote(id)}/assets/{quote(asset_id)}", options=options)
112
+
113
+
114
+ class Domains(Resource):
115
+ def add(self, domain: str, options: Options = None) -> Any:
116
+ """Registers a sending domain and returns the DNS records to publish."""
117
+ return self._call("POST", "email/domains", body={"domain": domain}, options=options)
118
+
119
+ def list(self, options: Options = None) -> List[Any]:
120
+ return self._call("GET", "email/domains", options=options)
121
+
122
+ def get(self, id: str, options: Options = None) -> Any:
123
+ return self._call("GET", f"email/domains/{quote(id)}", options=options)
124
+
125
+ def verify(self, id: str, options: Options = None) -> Any:
126
+ return self._call("POST", f"email/domains/{quote(id)}/verify", options=options)
127
+
128
+ def remove(self, id: str, options: Options = None) -> None:
129
+ self._call("DELETE", f"email/domains/{quote(id)}", options=options)
130
+
131
+
132
+ class Email(Resource):
133
+ def __init__(self, http: Any) -> None:
134
+ super().__init__(http)
135
+ self.contacts = Contacts(http)
136
+ self.segments = Segments(http)
137
+ self.templates = Templates(http)
138
+ self.domains = Domains(http)
139
+
140
+ def send(self, params: Params, options: Options = None) -> Any:
141
+ """Sends one email. Repeating the call with the same `idempotency_key` never sends it twice.
142
+
143
+ `to` is one address or a list; an attachment's `content` is bytes or the same base64-encoded.
144
+ """
145
+ return self._call("POST", "email/send", body=_email_body(params), send=True, options=options)
146
+
147
+ def send_batch(self, emails: List[Params], options: Options = None) -> Any:
148
+ """Sends up to 100 emails in one request. One failing does not stop the others: read `results`."""
149
+ return self._call("POST", "email/batch", body={"emails": [_email_body(e) for e in emails]}, send=True, options=options)
150
+
151
+ def get(self, id: str, options: Options = None) -> Any:
152
+ return self._call("GET", f"email/{quote(id)}", options=options)
153
+
154
+ def retry(self, id: str, options: Options = None) -> Any:
155
+ return self._call("POST", f"email/{quote(id)}/retry", send=True, options=options)
156
+
157
+ def suppressions(self, options: Options = None) -> Any:
158
+ """Addresses Zapiack will not send to: bounces, complaints and unsubscribes."""
159
+ return self._call("GET", "email/suppressions", options=options)