minilo 1.0.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.
- minilo/__init__.py +37 -0
- minilo/client.py +359 -0
- minilo/errors.py +65 -0
- minilo/py.typed +0 -0
- minilo/webhooks.py +71 -0
- minilo-1.0.0.dist-info/METADATA +206 -0
- minilo-1.0.0.dist-info/RECORD +10 -0
- minilo-1.0.0.dist-info/WHEEL +5 -0
- minilo-1.0.0.dist-info/licenses/LICENSE +21 -0
- minilo-1.0.0.dist-info/top_level.txt +1 -0
minilo/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Official Minilo API client for Python: short links, analytics and webhook verification."""
|
|
2
|
+
|
|
3
|
+
from . import webhooks
|
|
4
|
+
from .client import DEFAULT_BASE_URL, UNSET, VERSION, Minilo
|
|
5
|
+
from .errors import (
|
|
6
|
+
APIConnectionError,
|
|
7
|
+
APIError,
|
|
8
|
+
AuthenticationError,
|
|
9
|
+
ConflictError,
|
|
10
|
+
MiniloError,
|
|
11
|
+
NotFoundError,
|
|
12
|
+
PermissionDeniedError,
|
|
13
|
+
RateLimitError,
|
|
14
|
+
ServerError,
|
|
15
|
+
ValidationError,
|
|
16
|
+
WebhookSignatureError,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__version__ = VERSION
|
|
20
|
+
__all__ = [
|
|
21
|
+
"Minilo",
|
|
22
|
+
"webhooks",
|
|
23
|
+
"UNSET",
|
|
24
|
+
"VERSION",
|
|
25
|
+
"DEFAULT_BASE_URL",
|
|
26
|
+
"MiniloError",
|
|
27
|
+
"APIConnectionError",
|
|
28
|
+
"APIError",
|
|
29
|
+
"AuthenticationError",
|
|
30
|
+
"PermissionDeniedError",
|
|
31
|
+
"NotFoundError",
|
|
32
|
+
"ConflictError",
|
|
33
|
+
"ValidationError",
|
|
34
|
+
"RateLimitError",
|
|
35
|
+
"ServerError",
|
|
36
|
+
"WebhookSignatureError",
|
|
37
|
+
]
|
minilo/client.py
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
"""Minilo API client (standard library only)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import random
|
|
8
|
+
import socket
|
|
9
|
+
import time
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.parse
|
|
12
|
+
import urllib.request
|
|
13
|
+
import uuid
|
|
14
|
+
from email.utils import parsedate_to_datetime
|
|
15
|
+
from typing import Any, Dict, Iterator, List, Mapping, Optional
|
|
16
|
+
|
|
17
|
+
from .errors import (
|
|
18
|
+
APIConnectionError,
|
|
19
|
+
APIError,
|
|
20
|
+
AuthenticationError,
|
|
21
|
+
ConflictError,
|
|
22
|
+
MiniloError,
|
|
23
|
+
NotFoundError,
|
|
24
|
+
PermissionDeniedError,
|
|
25
|
+
RateLimitError,
|
|
26
|
+
ServerError,
|
|
27
|
+
ValidationError,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
VERSION = "1.0.0"
|
|
31
|
+
DEFAULT_BASE_URL = "https://minilo.nexoviasystems.com"
|
|
32
|
+
_RETRY_STATUSES = {500, 502, 503, 504}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _Unset:
|
|
36
|
+
def __repr__(self) -> str:
|
|
37
|
+
return "UNSET"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
UNSET: Any = _Unset()
|
|
41
|
+
"""Default for optional fields: the field is not sent. Pass None to clear a field."""
|
|
42
|
+
|
|
43
|
+
# Python argument name -> API field name.
|
|
44
|
+
_LINK_FIELDS = {
|
|
45
|
+
"destination": "destination",
|
|
46
|
+
"domain_id": "domainId",
|
|
47
|
+
"slug": "slug",
|
|
48
|
+
"slug_mode": "slugMode",
|
|
49
|
+
"title": "title",
|
|
50
|
+
"tags": "tags",
|
|
51
|
+
"utm": "utm",
|
|
52
|
+
"redirect_type": "redirectType",
|
|
53
|
+
"password": "password",
|
|
54
|
+
"expires_at": "expiresAt",
|
|
55
|
+
"expiry_fallback_url": "expiryFallbackUrl",
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _link_body(fields: Mapping[str, Any]) -> Dict[str, Any]:
|
|
60
|
+
body = {}
|
|
61
|
+
for name, value in fields.items():
|
|
62
|
+
if value is UNSET:
|
|
63
|
+
continue
|
|
64
|
+
api_name = _LINK_FIELDS.get(name)
|
|
65
|
+
if api_name is None:
|
|
66
|
+
if name in _LINK_FIELDS.values():
|
|
67
|
+
api_name = name # already the API's name (e.g. from a CSV or JSON)
|
|
68
|
+
else:
|
|
69
|
+
raise TypeError(f"Unknown link field: {name}")
|
|
70
|
+
body[api_name] = value
|
|
71
|
+
return body
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _retry_after(headers: Mapping[str, str]) -> Optional[float]:
|
|
75
|
+
raw = headers.get("retry-after") or headers.get("Retry-After")
|
|
76
|
+
if not raw:
|
|
77
|
+
return None
|
|
78
|
+
raw = raw.strip()
|
|
79
|
+
try:
|
|
80
|
+
return float(raw)
|
|
81
|
+
except ValueError:
|
|
82
|
+
pass
|
|
83
|
+
try:
|
|
84
|
+
return max(0.0, parsedate_to_datetime(raw).timestamp() - time.time())
|
|
85
|
+
except (TypeError, ValueError):
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _error_for(status: int, body: Any, headers: Mapping[str, str]) -> APIError:
|
|
90
|
+
if isinstance(body, dict) and isinstance(body.get("error"), dict):
|
|
91
|
+
err = body["error"]
|
|
92
|
+
else:
|
|
93
|
+
err = {"message": body if isinstance(body, str) and body else None}
|
|
94
|
+
if status == 401:
|
|
95
|
+
return AuthenticationError(status, err, headers)
|
|
96
|
+
if status == 403:
|
|
97
|
+
return PermissionDeniedError(status, err, headers)
|
|
98
|
+
if status == 404:
|
|
99
|
+
return NotFoundError(status, err, headers)
|
|
100
|
+
if status == 409:
|
|
101
|
+
return ConflictError(status, err, headers)
|
|
102
|
+
if status in (400, 422):
|
|
103
|
+
return ValidationError(status, err, headers)
|
|
104
|
+
if status == 429:
|
|
105
|
+
return RateLimitError(status, err, headers, _retry_after(headers))
|
|
106
|
+
if status >= 500:
|
|
107
|
+
return ServerError(status, err, headers)
|
|
108
|
+
return APIError(status, err, headers)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class Minilo:
|
|
112
|
+
"""Client for the Minilo API.
|
|
113
|
+
|
|
114
|
+
>>> from minilo import Minilo
|
|
115
|
+
>>> client = Minilo() # reads MINILO_API_KEY
|
|
116
|
+
>>> link = client.links.create("https://example.com/spring", title="Spring sale")
|
|
117
|
+
>>> link["shortUrl"]
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
def __init__(
|
|
121
|
+
self,
|
|
122
|
+
api_key: Optional[str] = None,
|
|
123
|
+
*,
|
|
124
|
+
base_url: Optional[str] = None,
|
|
125
|
+
max_retries: int = 3,
|
|
126
|
+
timeout: float = 30.0,
|
|
127
|
+
max_retry_after: float = 60.0,
|
|
128
|
+
):
|
|
129
|
+
api_key = api_key or os.environ.get("MINILO_API_KEY")
|
|
130
|
+
if not api_key:
|
|
131
|
+
raise MiniloError(
|
|
132
|
+
"No API key. Pass api_key or set MINILO_API_KEY. Create one in Settings → API keys."
|
|
133
|
+
)
|
|
134
|
+
self._api_key = api_key
|
|
135
|
+
self.base_url = (base_url or os.environ.get("MINILO_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
136
|
+
self.max_retries = max_retries
|
|
137
|
+
self.timeout = timeout
|
|
138
|
+
self.max_retry_after = max_retry_after
|
|
139
|
+
self.links = Links(self)
|
|
140
|
+
self.domains = Domains(self)
|
|
141
|
+
self.tags = Tags(self)
|
|
142
|
+
self.analytics = Analytics(self)
|
|
143
|
+
|
|
144
|
+
def _request(
|
|
145
|
+
self,
|
|
146
|
+
method: str,
|
|
147
|
+
path: str,
|
|
148
|
+
*,
|
|
149
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
150
|
+
body: Any = None,
|
|
151
|
+
idempotency_key: Optional[str] = None,
|
|
152
|
+
safe_to_repeat: bool = True,
|
|
153
|
+
) -> Any:
|
|
154
|
+
url = self.base_url + path
|
|
155
|
+
if query:
|
|
156
|
+
pairs = []
|
|
157
|
+
for key, value in query.items():
|
|
158
|
+
if value is None:
|
|
159
|
+
continue
|
|
160
|
+
for item in value if isinstance(value, (list, tuple)) else [value]:
|
|
161
|
+
pairs.append((key, str(item)))
|
|
162
|
+
if pairs:
|
|
163
|
+
url += "?" + urllib.parse.urlencode(pairs)
|
|
164
|
+
headers = {
|
|
165
|
+
"Authorization": f"Bearer {self._api_key}",
|
|
166
|
+
"Accept": "application/json",
|
|
167
|
+
"User-Agent": f"minilo-python/{VERSION}",
|
|
168
|
+
}
|
|
169
|
+
data = None
|
|
170
|
+
if body is not None:
|
|
171
|
+
data = json.dumps(body).encode("utf-8")
|
|
172
|
+
headers["Content-Type"] = "application/json"
|
|
173
|
+
if idempotency_key:
|
|
174
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
175
|
+
|
|
176
|
+
attempt = 0
|
|
177
|
+
while True:
|
|
178
|
+
request = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
179
|
+
try:
|
|
180
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
181
|
+
text = response.read().decode("utf-8")
|
|
182
|
+
return json.loads(text) if text else None
|
|
183
|
+
except urllib.error.HTTPError as http_error:
|
|
184
|
+
status = http_error.code
|
|
185
|
+
response_headers = {k.lower(): v for k, v in http_error.headers.items()}
|
|
186
|
+
text = http_error.read().decode("utf-8", errors="replace")
|
|
187
|
+
try:
|
|
188
|
+
parsed: Any = json.loads(text) if text else None
|
|
189
|
+
except ValueError:
|
|
190
|
+
parsed = text # not JSON, e.g. a proxy's HTML error page
|
|
191
|
+
error = _error_for(status, parsed, response_headers)
|
|
192
|
+
wait = _retry_after(response_headers)
|
|
193
|
+
# A 429 with Retry-After was not processed: always safe to repeat.
|
|
194
|
+
# A 429 without it is an hourly quota: waiting will not help.
|
|
195
|
+
if status == 429:
|
|
196
|
+
retryable = wait is not None
|
|
197
|
+
else:
|
|
198
|
+
retryable = status in _RETRY_STATUSES and safe_to_repeat
|
|
199
|
+
if not retryable or attempt >= self.max_retries:
|
|
200
|
+
raise error from None
|
|
201
|
+
if wait is not None and wait > self.max_retry_after:
|
|
202
|
+
raise error from None
|
|
203
|
+
time.sleep(wait if wait is not None else self._backoff(attempt))
|
|
204
|
+
except (urllib.error.URLError, socket.timeout, TimeoutError, ConnectionError) as network_error:
|
|
205
|
+
if safe_to_repeat and attempt < self.max_retries:
|
|
206
|
+
time.sleep(self._backoff(attempt))
|
|
207
|
+
else:
|
|
208
|
+
reason = getattr(network_error, "reason", network_error)
|
|
209
|
+
raise APIConnectionError(f"Could not reach {self.base_url}: {reason}") from network_error
|
|
210
|
+
attempt += 1
|
|
211
|
+
|
|
212
|
+
@staticmethod
|
|
213
|
+
def _backoff(attempt: int) -> float:
|
|
214
|
+
"""0.5 s, 1 s, 2 s, 4 s… (max 8 s) with ±25% jitter."""
|
|
215
|
+
return min(8.0, 0.5 * 2**attempt) * (0.75 + random.random() * 0.5)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _link_path(link_id: str) -> str:
|
|
219
|
+
return "/api/v1/links/" + urllib.parse.quote(link_id, safe="")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class Links:
|
|
223
|
+
def __init__(self, client: Minilo):
|
|
224
|
+
self._client = client
|
|
225
|
+
|
|
226
|
+
def list(
|
|
227
|
+
self,
|
|
228
|
+
*,
|
|
229
|
+
q: Optional[str] = None,
|
|
230
|
+
domain: Optional[str] = None,
|
|
231
|
+
tag: Any = None,
|
|
232
|
+
creator: Optional[str] = None,
|
|
233
|
+
status: Optional[str] = None,
|
|
234
|
+
from_: Optional[str] = None,
|
|
235
|
+
to: Optional[str] = None,
|
|
236
|
+
sort: Optional[str] = None,
|
|
237
|
+
direction: Optional[str] = None,
|
|
238
|
+
page: Optional[int] = None,
|
|
239
|
+
page_size: Optional[int] = None,
|
|
240
|
+
) -> Dict[str, Any]:
|
|
241
|
+
"""One page of links: ``{total, page, pageSize, items}``. page_size is 10, 20, 30, 40 or 50."""
|
|
242
|
+
return self._client._request(
|
|
243
|
+
"GET",
|
|
244
|
+
"/api/v1/links",
|
|
245
|
+
query={
|
|
246
|
+
"q": q, "domain": domain, "tag": tag, "creator": creator, "status": status,
|
|
247
|
+
"from": from_, "to": to, "sort": sort, "direction": direction,
|
|
248
|
+
"page": page, "pageSize": page_size,
|
|
249
|
+
},
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
def list_all(self, **filters: Any) -> Iterator[Dict[str, Any]]:
|
|
253
|
+
"""Every matching link, fetching pages of 50 as you iterate."""
|
|
254
|
+
filters.pop("page", None)
|
|
255
|
+
filters.pop("page_size", None)
|
|
256
|
+
page = 1
|
|
257
|
+
while True:
|
|
258
|
+
result = self.list(page=page, page_size=50, **filters)
|
|
259
|
+
yield from result["items"]
|
|
260
|
+
if not result["items"] or page * result["pageSize"] >= result["total"]:
|
|
261
|
+
return
|
|
262
|
+
page += 1
|
|
263
|
+
|
|
264
|
+
def create(
|
|
265
|
+
self,
|
|
266
|
+
destination: str,
|
|
267
|
+
*,
|
|
268
|
+
domain_id: Any = UNSET,
|
|
269
|
+
slug: Any = UNSET,
|
|
270
|
+
slug_mode: Any = UNSET,
|
|
271
|
+
title: Any = UNSET,
|
|
272
|
+
tags: Any = UNSET,
|
|
273
|
+
utm: Any = UNSET,
|
|
274
|
+
redirect_type: Any = UNSET,
|
|
275
|
+
password: Any = UNSET,
|
|
276
|
+
expires_at: Any = UNSET,
|
|
277
|
+
expiry_fallback_url: Any = UNSET,
|
|
278
|
+
idempotency_key: Optional[str] = None,
|
|
279
|
+
) -> Dict[str, Any]:
|
|
280
|
+
"""Create a link. An Idempotency-Key is sent (and reused on retries) automatically."""
|
|
281
|
+
fields = dict(locals())
|
|
282
|
+
for name in ("self", "idempotency_key"):
|
|
283
|
+
fields.pop(name)
|
|
284
|
+
return self._client._request(
|
|
285
|
+
"POST",
|
|
286
|
+
"/api/v1/links",
|
|
287
|
+
body=_link_body(fields),
|
|
288
|
+
idempotency_key=idempotency_key or str(uuid.uuid4()),
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
def bulk_create(self, links: List[Mapping[str, Any]], *, idempotency_key: Optional[str] = None) -> Dict[str, Any]:
|
|
292
|
+
"""Create up to 100 links. Each item is a dict of create fields (snake_case or the API's names)."""
|
|
293
|
+
return self._client._request(
|
|
294
|
+
"POST",
|
|
295
|
+
"/api/v1/links/bulk",
|
|
296
|
+
body={"links": [_link_body(item) for item in links]},
|
|
297
|
+
idempotency_key=idempotency_key or str(uuid.uuid4()),
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
def get(self, link_id: str) -> Dict[str, Any]:
|
|
301
|
+
return self._client._request("GET", _link_path(link_id))
|
|
302
|
+
|
|
303
|
+
def update(self, link_id: str, **changes: Any) -> Dict[str, Any]:
|
|
304
|
+
"""Send only the fields to change, e.g. ``update(id, title="New")``. None clears a field."""
|
|
305
|
+
return self._client._request("PATCH", _link_path(link_id), body=_link_body(changes))
|
|
306
|
+
|
|
307
|
+
def delete(self, link_id: str) -> Dict[str, Any]:
|
|
308
|
+
"""With an API key this archives the link (restorable); it never deletes permanently."""
|
|
309
|
+
return self._client._request("DELETE", _link_path(link_id))
|
|
310
|
+
|
|
311
|
+
def archive(self, link_id: str) -> Dict[str, Any]:
|
|
312
|
+
return self._client._request("POST", _link_path(link_id) + "/archive", safe_to_repeat=False)
|
|
313
|
+
|
|
314
|
+
def restore(self, link_id: str) -> Dict[str, Any]:
|
|
315
|
+
return self._client._request("POST", _link_path(link_id) + "/restore", safe_to_repeat=False)
|
|
316
|
+
|
|
317
|
+
def check_slug(self, slug: str, domain_id: Optional[str] = None) -> Dict[str, Any]:
|
|
318
|
+
"""``{available, reason}`` for a back-half on the shared domain or on domain_id."""
|
|
319
|
+
return self._client._request(
|
|
320
|
+
"GET", "/api/v1/links/slug-availability", query={"slug": slug, "domainId": domain_id}
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
class Domains:
|
|
325
|
+
def __init__(self, client: Minilo):
|
|
326
|
+
self._client = client
|
|
327
|
+
|
|
328
|
+
def list(self) -> List[Dict[str, Any]]:
|
|
329
|
+
"""The shared short domain and the workspace's verified custom domains."""
|
|
330
|
+
return self._client._request("GET", "/api/v1/links/domains")
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
class Tags:
|
|
334
|
+
def __init__(self, client: Minilo):
|
|
335
|
+
self._client = client
|
|
336
|
+
|
|
337
|
+
def list(self) -> List[Dict[str, Any]]:
|
|
338
|
+
return self._client._request("GET", "/api/v1/tags")
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
class Analytics:
|
|
342
|
+
def __init__(self, client: Minilo):
|
|
343
|
+
self._client = client
|
|
344
|
+
|
|
345
|
+
def get(
|
|
346
|
+
self,
|
|
347
|
+
range: str = "7d",
|
|
348
|
+
*,
|
|
349
|
+
from_: Optional[str] = None,
|
|
350
|
+
to: Optional[str] = None,
|
|
351
|
+
domain: Optional[str] = None,
|
|
352
|
+
link: Optional[str] = None,
|
|
353
|
+
) -> Dict[str, Any]:
|
|
354
|
+
"""Totals, a time series and breakdowns. range: 24h, 7d, 30d, 90d, or custom with from_/to (YYYY-MM-DD)."""
|
|
355
|
+
return self._client._request(
|
|
356
|
+
"GET",
|
|
357
|
+
"/api/v1/analytics",
|
|
358
|
+
query={"range": range, "from": from_, "to": to, "domain": domain, "link": link},
|
|
359
|
+
)
|
minilo/errors.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Errors raised by the Minilo SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Mapping, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MiniloError(Exception):
|
|
9
|
+
"""Base class of every error this SDK raises."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class APIConnectionError(MiniloError):
|
|
13
|
+
"""The request never got an HTTP answer (network failure or timeout)."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class APIError(MiniloError):
|
|
17
|
+
"""The API answered with an error: ``{"error": {code, message, field?, requestId}}``."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, status: int, body: Mapping[str, Any], headers: Mapping[str, str]):
|
|
20
|
+
self.status: int = status
|
|
21
|
+
self.code: str = body.get("code") or f"HTTP_{status}"
|
|
22
|
+
self.message: str = body.get("message") or f"HTTP {status}"
|
|
23
|
+
self.field: Optional[str] = body.get("field")
|
|
24
|
+
self.request_id: Optional[str] = body.get("requestId")
|
|
25
|
+
self.headers = dict(headers)
|
|
26
|
+
super().__init__(self.message)
|
|
27
|
+
|
|
28
|
+
def __repr__(self) -> str:
|
|
29
|
+
return f"{type(self).__name__}(status={self.status}, code={self.code!r}, message={self.message!r})"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class AuthenticationError(APIError):
|
|
33
|
+
"""401: missing, wrong or revoked API key."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class PermissionDeniedError(APIError):
|
|
37
|
+
"""403: the key's scope or the plan does not allow this."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class NotFoundError(APIError):
|
|
41
|
+
"""404: no such link in this workspace."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ConflictError(APIError):
|
|
45
|
+
"""409: e.g. the back-half is taken."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ValidationError(APIError):
|
|
49
|
+
"""400 / 422: validation failed; see ``code`` and ``field``."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class RateLimitError(APIError):
|
|
53
|
+
"""429: too many requests. ``retry_after`` is the number of seconds to wait, when known."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, status, body, headers, retry_after: Optional[float] = None):
|
|
56
|
+
super().__init__(status, body, headers)
|
|
57
|
+
self.retry_after = retry_after
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class ServerError(APIError):
|
|
61
|
+
"""5xx: a problem on Minilo's side."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class WebhookSignatureError(MiniloError):
|
|
65
|
+
"""A webhook's signature header is missing, malformed, wrong or too old."""
|
minilo/py.typed
ADDED
|
File without changes
|
minilo/webhooks.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Verify webhook deliveries from Minilo.
|
|
2
|
+
|
|
3
|
+
Each delivery carries ``X-Minilo-Signature: t=<unix seconds>,v1=<hex>``, where
|
|
4
|
+
v1 is HMAC-SHA256 of ``"<t>.<raw body>"`` with the endpoint's signing secret.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import hmac
|
|
11
|
+
import json
|
|
12
|
+
import time
|
|
13
|
+
from typing import Any, Dict, Optional, Union
|
|
14
|
+
|
|
15
|
+
from .errors import WebhookSignatureError
|
|
16
|
+
|
|
17
|
+
Payload = Union[str, bytes]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _text(payload: Payload) -> str:
|
|
21
|
+
return payload.decode("utf-8") if isinstance(payload, (bytes, bytearray)) else payload
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def verify_signature(
|
|
25
|
+
payload: Payload,
|
|
26
|
+
signature: Optional[str],
|
|
27
|
+
secret: str,
|
|
28
|
+
tolerance: int = 300,
|
|
29
|
+
now: Optional[int] = None,
|
|
30
|
+
) -> None:
|
|
31
|
+
"""Raise WebhookSignatureError unless the signature is valid and recent.
|
|
32
|
+
|
|
33
|
+
Pass the raw request body exactly as received, not re-serialised JSON.
|
|
34
|
+
"""
|
|
35
|
+
if not signature:
|
|
36
|
+
raise WebhookSignatureError("Missing X-Minilo-Signature header.")
|
|
37
|
+
timestamp = None
|
|
38
|
+
candidates = []
|
|
39
|
+
for part in signature.split(","):
|
|
40
|
+
key, _, value = part.strip().partition("=")
|
|
41
|
+
if key == "t":
|
|
42
|
+
timestamp = value
|
|
43
|
+
elif key == "v1":
|
|
44
|
+
candidates.append(value)
|
|
45
|
+
if not timestamp or not timestamp.isdigit() or not candidates:
|
|
46
|
+
raise WebhookSignatureError("Malformed X-Minilo-Signature header.")
|
|
47
|
+
current = int(time.time()) if now is None else now
|
|
48
|
+
if abs(current - int(timestamp)) > tolerance:
|
|
49
|
+
raise WebhookSignatureError("Webhook timestamp is outside the tolerance.")
|
|
50
|
+
expected = hmac.new(
|
|
51
|
+
secret.encode("utf-8"),
|
|
52
|
+
f"{timestamp}.{_text(payload)}".encode("utf-8"),
|
|
53
|
+
hashlib.sha256,
|
|
54
|
+
).hexdigest()
|
|
55
|
+
if not any(hmac.compare_digest(expected, c) for c in candidates):
|
|
56
|
+
raise WebhookSignatureError("Webhook signature does not match.")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def is_valid(payload: Payload, signature: Optional[str], secret: str, tolerance: int = 300, now: Optional[int] = None) -> bool:
|
|
60
|
+
"""True when the signature is valid; never raises."""
|
|
61
|
+
try:
|
|
62
|
+
verify_signature(payload, signature, secret, tolerance, now)
|
|
63
|
+
return True
|
|
64
|
+
except WebhookSignatureError:
|
|
65
|
+
return False
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def parse(payload: Payload, signature: Optional[str], secret: str, tolerance: int = 300, now: Optional[int] = None) -> Dict[str, Any]:
|
|
69
|
+
"""Verify the signature, then return the event as a dict."""
|
|
70
|
+
verify_signature(payload, signature, secret, tolerance, now)
|
|
71
|
+
return json.loads(_text(payload))
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: minilo
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Official Minilo API client: short links, bulk creation, analytics and webhook verification.
|
|
5
|
+
License: MIT
|
|
6
|
+
Keywords: minilo,url-shortener,short-links,api,sdk
|
|
7
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# Minilo SDK for Python
|
|
17
|
+
|
|
18
|
+
The official client for the [Minilo API](https://minilo.nexoviasystems.com/docs). Use it to create and manage short links, create links in bulk, read click analytics and check webhook signatures.
|
|
19
|
+
|
|
20
|
+
- Python 3.9 or later. No dependencies: only the standard library.
|
|
21
|
+
- Creating a link sends an `Idempotency-Key` automatically, so a retry never makes a duplicate.
|
|
22
|
+
- Retries automatically after rate limits (`429` with `Retry-After`), `5xx` errors and network errors.
|
|
23
|
+
- Errors are typed: `NotFoundError`, `ValidationError`, `RateLimitError` and so on.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install minilo
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
> Before the package is on PyPI, install it from the archive Minilo sent you: `pip install ./minilo-python-1.0.0.tar.gz`.
|
|
32
|
+
|
|
33
|
+
## Quick start
|
|
34
|
+
|
|
35
|
+
Create an API key in **Settings → API keys** and set it as `MINILO_API_KEY`.
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from minilo import Minilo
|
|
39
|
+
|
|
40
|
+
client = Minilo() # reads MINILO_API_KEY
|
|
41
|
+
|
|
42
|
+
link = client.links.create(
|
|
43
|
+
"https://example.com/spring-sale",
|
|
44
|
+
title="Spring sale",
|
|
45
|
+
tags=["campaign"],
|
|
46
|
+
)
|
|
47
|
+
print(link["shortUrl"]) # https://go.nexoviasystems.com/aB3dE9xQ2kLm
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Responses are plain dicts with the API's field names (`shortUrl`, `createdAt`, …), exactly as in the [API reference](https://minilo.nexoviasystems.com/docs).
|
|
51
|
+
|
|
52
|
+
## Configuration
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
client = Minilo(
|
|
56
|
+
"sk_live_…", # default: MINILO_API_KEY
|
|
57
|
+
base_url="https://…", # default: MINILO_BASE_URL, else https://minilo.nexoviasystems.com
|
|
58
|
+
max_retries=3, # retries after 429 / 5xx / network errors
|
|
59
|
+
timeout=30.0, # seconds per attempt
|
|
60
|
+
max_retry_after=60.0, # a longer Retry-After raises RateLimitError at once
|
|
61
|
+
)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Use a **full access** key (`sk_live_…`) for everything. A **create-only** key (`ck_live_…`) can only call `links.create` and `links.bulk_create`. Keep keys out of source control.
|
|
65
|
+
|
|
66
|
+
## Links
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
# Pass your own idempotency_key (e.g. an order number) to make retries across
|
|
70
|
+
# process restarts safe too.
|
|
71
|
+
link = client.links.create(
|
|
72
|
+
"https://example.com",
|
|
73
|
+
slug="spring",
|
|
74
|
+
expires_at="2027-01-01T00:00:00Z",
|
|
75
|
+
idempotency_key="order-1042",
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
client.links.get(link["id"])
|
|
79
|
+
client.links.update(link["id"], title="Spring sale (final)")
|
|
80
|
+
client.links.update(link["id"], expires_at=None) # None clears a field
|
|
81
|
+
client.links.archive(link["id"]) # stops redirecting; can be restored
|
|
82
|
+
client.links.restore(link["id"])
|
|
83
|
+
client.links.delete(link["id"]) # with an API key this archives (never permanent)
|
|
84
|
+
|
|
85
|
+
client.links.check_slug("spring") # {"available": True, "reason": None}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Fields for `create` and `update`: `destination`, `domain_id`, `slug`, `slug_mode`, `title`, `tags`, `utm`, `redirect_type` (301 or 302), `password`, `expires_at`, `expiry_fallback_url`.
|
|
89
|
+
|
|
90
|
+
### Bulk create (up to 100)
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
result = client.links.bulk_create([
|
|
94
|
+
{"destination": "https://example.com/a"},
|
|
95
|
+
{"destination": "https://example.com/b", "tags": ["email"]},
|
|
96
|
+
])
|
|
97
|
+
print(result["created"], result["failed"])
|
|
98
|
+
for row in result["results"]:
|
|
99
|
+
if row["status"] == "FAILED":
|
|
100
|
+
print(row["index"], row["error"]["code"], row["error"]["message"])
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
One failing row never stops the others. Items accept the Python names (`domain_id`) or the API's (`domainId`).
|
|
104
|
+
|
|
105
|
+
### Listing and paging
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
page = client.links.list(q="spring", status="ACTIVE", page_size=50, page=1)
|
|
109
|
+
print(page["total"], len(page["items"]))
|
|
110
|
+
|
|
111
|
+
# Or let the SDK walk every page:
|
|
112
|
+
for link in client.links.list_all(tag="campaign"):
|
|
113
|
+
print(link["shortUrl"], link["totalClicks"])
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
`from` is a Python keyword, so the date filter is `from_=`.
|
|
117
|
+
|
|
118
|
+
## Domains, tags and analytics
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
client.domains.list() # the shared domain plus your verified custom domains
|
|
122
|
+
client.tags.list()
|
|
123
|
+
|
|
124
|
+
report = client.analytics.get("30d") # whole workspace
|
|
125
|
+
one = client.analytics.get("7d", link=link["id"]) # one link
|
|
126
|
+
custom = client.analytics.get("custom", from_="2026-11-01", to="2026-11-30")
|
|
127
|
+
print(report["totals"]["clicks"])
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Errors
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
import minilo
|
|
134
|
+
|
|
135
|
+
client = minilo.Minilo()
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
client.links.create("not a url")
|
|
139
|
+
except minilo.ValidationError as e:
|
|
140
|
+
print(e.field, e.code, e.message)
|
|
141
|
+
except minilo.RateLimitError as e:
|
|
142
|
+
print(f"retry in {e.retry_after} s")
|
|
143
|
+
except minilo.APIError as e:
|
|
144
|
+
print(e.status, e.code, e.request_id)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
| Class | When |
|
|
148
|
+
| ----------------------- | -------------------------------------------------- |
|
|
149
|
+
| `AuthenticationError` | 401: missing, wrong or revoked key |
|
|
150
|
+
| `PermissionDeniedError` | 403: the key's scope or the plan does not allow it |
|
|
151
|
+
| `NotFoundError` | 404: no such link in this workspace |
|
|
152
|
+
| `ConflictError` | 409: e.g. the back-half is taken |
|
|
153
|
+
| `ValidationError` | 400 / 422: see `field` and `code` |
|
|
154
|
+
| `RateLimitError` | 429: `retry_after` seconds, when given |
|
|
155
|
+
| `ServerError` | 5xx |
|
|
156
|
+
| `APIConnectionError` | no answer (network failure or timeout) |
|
|
157
|
+
|
|
158
|
+
All of them derive from `minilo.MiniloError`. API errors carry `status`, `code`, `message`, `field` and `request_id`; quote the `request_id` when you contact support.
|
|
159
|
+
|
|
160
|
+
### Retries
|
|
161
|
+
|
|
162
|
+
| Situation | What the SDK does |
|
|
163
|
+
| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
164
|
+
| 429 with `Retry-After` | waits that long, then retries (up to `max_retries`) |
|
|
165
|
+
| 429 without `Retry-After` (an hourly creation limit) | raises at once: waiting seconds will not help |
|
|
166
|
+
| 500, 502, 503, 504 or a network error | retries with backoff (0.5 s, 1 s, 2 s…) when repeating is safe: reads, updates, archive by DELETE, and creates (they carry an Idempotency-Key) |
|
|
167
|
+
| `archive` / `restore` after a 5xx | not retried |
|
|
168
|
+
| 400, 401, 403, 404, 409, 422 | never retried |
|
|
169
|
+
|
|
170
|
+
## Webhooks
|
|
171
|
+
|
|
172
|
+
Minilo signs every delivery with `X-Minilo-Signature`. Verify it against the **raw** body:
|
|
173
|
+
|
|
174
|
+
```python
|
|
175
|
+
# Flask
|
|
176
|
+
import os
|
|
177
|
+
|
|
178
|
+
from flask import Flask, request, abort
|
|
179
|
+
from minilo import webhooks, WebhookSignatureError
|
|
180
|
+
|
|
181
|
+
app = Flask(__name__)
|
|
182
|
+
|
|
183
|
+
@app.post("/minilo/webhooks")
|
|
184
|
+
def minilo_webhook():
|
|
185
|
+
try:
|
|
186
|
+
event = webhooks.parse(
|
|
187
|
+
request.get_data(), # raw bytes, not request.json
|
|
188
|
+
request.headers.get("X-Minilo-Signature"),
|
|
189
|
+
os.environ["MINILO_WEBHOOK_SECRET"],
|
|
190
|
+
)
|
|
191
|
+
except WebhookSignatureError:
|
|
192
|
+
abort(400)
|
|
193
|
+
if event["type"] == "link.clicked":
|
|
194
|
+
...
|
|
195
|
+
return "", 200
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
`webhooks.is_valid(...)` returns `True`/`False` instead of raising. Deliveries signed more than 5 minutes ago are refused (`tolerance=`). The same event can arrive more than once; use `event["id"]` to skip duplicates.
|
|
199
|
+
|
|
200
|
+
## Support
|
|
201
|
+
|
|
202
|
+
API reference: https://minilo.nexoviasystems.com/docs · OpenAPI description: https://minilo.nexoviasystems.com/openapi.json
|
|
203
|
+
|
|
204
|
+
## License
|
|
205
|
+
|
|
206
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
minilo/__init__.py,sha256=-ayX2ek1WjDKqnXxmShlobwRTvYpRKL0p5XsVTfrBkI,804
|
|
2
|
+
minilo/client.py,sha256=MS-J40cC8iIPDcOffxPDagY5tKMor0-tk1vrAqb0Ey8,12717
|
|
3
|
+
minilo/errors.py,sha256=mM1l-6tdY3NjxBCYZHLE5VGmEywuNdztwOyDl2aRMT0,1987
|
|
4
|
+
minilo/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
minilo/webhooks.py,sha256=W4kMZzvM35_x1U04bEMzy6CJ9SDgTX4DxqD7i-kuF5g,2480
|
|
6
|
+
minilo-1.0.0.dist-info/licenses/LICENSE,sha256=EZk9pOPjlKmcTODo8khQSSiOWWLZkLOJ01W_PAURO6o,1063
|
|
7
|
+
minilo-1.0.0.dist-info/METADATA,sha256=oAPqJN3r0CY1AOWCkCAgt5Ec7s8IhL_-0bOXrbHwz9M,8327
|
|
8
|
+
minilo-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
minilo-1.0.0.dist-info/top_level.txt,sha256=XeqFfK_ZCiIi8UcH7yKgcNArNcMm-ymXib6HjfRF-wg,7
|
|
10
|
+
minilo-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Minilo
|
|
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 @@
|
|
|
1
|
+
minilo
|