zapiack 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.
- zapiack-0.1.0/LICENSE +21 -0
- zapiack-0.1.0/PKG-INFO +185 -0
- zapiack-0.1.0/README.md +160 -0
- zapiack-0.1.0/pyproject.toml +37 -0
- zapiack-0.1.0/setup.cfg +4 -0
- zapiack-0.1.0/src/zapiack/__init__.py +27 -0
- zapiack-0.1.0/src/zapiack/_http.py +214 -0
- zapiack-0.1.0/src/zapiack/_version.py +1 -0
- zapiack-0.1.0/src/zapiack/client.py +56 -0
- zapiack-0.1.0/src/zapiack/errors.py +105 -0
- zapiack-0.1.0/src/zapiack/pagination.py +56 -0
- zapiack-0.1.0/src/zapiack/py.typed +0 -0
- zapiack-0.1.0/src/zapiack/resources/__init__.py +0 -0
- zapiack-0.1.0/src/zapiack/resources/base.py +47 -0
- zapiack-0.1.0/src/zapiack/resources/email.py +159 -0
- zapiack-0.1.0/src/zapiack/resources/push.py +194 -0
- zapiack-0.1.0/src/zapiack/resources/sms.py +16 -0
- zapiack-0.1.0/src/zapiack/resources/whatsapp.py +176 -0
- zapiack-0.1.0/src/zapiack/webhooks.py +64 -0
- zapiack-0.1.0/src/zapiack.egg-info/PKG-INFO +185 -0
- zapiack-0.1.0/src/zapiack.egg-info/SOURCES.txt +24 -0
- zapiack-0.1.0/src/zapiack.egg-info/dependency_links.txt +1 -0
- zapiack-0.1.0/src/zapiack.egg-info/top_level.txt +1 -0
- zapiack-0.1.0/tests/test_http.py +176 -0
- zapiack-0.1.0/tests/test_routes.py +187 -0
- zapiack-0.1.0/tests/test_webhooks_pages.py +102 -0
zapiack-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Zapiack
|
|
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.
|
zapiack-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: zapiack
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The official Zapiack SDK for Python: email, SMS and push notifications from one client.
|
|
5
|
+
Author-email: Zapiack <support@zapiack.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://zapiack.com
|
|
8
|
+
Project-URL: Documentation, https://docs.zapiack.com/introduction
|
|
9
|
+
Project-URL: Source, https://github.com/zapiack-hq/zapiack-python
|
|
10
|
+
Project-URL: Issues, https://github.com/zapiack-hq/zapiack-python/issues
|
|
11
|
+
Keywords: zapiack,email,sms,push,notifications,sdk
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# zapiack (Python)
|
|
27
|
+
|
|
28
|
+
The official Zapiack SDK for Python. Send email, SMS and push notifications from one client.
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install zapiack
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Python 3.9 or later. No dependencies.
|
|
35
|
+
|
|
36
|
+
## Quickstart
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
import os
|
|
40
|
+
from zapiack import Zapiack
|
|
41
|
+
|
|
42
|
+
zapiack = Zapiack(os.environ["ZAPIACK_API_KEY"])
|
|
43
|
+
|
|
44
|
+
zapiack.email.send({
|
|
45
|
+
"from": "orders@myshop.com",
|
|
46
|
+
"to": "ada@example.com",
|
|
47
|
+
"subject": "Your order has shipped",
|
|
48
|
+
"html": "<p>It is on its way.</p>",
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
zapiack.sms.send({"phone": "+2348012345678", "country": "NG", "message": "Your order has shipped"})
|
|
52
|
+
|
|
53
|
+
zapiack.push.send({
|
|
54
|
+
"target": {"externalUserIds": ["user_123"]},
|
|
55
|
+
"title": "Your order has shipped",
|
|
56
|
+
"body": "Tap to track it",
|
|
57
|
+
"link": {"app": "myshop://orders/ord_789"},
|
|
58
|
+
})
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Create a secret API key in the dashboard under **Project → API Keys**. Keep it on your server: the client refuses a public app key.
|
|
62
|
+
The key can also come from the `ZAPIACK_API_KEY` environment variable: `Zapiack()`.
|
|
63
|
+
|
|
64
|
+
Parameters and answers are plain dictionaries, with the same names as the REST API and every other Zapiack SDK.
|
|
65
|
+
|
|
66
|
+
## What it does for you
|
|
67
|
+
|
|
68
|
+
- **Safe retries.** A failed request is retried up to twice, with backoff, on network errors, `429` and `5xx`, honouring
|
|
69
|
+
`Retry-After`. Only requests that cannot happen twice are retried: reads, and sends, which carry an idempotency key.
|
|
70
|
+
- **Idempotent sends.** Every send gets an `Idempotency-Key` automatically, so a retried send never goes out twice. Pass your own
|
|
71
|
+
to make a repeat from your code safe too: `zapiack.sms.send(params, RequestOptions(idempotency_key="order-42"))`.
|
|
72
|
+
- **Typed errors.** Every failure is a `ZapiackError` with a stable `code`, the HTTP `status` and a `request_id`.
|
|
73
|
+
- **Timeouts.** 30 seconds by default, per client or per call.
|
|
74
|
+
- **Pagination.** List calls return the first page; iterate it to walk every page.
|
|
75
|
+
- **Webhook verification.** One call checks the signature and reads the body.
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
from zapiack import Zapiack, RequestOptions
|
|
79
|
+
|
|
80
|
+
zapiack = Zapiack("zpk_...", timeout=10, max_retries=3, app_info="my-app/1.4.0")
|
|
81
|
+
zapiack.sms.send(params, RequestOptions(idempotency_key="order-42", timeout=5))
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Email
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
zapiack.email.send({"from": f, "to": ["a@x.com", "b@x.com"], "templateId": "tpl_1", "variables": {"name": "Ada"}})
|
|
88
|
+
zapiack.email.send_batch([{"from": f, "to": "a@x.com", "subject": s, "html": h}, ...])
|
|
89
|
+
status = zapiack.email.get(email_id)
|
|
90
|
+
|
|
91
|
+
zapiack.email.contacts.create({"email": "ada@example.com", "firstName": "Ada"})
|
|
92
|
+
for contact in zapiack.email.contacts.list({"status": "SUBSCRIBED"}): # every contact, on every page
|
|
93
|
+
print(contact["email"])
|
|
94
|
+
|
|
95
|
+
zapiack.email.domains.add("myshop.com")
|
|
96
|
+
zapiack.email.templates.upload_asset(template_id, UploadFile(logo_bytes, "logo.png", "image/png"))
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Attachments take bytes or base64: `"attachments": [{"filename": "invoice.pdf", "content": pdf_bytes}]`.
|
|
100
|
+
|
|
101
|
+
## SMS
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
zapiack.sms.send({"phone": "+2348012345678", "country": "NG", "message": "Hello"})
|
|
105
|
+
zapiack.sms.send_batch([{"phone": p, "country": "NG", "message": m}, ...])
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Push notifications
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
sent = zapiack.push.send({
|
|
112
|
+
"target": {"tags": {"plan": "pro"}},
|
|
113
|
+
"title": "New in Pro",
|
|
114
|
+
"body": "See what is new",
|
|
115
|
+
"image": "https://cdn.myshop.com/launch.jpg",
|
|
116
|
+
"actions": [{"id": "open", "title": "Open", "event": "launch_opened", "link": {"app": "myshop://launch"}}],
|
|
117
|
+
"tracking": {"windowMinutes": 60, "screens": True, "goal": "upgrade_completed"},
|
|
118
|
+
"scheduledAt": datetime(2026, 12, 1, 9, tzinfo=timezone.utc),
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
zapiack.push.messages.reschedule(sent["messageId"], "2026-12-02T09:00:00+01:00")
|
|
122
|
+
zapiack.push.messages.cancel(sent["messageId"])
|
|
123
|
+
funnel = zapiack.push.messages.funnel(sent["messageId"])
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
A scheduled push works out who it reaches when its time comes. It can be cancelled or moved while it is still scheduled, and not
|
|
127
|
+
after it has started going out. Device-side registration and click tracking are done by the client SDKs inside your app.
|
|
128
|
+
|
|
129
|
+
## Webhooks
|
|
130
|
+
|
|
131
|
+
Pass the **raw** request body, the `Zapiack-Signature` header and your endpoint's signing secret:
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from flask import Flask, request
|
|
135
|
+
from zapiack import ZapiackSignatureError
|
|
136
|
+
|
|
137
|
+
@app.post("/zapiack")
|
|
138
|
+
def hook():
|
|
139
|
+
try:
|
|
140
|
+
payload = zapiack.webhooks.verify(request.get_data(), request.headers.get("Zapiack-Signature"), os.environ["ZAPIACK_WEBHOOK_SECRET"])
|
|
141
|
+
except ZapiackSignatureError:
|
|
142
|
+
return "", 400
|
|
143
|
+
for event in payload["events"]:
|
|
144
|
+
if event["type"] == "push.clicked":
|
|
145
|
+
print(event["externalUserId"], event["messageId"])
|
|
146
|
+
return "", 204
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`verify` raises `ZapiackSignatureError` when the signature is missing, wrong, or older than five minutes. Return any `2xx` to
|
|
150
|
+
acknowledge; otherwise the delivery is retried for up to a day.
|
|
151
|
+
|
|
152
|
+
## Errors
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
from zapiack import ZapiackError
|
|
156
|
+
|
|
157
|
+
try:
|
|
158
|
+
zapiack.sms.send(params)
|
|
159
|
+
except ZapiackError as error:
|
|
160
|
+
print(error.code, error.status, error.request_id, error.details)
|
|
161
|
+
if error.code == "insufficient_balance": ...
|
|
162
|
+
if error.code == "rate_limited": time.sleep(error.retry_after or 1)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
| `code` | When |
|
|
166
|
+
|---|---|
|
|
167
|
+
| `invalid_request` | The request was wrong. `details` lists what, when the API says |
|
|
168
|
+
| `authentication_failed` | The key is missing or not valid |
|
|
169
|
+
| `insufficient_balance` | The wallet cannot cover the send |
|
|
170
|
+
| `permission_denied` | The key may not do this |
|
|
171
|
+
| `not_found` | There is no such thing |
|
|
172
|
+
| `conflict` | It clashes with what is already there |
|
|
173
|
+
| `unprocessable` | The request was understood and refused |
|
|
174
|
+
| `rate_limited` | Too many requests. `retry_after` says how long to wait |
|
|
175
|
+
| `server_error` | Zapiack failed. Retried for you, then raised |
|
|
176
|
+
| `connection_error`, `timeout` | No answer was received |
|
|
177
|
+
| `invalid_signature` | A webhook was not genuine |
|
|
178
|
+
|
|
179
|
+
A code the API names itself, such as `credential_invalid`, is passed through in lower case.
|
|
180
|
+
|
|
181
|
+
## Tests
|
|
182
|
+
|
|
183
|
+
```
|
|
184
|
+
python -m unittest discover -s tests
|
|
185
|
+
```
|
zapiack-0.1.0/README.md
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# zapiack (Python)
|
|
2
|
+
|
|
3
|
+
The official Zapiack SDK for Python. Send email, SMS and push notifications from one client.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install zapiack
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Python 3.9 or later. No dependencies.
|
|
10
|
+
|
|
11
|
+
## Quickstart
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import os
|
|
15
|
+
from zapiack import Zapiack
|
|
16
|
+
|
|
17
|
+
zapiack = Zapiack(os.environ["ZAPIACK_API_KEY"])
|
|
18
|
+
|
|
19
|
+
zapiack.email.send({
|
|
20
|
+
"from": "orders@myshop.com",
|
|
21
|
+
"to": "ada@example.com",
|
|
22
|
+
"subject": "Your order has shipped",
|
|
23
|
+
"html": "<p>It is on its way.</p>",
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
zapiack.sms.send({"phone": "+2348012345678", "country": "NG", "message": "Your order has shipped"})
|
|
27
|
+
|
|
28
|
+
zapiack.push.send({
|
|
29
|
+
"target": {"externalUserIds": ["user_123"]},
|
|
30
|
+
"title": "Your order has shipped",
|
|
31
|
+
"body": "Tap to track it",
|
|
32
|
+
"link": {"app": "myshop://orders/ord_789"},
|
|
33
|
+
})
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Create a secret API key in the dashboard under **Project → API Keys**. Keep it on your server: the client refuses a public app key.
|
|
37
|
+
The key can also come from the `ZAPIACK_API_KEY` environment variable: `Zapiack()`.
|
|
38
|
+
|
|
39
|
+
Parameters and answers are plain dictionaries, with the same names as the REST API and every other Zapiack SDK.
|
|
40
|
+
|
|
41
|
+
## What it does for you
|
|
42
|
+
|
|
43
|
+
- **Safe retries.** A failed request is retried up to twice, with backoff, on network errors, `429` and `5xx`, honouring
|
|
44
|
+
`Retry-After`. Only requests that cannot happen twice are retried: reads, and sends, which carry an idempotency key.
|
|
45
|
+
- **Idempotent sends.** Every send gets an `Idempotency-Key` automatically, so a retried send never goes out twice. Pass your own
|
|
46
|
+
to make a repeat from your code safe too: `zapiack.sms.send(params, RequestOptions(idempotency_key="order-42"))`.
|
|
47
|
+
- **Typed errors.** Every failure is a `ZapiackError` with a stable `code`, the HTTP `status` and a `request_id`.
|
|
48
|
+
- **Timeouts.** 30 seconds by default, per client or per call.
|
|
49
|
+
- **Pagination.** List calls return the first page; iterate it to walk every page.
|
|
50
|
+
- **Webhook verification.** One call checks the signature and reads the body.
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from zapiack import Zapiack, RequestOptions
|
|
54
|
+
|
|
55
|
+
zapiack = Zapiack("zpk_...", timeout=10, max_retries=3, app_info="my-app/1.4.0")
|
|
56
|
+
zapiack.sms.send(params, RequestOptions(idempotency_key="order-42", timeout=5))
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Email
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
zapiack.email.send({"from": f, "to": ["a@x.com", "b@x.com"], "templateId": "tpl_1", "variables": {"name": "Ada"}})
|
|
63
|
+
zapiack.email.send_batch([{"from": f, "to": "a@x.com", "subject": s, "html": h}, ...])
|
|
64
|
+
status = zapiack.email.get(email_id)
|
|
65
|
+
|
|
66
|
+
zapiack.email.contacts.create({"email": "ada@example.com", "firstName": "Ada"})
|
|
67
|
+
for contact in zapiack.email.contacts.list({"status": "SUBSCRIBED"}): # every contact, on every page
|
|
68
|
+
print(contact["email"])
|
|
69
|
+
|
|
70
|
+
zapiack.email.domains.add("myshop.com")
|
|
71
|
+
zapiack.email.templates.upload_asset(template_id, UploadFile(logo_bytes, "logo.png", "image/png"))
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Attachments take bytes or base64: `"attachments": [{"filename": "invoice.pdf", "content": pdf_bytes}]`.
|
|
75
|
+
|
|
76
|
+
## SMS
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
zapiack.sms.send({"phone": "+2348012345678", "country": "NG", "message": "Hello"})
|
|
80
|
+
zapiack.sms.send_batch([{"phone": p, "country": "NG", "message": m}, ...])
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Push notifications
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
sent = zapiack.push.send({
|
|
87
|
+
"target": {"tags": {"plan": "pro"}},
|
|
88
|
+
"title": "New in Pro",
|
|
89
|
+
"body": "See what is new",
|
|
90
|
+
"image": "https://cdn.myshop.com/launch.jpg",
|
|
91
|
+
"actions": [{"id": "open", "title": "Open", "event": "launch_opened", "link": {"app": "myshop://launch"}}],
|
|
92
|
+
"tracking": {"windowMinutes": 60, "screens": True, "goal": "upgrade_completed"},
|
|
93
|
+
"scheduledAt": datetime(2026, 12, 1, 9, tzinfo=timezone.utc),
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
zapiack.push.messages.reschedule(sent["messageId"], "2026-12-02T09:00:00+01:00")
|
|
97
|
+
zapiack.push.messages.cancel(sent["messageId"])
|
|
98
|
+
funnel = zapiack.push.messages.funnel(sent["messageId"])
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
A scheduled push works out who it reaches when its time comes. It can be cancelled or moved while it is still scheduled, and not
|
|
102
|
+
after it has started going out. Device-side registration and click tracking are done by the client SDKs inside your app.
|
|
103
|
+
|
|
104
|
+
## Webhooks
|
|
105
|
+
|
|
106
|
+
Pass the **raw** request body, the `Zapiack-Signature` header and your endpoint's signing secret:
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from flask import Flask, request
|
|
110
|
+
from zapiack import ZapiackSignatureError
|
|
111
|
+
|
|
112
|
+
@app.post("/zapiack")
|
|
113
|
+
def hook():
|
|
114
|
+
try:
|
|
115
|
+
payload = zapiack.webhooks.verify(request.get_data(), request.headers.get("Zapiack-Signature"), os.environ["ZAPIACK_WEBHOOK_SECRET"])
|
|
116
|
+
except ZapiackSignatureError:
|
|
117
|
+
return "", 400
|
|
118
|
+
for event in payload["events"]:
|
|
119
|
+
if event["type"] == "push.clicked":
|
|
120
|
+
print(event["externalUserId"], event["messageId"])
|
|
121
|
+
return "", 204
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`verify` raises `ZapiackSignatureError` when the signature is missing, wrong, or older than five minutes. Return any `2xx` to
|
|
125
|
+
acknowledge; otherwise the delivery is retried for up to a day.
|
|
126
|
+
|
|
127
|
+
## Errors
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from zapiack import ZapiackError
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
zapiack.sms.send(params)
|
|
134
|
+
except ZapiackError as error:
|
|
135
|
+
print(error.code, error.status, error.request_id, error.details)
|
|
136
|
+
if error.code == "insufficient_balance": ...
|
|
137
|
+
if error.code == "rate_limited": time.sleep(error.retry_after or 1)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
| `code` | When |
|
|
141
|
+
|---|---|
|
|
142
|
+
| `invalid_request` | The request was wrong. `details` lists what, when the API says |
|
|
143
|
+
| `authentication_failed` | The key is missing or not valid |
|
|
144
|
+
| `insufficient_balance` | The wallet cannot cover the send |
|
|
145
|
+
| `permission_denied` | The key may not do this |
|
|
146
|
+
| `not_found` | There is no such thing |
|
|
147
|
+
| `conflict` | It clashes with what is already there |
|
|
148
|
+
| `unprocessable` | The request was understood and refused |
|
|
149
|
+
| `rate_limited` | Too many requests. `retry_after` says how long to wait |
|
|
150
|
+
| `server_error` | Zapiack failed. Retried for you, then raised |
|
|
151
|
+
| `connection_error`, `timeout` | No answer was received |
|
|
152
|
+
| `invalid_signature` | A webhook was not genuine |
|
|
153
|
+
|
|
154
|
+
A code the API names itself, such as `credential_invalid`, is passed through in lower case.
|
|
155
|
+
|
|
156
|
+
## Tests
|
|
157
|
+
|
|
158
|
+
```
|
|
159
|
+
python -m unittest discover -s tests
|
|
160
|
+
```
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "zapiack"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "The official Zapiack SDK for Python: email, SMS and push notifications from one client."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
authors = [{ name = "Zapiack", email = "support@zapiack.com" }]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
dependencies = []
|
|
14
|
+
keywords = ["zapiack", "email", "sms", "push", "notifications", "sdk"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
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
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://zapiack.com"
|
|
29
|
+
Documentation = "https://docs.zapiack.com/introduction"
|
|
30
|
+
Source = "https://github.com/zapiack-hq/zapiack-python"
|
|
31
|
+
Issues = "https://github.com/zapiack-hq/zapiack-python/issues"
|
|
32
|
+
|
|
33
|
+
[tool.setuptools.packages.find]
|
|
34
|
+
where = ["src"]
|
|
35
|
+
|
|
36
|
+
[tool.setuptools.package-data]
|
|
37
|
+
zapiack = ["py.typed"]
|
zapiack-0.1.0/setup.cfg
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
|
+
]
|
|
@@ -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
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
VERSION = "0.1.0"
|