lshorter 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,53 @@
1
+ # prod
2
+ dist/
3
+
4
+ # dev
5
+ .yarn/
6
+ !.yarn/releases
7
+ .vscode/*
8
+ !.vscode/launch.json
9
+ !.vscode/*.code-snippets
10
+ .idea/workspace.xml
11
+ .idea/usage.statistics.xml
12
+ .idea/shelf
13
+
14
+ # deps
15
+ node_modules/
16
+ .wrangler
17
+
18
+ # env
19
+ .env
20
+ .env.production
21
+ .dev.vars
22
+
23
+ # logs
24
+ logs/
25
+ *.log
26
+ npm-debug.log*
27
+ yarn-debug.log*
28
+ yarn-error.log*
29
+ pnpm-debug.log*
30
+ lerna-debug.log*
31
+
32
+ # misc
33
+ .DS_Store
34
+
35
+ # private docs (internal only — not for public repo)
36
+ privateReadme.md
37
+
38
+ # test artifacts
39
+ coverage/
40
+ __tests__/
41
+ .playwright-cli/
42
+
43
+ # multi-language SDK build artifacts
44
+ sdks/python/dist/
45
+ sdks/python/build/
46
+ sdks/python/*.egg-info/
47
+ sdks/python/src/*.egg-info/
48
+ sdks/python/**/__pycache__/
49
+ sdks/python/.pytest_cache/
50
+ sdks/rust/target/
51
+ sdks/rust/Cargo.lock
52
+ sdks/php/vendor/
53
+ sdks/php/.phpunit.cache/
lshorter-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 KONVELBO Samuel — LShorter
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,90 @@
1
+ Metadata-Version: 2.5
2
+ Name: lshorter
3
+ Version: 1.0.0
4
+ Summary: Official Python SDK for LShorter — Ultra-fast Edge URL Shortener, Dynamic Routing, PathLock™, and Conversion Tracking.
5
+ Project-URL: Homepage, https://lsho.cc
6
+ Project-URL: Documentation, https://lsho.cc/docs
7
+ Project-URL: Repository, https://github.com/Konvelbo/LShorter-api
8
+ Project-URL: Issues, https://github.com/Konvelbo/LShorter-api/issues
9
+ Author: KONVELBO Samuel
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: analytics,conversion-tracking,edge-redirect,lshorter,pathlock,short-link,url-shortener
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+
26
+ # LShorter — Official Python SDK
27
+
28
+ Official zero-dependency Python SDK for [LShorter](https://lsho.cc): ultra-fast edge URL shortening, dynamic geo/device routing, PathLock™, retargeting pixels, webhooks, and conversion attribution.
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install lshorter
34
+ ```
35
+
36
+ ## Quickstart
37
+
38
+ ```python
39
+ import os
40
+ from lshorter import LShorter, LShorterError
41
+
42
+ lsh = LShorter(api_key=os.environ["LSHORTER_API_KEY"])
43
+
44
+ # 1. Create a short link with targeting & PathLock™
45
+ link = lsh.links.create({
46
+ "targetUrl": "https://my-store.com/summer-sale",
47
+ "slug": "summer-2026",
48
+ "geoTargeting": {
49
+ "FR": "https://my-store.fr/summer-sale",
50
+ "US": "https://my-store.com/us-sale",
51
+ },
52
+ "deviceTargeting": {
53
+ "ios": "https://apps.apple.com/app/id123456789",
54
+ "android": "https://play.google.com/store/apps/details?id=com.store",
55
+ },
56
+ "pixels": ["px_meta_main", "px_tiktok_main"],
57
+ })
58
+ print("Short URL:", link["shortUrl"])
59
+
60
+ # 2. Track a conversion
61
+ lsh.track.conversion(
62
+ event_name="purchase",
63
+ amount=49.99,
64
+ currency="EUR",
65
+ link_id=link["id"],
66
+ click_id="clk_abc123",
67
+ customer={
68
+ "id": "usr_123",
69
+ "email": "alex@example.com",
70
+ "name": "Alex Johnson",
71
+ "avatarUrl": "https://example.com/avatars/alex.jpg",
72
+ },
73
+ )
74
+
75
+ # 3. Query real-time analytics
76
+ stats = lsh.analytics.dashboard(link_id=link["id"])
77
+ print("Clicks:", stats["totalClicks"], "Revenue:", stats["trackedRevenue"])
78
+ ```
79
+
80
+ ## Available Modules
81
+
82
+ | Module | Methods |
83
+ | :--- | :--- |
84
+ | `lsh.links` | `create`, `list`, `get`, `update`, `delete` |
85
+ | `lsh.track` | `conversion`, `list` |
86
+ | `lsh.analytics` | `dashboard`, `top`, `links`, `export_csv` |
87
+ | `lsh.domains` | `create`, `list`, `get`, `verify`, `delete` |
88
+ | `lsh.webhooks` | `list`, `get`, `update`, `delete` *(creation via Dashboard only)* |
89
+ | `lsh.pixels` | `list`, `get`, `update`, `delete` *(creation via Dashboard only)* |
90
+ | `lsh.notifications` / `lsh.targets` | `list`, `get` *(read-only)* |
@@ -0,0 +1,65 @@
1
+ # LShorter — Official Python SDK
2
+
3
+ Official zero-dependency Python SDK for [LShorter](https://lsho.cc): ultra-fast edge URL shortening, dynamic geo/device routing, PathLock™, retargeting pixels, webhooks, and conversion attribution.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install lshorter
9
+ ```
10
+
11
+ ## Quickstart
12
+
13
+ ```python
14
+ import os
15
+ from lshorter import LShorter, LShorterError
16
+
17
+ lsh = LShorter(api_key=os.environ["LSHORTER_API_KEY"])
18
+
19
+ # 1. Create a short link with targeting & PathLock™
20
+ link = lsh.links.create({
21
+ "targetUrl": "https://my-store.com/summer-sale",
22
+ "slug": "summer-2026",
23
+ "geoTargeting": {
24
+ "FR": "https://my-store.fr/summer-sale",
25
+ "US": "https://my-store.com/us-sale",
26
+ },
27
+ "deviceTargeting": {
28
+ "ios": "https://apps.apple.com/app/id123456789",
29
+ "android": "https://play.google.com/store/apps/details?id=com.store",
30
+ },
31
+ "pixels": ["px_meta_main", "px_tiktok_main"],
32
+ })
33
+ print("Short URL:", link["shortUrl"])
34
+
35
+ # 2. Track a conversion
36
+ lsh.track.conversion(
37
+ event_name="purchase",
38
+ amount=49.99,
39
+ currency="EUR",
40
+ link_id=link["id"],
41
+ click_id="clk_abc123",
42
+ customer={
43
+ "id": "usr_123",
44
+ "email": "alex@example.com",
45
+ "name": "Alex Johnson",
46
+ "avatarUrl": "https://example.com/avatars/alex.jpg",
47
+ },
48
+ )
49
+
50
+ # 3. Query real-time analytics
51
+ stats = lsh.analytics.dashboard(link_id=link["id"])
52
+ print("Clicks:", stats["totalClicks"], "Revenue:", stats["trackedRevenue"])
53
+ ```
54
+
55
+ ## Available Modules
56
+
57
+ | Module | Methods |
58
+ | :--- | :--- |
59
+ | `lsh.links` | `create`, `list`, `get`, `update`, `delete` |
60
+ | `lsh.track` | `conversion`, `list` |
61
+ | `lsh.analytics` | `dashboard`, `top`, `links`, `export_csv` |
62
+ | `lsh.domains` | `create`, `list`, `get`, `verify`, `delete` |
63
+ | `lsh.webhooks` | `list`, `get`, `update`, `delete` *(creation via Dashboard only)* |
64
+ | `lsh.pixels` | `list`, `get`, `update`, `delete` *(creation via Dashboard only)* |
65
+ | `lsh.notifications` / `lsh.targets` | `list`, `get` *(read-only)* |
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24.0"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "lshorter"
7
+ version = "1.0.0"
8
+ description = "Official Python SDK for LShorter — Ultra-fast Edge URL Shortener, Dynamic Routing, PathLock™, and Conversion Tracking."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.9"
12
+ authors = [
13
+ { name = "KONVELBO Samuel" }
14
+ ]
15
+ keywords = [
16
+ "lshorter",
17
+ "url-shortener",
18
+ "short-link",
19
+ "edge-redirect",
20
+ "analytics",
21
+ "conversion-tracking",
22
+ "pathlock",
23
+ ]
24
+ classifiers = [
25
+ "Development Status :: 5 - Production/Stable",
26
+ "Intended Audience :: Developers",
27
+ "License :: OSI Approved :: MIT License",
28
+ "Programming Language :: Python :: 3",
29
+ "Programming Language :: Python :: 3.9",
30
+ "Programming Language :: Python :: 3.10",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Programming Language :: Python :: 3.13",
34
+ "Typing :: Typed",
35
+ ]
36
+ dependencies = []
37
+
38
+ [project.urls]
39
+ Homepage = "https://lsho.cc"
40
+ Documentation = "https://lsho.cc/docs"
41
+ Repository = "https://github.com/Konvelbo/LShorter-api"
42
+ Issues = "https://github.com/Konvelbo/LShorter-api/issues"
43
+
44
+ [tool.hatch.build.targets.wheel]
45
+ packages = ["src/lshorter"]
@@ -0,0 +1,5 @@
1
+ from .client import LShorter, QuickLink
2
+ from .errors import LShorterError, QuickLinkError
3
+
4
+ __all__ = ["LShorter", "QuickLink", "LShorterError", "QuickLinkError"]
5
+ __version__ = "1.0.0"
@@ -0,0 +1,394 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import urllib.error
5
+ import urllib.parse
6
+ import urllib.request
7
+ from typing import Any, Dict, List, Mapping, Optional, Union
8
+
9
+ from .errors import LShorterError
10
+
11
+ DEFAULT_BASE_URL = "https://lshorter-api.fiatechnologiecam.workers.dev"
12
+
13
+
14
+ def _normalize_base_url(base_url: Optional[str]) -> str:
15
+ base = (base_url or DEFAULT_BASE_URL).rstrip("/")
16
+ if base in ("https://lsho.cc", "https://api.lsho.cc"):
17
+ return DEFAULT_BASE_URL
18
+ return base
19
+
20
+
21
+ class HttpClient:
22
+ """Zero-dependency HTTP client backed by Python's standard library."""
23
+
24
+ def __init__(
25
+ self,
26
+ api_key: str,
27
+ base_url: Optional[str] = None,
28
+ timeout: float = 15.0,
29
+ ) -> None:
30
+ if not api_key or not api_key.strip():
31
+ raise ValueError("api_key is required")
32
+ self.api_key = api_key.strip()
33
+ self.base_url = _normalize_base_url(base_url)
34
+ self.timeout = timeout
35
+
36
+ def _build_url(
37
+ self,
38
+ path: str,
39
+ params: Optional[Mapping[str, Any]] = None,
40
+ ) -> str:
41
+ url = f"{self.base_url}{path}"
42
+ if params:
43
+ filtered = {k: str(v) for k, v in params.items() if v is not None}
44
+ if filtered:
45
+ url = f"{url}?{urllib.parse.urlencode(filtered)}"
46
+ return url
47
+
48
+ def request(
49
+ self,
50
+ method: str,
51
+ path: str,
52
+ body: Optional[Mapping[str, Any]] = None,
53
+ params: Optional[Mapping[str, Any]] = None,
54
+ ) -> Any:
55
+ url = self._build_url(path, params)
56
+ headers: Dict[str, str] = {
57
+ "Authorization": f"Bearer {self.api_key}",
58
+ "Accept": "application/json",
59
+ "User-Agent": "lshorter-python/1.0.0",
60
+ }
61
+ data: Optional[bytes] = None
62
+ if body is not None:
63
+ headers["Content-Type"] = "application/json"
64
+ data = json.dumps(body).encode("utf-8")
65
+
66
+ req = urllib.request.Request(url, data=data, headers=headers, method=method)
67
+ try:
68
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
69
+ status = resp.status
70
+ raw = resp.read().decode("utf-8")
71
+ except urllib.error.HTTPError as exc:
72
+ status = exc.code
73
+ raw = exc.read().decode("utf-8", errors="replace")
74
+ try:
75
+ err_json = json.loads(raw)
76
+ raise LShorterError(
77
+ err_json.get("error") or f"HTTP {status}",
78
+ status=status,
79
+ code=err_json.get("code"),
80
+ ) from exc
81
+ except LShorterError:
82
+ raise
83
+ except Exception:
84
+ raise LShorterError(raw or f"HTTP {status}", status=status) from exc
85
+ except urllib.error.URLError as exc:
86
+ raise LShorterError(f"Network error: {exc.reason}", status=0, code="NETWORK_ERROR") from exc
87
+
88
+ try:
89
+ payload = json.loads(raw) if raw else {}
90
+ except json.JSONDecodeError as exc:
91
+ raise LShorterError(f"Invalid JSON response: {exc}", status=status) from exc
92
+
93
+ if not isinstance(payload, dict) or not payload.get("success", False):
94
+ msg = payload.get("error") if isinstance(payload, dict) else None
95
+ code = payload.get("code") if isinstance(payload, dict) else None
96
+ raise LShorterError(msg or f"HTTP {status}", status=status, code=code)
97
+
98
+ if "pagination" in payload and isinstance(payload.get("data"), list):
99
+ return {
100
+ "data": payload["data"],
101
+ "pagination": payload["pagination"],
102
+ }
103
+ return payload.get("data")
104
+
105
+ def request_text(
106
+ self,
107
+ method: str,
108
+ path: str,
109
+ params: Optional[Mapping[str, Any]] = None,
110
+ ) -> str:
111
+ url = self._build_url(path, params)
112
+ req = urllib.request.Request(
113
+ url,
114
+ headers={
115
+ "Authorization": f"Bearer {self.api_key}",
116
+ "User-Agent": "lshorter-python/1.0.0",
117
+ },
118
+ method=method,
119
+ )
120
+ try:
121
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
122
+ return resp.read().decode("utf-8")
123
+ except urllib.error.HTTPError as exc:
124
+ status = exc.code
125
+ raw = exc.read().decode("utf-8", errors="replace")
126
+ try:
127
+ err_json = json.loads(raw)
128
+ raise LShorterError(
129
+ err_json.get("error") or f"HTTP {status}",
130
+ status=status,
131
+ code=err_json.get("code"),
132
+ ) from exc
133
+ except LShorterError:
134
+ raise
135
+ except Exception:
136
+ raise LShorterError(raw or f"HTTP {status}", status=status) from exc
137
+ except urllib.error.URLError as exc:
138
+ raise LShorterError(f"Network error: {exc.reason}", status=0, code="NETWORK_ERROR") from exc
139
+
140
+ def get(self, path: str, params: Optional[Mapping[str, Any]] = None) -> Any:
141
+ return self.request("GET", path, params=params)
142
+
143
+ def post(self, path: str, body: Mapping[str, Any]) -> Any:
144
+ return self.request("POST", path, body=body)
145
+
146
+ def patch(self, path: str, body: Mapping[str, Any]) -> Any:
147
+ return self.request("PATCH", path, body=body)
148
+
149
+ def delete(self, path: str) -> Any:
150
+ return self.request("DELETE", path)
151
+
152
+
153
+ class LinksResource:
154
+ def __init__(self, http: HttpClient) -> None:
155
+ self._http = http
156
+
157
+ def create(self, payload: Mapping[str, Any]) -> Dict[str, Any]:
158
+ return self._http.post("/api/v1/links", payload)
159
+
160
+ def list(
161
+ self,
162
+ *,
163
+ page: Optional[int] = None,
164
+ limit: Optional[int] = None,
165
+ ) -> Dict[str, Any]:
166
+ return self._http.get("/api/v1/links", {"page": page, "limit": limit})
167
+
168
+ def get(self, link_id: str) -> Dict[str, Any]:
169
+ return self._http.get(f"/api/v1/links/{urllib.parse.quote(link_id, safe='')}")
170
+
171
+ def update(self, link_id: str, payload: Mapping[str, Any]) -> Dict[str, Any]:
172
+ return self._http.patch(f"/api/v1/links/{urllib.parse.quote(link_id, safe='')}", payload)
173
+
174
+ def delete(self, link_id: str) -> Dict[str, Any]:
175
+ return self._http.delete(f"/api/v1/links/{urllib.parse.quote(link_id, safe='')}")
176
+
177
+
178
+ class TrackResource:
179
+ def __init__(self, http: HttpClient) -> None:
180
+ self._http = http
181
+
182
+ def conversion(
183
+ self,
184
+ *,
185
+ event_name: str,
186
+ link_id: str,
187
+ amount: float = 0.0,
188
+ currency: str = "EUR",
189
+ click_id: Optional[str] = None,
190
+ customer: Optional[Mapping[str, Any]] = None,
191
+ customer_id: Optional[str] = None,
192
+ customer_email: Optional[str] = None,
193
+ customer_name: Optional[str] = None,
194
+ customer_avatar: Optional[str] = None,
195
+ ) -> Dict[str, Any]:
196
+ cust = customer or {}
197
+ payload: Dict[str, Any] = {
198
+ "eventName": event_name,
199
+ "amount": amount,
200
+ "currency": currency,
201
+ "customerId": customer_id or cust.get("id") or "usr_anon",
202
+ "linkId": link_id,
203
+ "clickId": click_id,
204
+ }
205
+ email = customer_email or cust.get("email")
206
+ name = customer_name or cust.get("name") or cust.get("fullName")
207
+ avatar = customer_avatar or cust.get("avatarUrl") or cust.get("avatar")
208
+ if email is not None:
209
+ payload["customerEmail"] = email
210
+ if name is not None:
211
+ payload["customerName"] = name
212
+ if avatar is not None:
213
+ payload["customerAvatar"] = avatar
214
+ return self._http.post("/api/v1/track", payload)
215
+
216
+ def list(
217
+ self,
218
+ *,
219
+ page: Optional[int] = None,
220
+ limit: Optional[int] = None,
221
+ link_id: Optional[str] = None,
222
+ ) -> Dict[str, Any]:
223
+ return self._http.get(
224
+ "/api/v1/track",
225
+ {"page": page, "limit": limit, "linkId": link_id},
226
+ )
227
+
228
+
229
+ class AnalyticsResource:
230
+ def __init__(self, http: HttpClient) -> None:
231
+ self._http = http
232
+
233
+ def dashboard(
234
+ self,
235
+ *,
236
+ link_id: Optional[str] = None,
237
+ from_date: Optional[str] = None,
238
+ to_date: Optional[str] = None,
239
+ ) -> Dict[str, Any]:
240
+ return self._http.get(
241
+ "/api/v1/analytics",
242
+ {"linkId": link_id, "from": from_date, "to": to_date},
243
+ )
244
+
245
+ def top(self, *, link_id: Optional[str] = None) -> Dict[str, Any]:
246
+ return self._http.get("/api/v1/analytics/top", {"linkId": link_id})
247
+
248
+ def export_csv(self, *, link_id: Optional[str] = None) -> str:
249
+ return self._http.request_text("GET", "/api/v1/analytics/export", {"linkId": link_id})
250
+
251
+ def links(self, *, limit: Optional[int] = None) -> List[Any]:
252
+ return self._http.get("/api/v1/analytics/links", {"limit": limit})
253
+
254
+
255
+ class DomainsResource:
256
+ def __init__(self, http: HttpClient) -> None:
257
+ self._http = http
258
+
259
+ def create(self, domain: str) -> Dict[str, Any]:
260
+ return self._http.post("/api/v1/domains", {"domain": domain})
261
+
262
+ def list(self) -> List[Any]:
263
+ return self._http.get("/api/v1/domains")
264
+
265
+ def get(self, domain_id: str) -> Dict[str, Any]:
266
+ return self._http.get(f"/api/v1/domains/{urllib.parse.quote(domain_id, safe='')}")
267
+
268
+ def verify(self, domain_id: str) -> Dict[str, Any]:
269
+ return self._http.post(
270
+ f"/api/v1/domains/{urllib.parse.quote(domain_id, safe='')}/verify",
271
+ {},
272
+ )
273
+
274
+ def delete(self, domain_id: str) -> Dict[str, Any]:
275
+ return self._http.delete(f"/api/v1/domains/{urllib.parse.quote(domain_id, safe='')}")
276
+
277
+
278
+ class WebhooksResource:
279
+ def __init__(self, http: HttpClient) -> None:
280
+ self._http = http
281
+
282
+ def create(self, *_args: Any, **_kwargs: Any) -> None:
283
+ raise LShorterError(
284
+ "Creating webhooks via the SDK is disabled. Please configure your webhooks from the LShorter Dashboard (Settings > Webhooks).",
285
+ status=403,
286
+ )
287
+
288
+ def list(self) -> List[Dict[str, Any]]:
289
+ res = self._http.get("/api/v1/webhooks")
290
+ if isinstance(res, dict) and isinstance(res.get("webhooks"), list):
291
+ return res["webhooks"]
292
+ return res if isinstance(res, list) else []
293
+
294
+ def get(self, webhook_id: str) -> Dict[str, Any]:
295
+ res = self._http.get(f"/api/v1/webhooks/{urllib.parse.quote(webhook_id, safe='')}")
296
+ return res["webhook"] if isinstance(res, dict) and "webhook" in res else res
297
+
298
+ def update(self, webhook_id: str, payload: Mapping[str, Any]) -> Dict[str, Any]:
299
+ res = self._http.patch(
300
+ f"/api/v1/webhooks/{urllib.parse.quote(webhook_id, safe='')}",
301
+ payload,
302
+ )
303
+ return res["webhook"] if isinstance(res, dict) and "webhook" in res else res
304
+
305
+ def delete(self, webhook_id: str) -> Dict[str, Any]:
306
+ return self._http.delete(f"/api/v1/webhooks/{urllib.parse.quote(webhook_id, safe='')}")
307
+
308
+
309
+ class PixelsResource:
310
+ def __init__(self, http: HttpClient) -> None:
311
+ self._http = http
312
+
313
+ def create(self, *_args: Any, **_kwargs: Any) -> None:
314
+ raise LShorterError(
315
+ "Creating retargeting pixels via the SDK is disabled. Please register your pixels from the LShorter Dashboard (Settings > Retargeting Pixels).",
316
+ status=403,
317
+ )
318
+
319
+ def list(self) -> List[Dict[str, Any]]:
320
+ res = self._http.get("/api/v1/pixels")
321
+ if isinstance(res, dict) and isinstance(res.get("pixels"), list):
322
+ return res["pixels"]
323
+ return res if isinstance(res, list) else []
324
+
325
+ def get(self, pixel_id: str) -> Dict[str, Any]:
326
+ res = self._http.get(f"/api/v1/pixels/{urllib.parse.quote(pixel_id, safe='')}")
327
+ return res["pixel"] if isinstance(res, dict) and "pixel" in res else res
328
+
329
+ def update(self, pixel_id: str, payload: Mapping[str, Any]) -> Dict[str, Any]:
330
+ res = self._http.patch(
331
+ f"/api/v1/pixels/{urllib.parse.quote(pixel_id, safe='')}",
332
+ payload,
333
+ )
334
+ return res["pixel"] if isinstance(res, dict) and "pixel" in res else res
335
+
336
+ def delete(self, pixel_id: str) -> Dict[str, Any]:
337
+ return self._http.delete(f"/api/v1/pixels/{urllib.parse.quote(pixel_id, safe='')}")
338
+
339
+
340
+ class NotificationsResource:
341
+ def __init__(self, http: HttpClient) -> None:
342
+ self._http = http
343
+
344
+ def create(self, *_args: Any, **_kwargs: Any) -> None:
345
+ raise LShorterError(
346
+ "Creating target alerts and notifications via the SDK is disabled. Notifications must be configured directly from the LShorter Dashboard (Settings > Notifications).",
347
+ status=403,
348
+ )
349
+
350
+ create_target = create
351
+
352
+ def list(self) -> List[Dict[str, Any]]:
353
+ res = self._http.get("/api/v1/targets")
354
+ if isinstance(res, list):
355
+ return res
356
+ if isinstance(res, dict) and isinstance(res.get("data"), list):
357
+ return res["data"]
358
+ return []
359
+
360
+ def get(self, alert_id: str) -> Dict[str, Any]:
361
+ for alert in self.list():
362
+ if alert.get("id") == alert_id:
363
+ return alert
364
+ raise LShorterError("Target alert not found", status=404)
365
+
366
+
367
+ class LShorter:
368
+ """Official LShorter Python SDK client."""
369
+
370
+ def __init__(
371
+ self,
372
+ api_key: str,
373
+ *,
374
+ base_url: Optional[str] = None,
375
+ timeout: float = 15.0,
376
+ ) -> None:
377
+ self._http = HttpClient(api_key=api_key, base_url=base_url, timeout=timeout)
378
+ self.links = LinksResource(self._http)
379
+ self.track = TrackResource(self._http)
380
+ self.analytics = AnalyticsResource(self._http)
381
+ self.domains = DomainsResource(self._http)
382
+ self.webhooks = WebhooksResource(self._http)
383
+ self.pixels = PixelsResource(self._http)
384
+ self.notifications = NotificationsResource(self._http)
385
+ self.targets = self.notifications
386
+
387
+ def __enter__(self) -> "LShorter":
388
+ return self
389
+
390
+ def __exit__(self, *_args: Union[object, None]) -> None:
391
+ return None
392
+
393
+
394
+ QuickLink = LShorter
@@ -0,0 +1,24 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Optional
4
+
5
+
6
+ class LShorterError(Exception):
7
+ """Typed error raised when the LShorter API returns a non-2xx response or error payload."""
8
+
9
+ def __init__(
10
+ self,
11
+ message: str,
12
+ status: int = 500,
13
+ code: Optional[str] = None,
14
+ ) -> None:
15
+ super().__init__(message)
16
+ self.message = message
17
+ self.status = status
18
+ self.code = code
19
+
20
+ def __repr__(self) -> str:
21
+ return f"LShorterError(status={self.status!r}, code={self.code!r}, message={self.message!r})"
22
+
23
+
24
+ QuickLinkError = LShorterError
File without changes
@@ -0,0 +1,202 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import sys
5
+ import threading
6
+ import unittest
7
+ from http.server import BaseHTTPRequestHandler, HTTPServer
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Tuple
10
+
11
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
12
+
13
+ from lshorter import LShorter, LShorterError # noqa: E402
14
+
15
+
16
+ class _MockApiState:
17
+ requests: List[Tuple[str, str, str, Any]] = []
18
+
19
+
20
+ class _MockHandler(BaseHTTPRequestHandler):
21
+ def log_message(self, format: str, *args: Any) -> None:
22
+ return
23
+
24
+ def _read_json(self) -> Any:
25
+ length = int(self.headers.get("Content-Length", "0"))
26
+ if length == 0:
27
+ return None
28
+ return json.loads(self.rfile.read(length).decode("utf-8"))
29
+
30
+ def _send_json(self, status: int, body: Dict[str, Any]) -> None:
31
+ raw = json.dumps(body).encode("utf-8")
32
+ self.send_response(status)
33
+ self.send_header("Content-Type", "application/json")
34
+ self.send_header("Content-Length", str(len(raw)))
35
+ self.end_headers()
36
+ self.wfile.write(raw)
37
+
38
+ def _dispatch(self, method: str) -> None:
39
+ auth = self.headers.get("Authorization", "")
40
+ body = self._read_json()
41
+ _MockApiState.requests.append((method, self.path, auth, body))
42
+
43
+ if auth != "Bearer lsh_live_test":
44
+ return self._send_json(401, {"success": False, "error": "Unauthorized", "code": "UNAUTHORIZED"})
45
+
46
+ if method == "POST" and self.path == "/api/v1/links":
47
+ return self._send_json(
48
+ 201,
49
+ {
50
+ "success": True,
51
+ "data": {
52
+ "id": "link_01",
53
+ "slug": body.get("slug", "auto"),
54
+ "shortUrl": f"https://lsho.cc/{body.get('slug', 'auto')}",
55
+ "targetUrl": body["targetUrl"],
56
+ },
57
+ },
58
+ )
59
+ if method == "GET" and self.path.startswith("/api/v1/links?"):
60
+ return self._send_json(
61
+ 200,
62
+ {
63
+ "success": True,
64
+ "data": [{"id": "link_01", "slug": "summer-2026"}],
65
+ "pagination": {"page": 1, "limit": 20, "total": 1},
66
+ },
67
+ )
68
+ if method == "POST" and self.path == "/api/v1/track":
69
+ return self._send_json(
70
+ 201,
71
+ {
72
+ "success": True,
73
+ "data": {
74
+ "id": "conv_01",
75
+ "eventName": body["eventName"],
76
+ "amount": body["amount"],
77
+ "customerEmail": body.get("customerEmail"),
78
+ },
79
+ },
80
+ )
81
+ if method == "GET" and self.path.startswith("/api/v1/analytics/export"):
82
+ csv_raw = b"id,amount\nconv_01,49.99\n"
83
+ self.send_response(200)
84
+ self.send_header("Content-Type", "text/csv")
85
+ self.send_header("Content-Length", str(len(csv_raw)))
86
+ self.end_headers()
87
+ self.wfile.write(csv_raw)
88
+ return
89
+ if method == "GET" and self.path.startswith("/api/v1/analytics"):
90
+ return self._send_json(200, {"success": True, "data": {"totalClicks": 120, "trackedRevenue": 499.0}})
91
+ if method == "GET" and self.path == "/api/v1/pixels":
92
+ return self._send_json(
93
+ 200,
94
+ {"success": True, "data": {"pixels": [{"id": "px_1", "platform": "pinterest", "pixelId": "26123"}]}},
95
+ )
96
+ if method == "GET" and self.path == "/api/v1/webhooks":
97
+ return self._send_json(
98
+ 200,
99
+ {"success": True, "data": {"webhooks": [{"id": "wh_1", "url": "https://example.com/hook"}]}},
100
+ )
101
+ if method == "GET" and self.path == "/api/v1/targets":
102
+ return self._send_json(
103
+ 200,
104
+ {"success": True, "data": [{"id": "tgt_1", "metricType": "clicks", "targetValue": 500}]},
105
+ )
106
+ if method == "POST" and self.path == "/api/v1/domains/dom_1/verify":
107
+ return self._send_json(
108
+ 200,
109
+ {"success": True, "data": {"id": "dom_1", "domain": "go.brand.com", "status": "active", "message": "Verified"}},
110
+ )
111
+ return self._send_json(404, {"success": False, "error": "Not found", "code": "NOT_FOUND"})
112
+
113
+ def do_GET(self) -> None:
114
+ self._dispatch("GET")
115
+
116
+ def do_POST(self) -> None:
117
+ self._dispatch("POST")
118
+
119
+ def do_PATCH(self) -> None:
120
+ self._dispatch("PATCH")
121
+
122
+ def do_DELETE(self) -> None:
123
+ self._dispatch("DELETE")
124
+
125
+
126
+ class LShorterPythonSdkTests(unittest.TestCase):
127
+ server: HTTPServer
128
+ thread: threading.Thread
129
+ base_url: str
130
+
131
+ @classmethod
132
+ def setUpClass(cls) -> None:
133
+ cls.server = HTTPServer(("127.0.0.1", 0), _MockHandler)
134
+ port = cls.server.server_address[1]
135
+ cls.base_url = f"http://127.0.0.1:{port}"
136
+ cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
137
+ cls.thread.start()
138
+
139
+ @classmethod
140
+ def tearDownClass(cls) -> None:
141
+ cls.server.shutdown()
142
+ cls.server.server_close()
143
+
144
+ def setUp(self) -> None:
145
+ _MockApiState.requests.clear()
146
+ self.client = LShorter(api_key="lsh_live_test", base_url=self.base_url)
147
+
148
+ def test_links_create_and_list(self) -> None:
149
+ created = self.client.links.create({"targetUrl": "https://example.com/offer", "slug": "summer-2026"})
150
+ self.assertEqual(created["id"], "link_01")
151
+ self.assertEqual(created["shortUrl"], "https://lsho.cc/summer-2026")
152
+
153
+ listed = self.client.links.list(page=1, limit=20)
154
+ self.assertEqual(listed["pagination"]["total"], 1)
155
+ self.assertEqual(len(listed["data"]), 1)
156
+
157
+ def test_track_conversion_maps_customer(self) -> None:
158
+ conv = self.client.track.conversion(
159
+ event_name="purchase",
160
+ amount=49.99,
161
+ currency="EUR",
162
+ link_id="link_01",
163
+ customer={"id": "u1", "email": "alice@example.com", "name": "Alice"},
164
+ )
165
+ self.assertEqual(conv["id"], "conv_01")
166
+ self.assertEqual(conv["customerEmail"], "alice@example.com")
167
+
168
+ def test_analytics_and_csv_export(self) -> None:
169
+ dash = self.client.analytics.dashboard(link_id="link_01")
170
+ self.assertEqual(dash["totalClicks"], 120)
171
+ csv_data = self.client.analytics.export_csv(link_id="link_01")
172
+ self.assertIn("conv_01,49.99", csv_data)
173
+
174
+ def test_domains_pixels_webhooks_notifications(self) -> None:
175
+ verified = self.client.domains.verify("dom_1")
176
+ self.assertEqual(verified["status"], "active")
177
+
178
+ pixels = self.client.pixels.list()
179
+ self.assertEqual(pixels[0]["platform"], "pinterest")
180
+
181
+ webhooks = self.client.webhooks.list()
182
+ self.assertEqual(webhooks[0]["id"], "wh_1")
183
+
184
+ target = self.client.targets.get("tgt_1")
185
+ self.assertEqual(target["targetValue"], 500)
186
+
187
+ def test_dashboard_only_creates_raise_403(self) -> None:
188
+ for fn in (self.client.webhooks.create, self.client.pixels.create, self.client.notifications.create):
189
+ with self.assertRaises(LShorterError) as ctx:
190
+ fn()
191
+ self.assertEqual(ctx.exception.status, 403)
192
+
193
+ def test_unauthorized_raises_typed_error(self) -> None:
194
+ bad = LShorter(api_key="lsh_live_wrong", base_url=self.base_url)
195
+ with self.assertRaises(LShorterError) as ctx:
196
+ bad.links.list()
197
+ self.assertEqual(ctx.exception.status, 401)
198
+ self.assertEqual(ctx.exception.code, "UNAUTHORIZED")
199
+
200
+
201
+ if __name__ == "__main__":
202
+ unittest.main()