xtikapi 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.
- xtikapi-0.1.0/.gitignore +8 -0
- xtikapi-0.1.0/PKG-INFO +41 -0
- xtikapi-0.1.0/README.md +17 -0
- xtikapi-0.1.0/pyproject.toml +45 -0
- xtikapi-0.1.0/src/xtikapi/__init__.py +6 -0
- xtikapi-0.1.0/src/xtikapi/client.py +368 -0
xtikapi-0.1.0/.gitignore
ADDED
xtikapi-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: xtikapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK (sync & async) for XTikAPI — 19 social media platforms, 229 normalized endpoints, pay per call.
|
|
5
|
+
Project-URL: Homepage, https://xtikapi.com
|
|
6
|
+
Project-URL: Documentation, https://xtikapi.com/apis
|
|
7
|
+
Project-URL: Repository, https://github.com/xtikapi/xtikapi-python
|
|
8
|
+
Project-URL: Issues, https://github.com/xtikapi/xtikapi-python/issues
|
|
9
|
+
Author-email: XTikAPI <support@xtikapi.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
Keywords: douyin,mcp,reddit,social-media-api,tiktok,twitter,wechat,xiaohongshu,xtikapi,youtube
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Requires-Dist: httpx>=0.27.0
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# xtikapi
|
|
26
|
+
|
|
27
|
+
Official Python SDK (sync & async) for [XTikAPI](https://xtikapi.com) — 19 social media platforms, 229 normalized endpoints, pay per call ($0.002–$0.04).
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install xtikapi
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from xtikapi import XTikClient
|
|
35
|
+
|
|
36
|
+
client = XTikClient(api_key="dk_your_key")
|
|
37
|
+
res = client.call("tiktok.videos.search", {"keyword": "ai agents"})
|
|
38
|
+
print(res["data"]["items"])
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Full docs: [https://xtikapi.com/apis](https://xtikapi.com/apis)
|
xtikapi-0.1.0/README.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# xtikapi
|
|
2
|
+
|
|
3
|
+
Official Python SDK (sync & async) for [XTikAPI](https://xtikapi.com) — 19 social media platforms, 229 normalized endpoints, pay per call ($0.002–$0.04).
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install xtikapi
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from xtikapi import XTikClient
|
|
11
|
+
|
|
12
|
+
client = XTikClient(api_key="dk_your_key")
|
|
13
|
+
res = client.call("tiktok.videos.search", {"keyword": "ai agents"})
|
|
14
|
+
print(res["data"]["items"])
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Full docs: [https://xtikapi.com/apis](https://xtikapi.com/apis)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25.0"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "xtikapi"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Official Python SDK (sync & async) for XTikAPI — 19 social media platforms, 229 normalized endpoints, pay per call."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
authors = [{ name = "XTikAPI", email = "support@xtikapi.com" }]
|
|
13
|
+
keywords = [
|
|
14
|
+
"xtikapi",
|
|
15
|
+
"social-media-api",
|
|
16
|
+
"douyin",
|
|
17
|
+
"xiaohongshu",
|
|
18
|
+
"tiktok",
|
|
19
|
+
"wechat",
|
|
20
|
+
"youtube",
|
|
21
|
+
"twitter",
|
|
22
|
+
"reddit",
|
|
23
|
+
"mcp",
|
|
24
|
+
]
|
|
25
|
+
classifiers = [
|
|
26
|
+
"Development Status :: 4 - Beta",
|
|
27
|
+
"Intended Audience :: Developers",
|
|
28
|
+
"License :: OSI Approved :: MIT License",
|
|
29
|
+
"Programming Language :: Python :: 3",
|
|
30
|
+
"Programming Language :: Python :: 3.9",
|
|
31
|
+
"Programming Language :: Python :: 3.10",
|
|
32
|
+
"Programming Language :: Python :: 3.11",
|
|
33
|
+
"Programming Language :: Python :: 3.12",
|
|
34
|
+
"Programming Language :: Python :: 3.13",
|
|
35
|
+
]
|
|
36
|
+
dependencies = ["httpx>=0.27.0"]
|
|
37
|
+
|
|
38
|
+
[project.urls]
|
|
39
|
+
Homepage = "https://xtikapi.com"
|
|
40
|
+
Documentation = "https://xtikapi.com/apis"
|
|
41
|
+
Repository = "https://github.com/xtikapi/xtikapi-python"
|
|
42
|
+
Issues = "https://github.com/xtikapi/xtikapi-python/issues"
|
|
43
|
+
|
|
44
|
+
[tool.hatch.build.targets.wheel]
|
|
45
|
+
packages = ["src/xtikapi"]
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional
|
|
6
|
+
from urllib.parse import quote
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
DEFAULT_BASE_URL = "https://xtikapi.com"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class XTikError(Exception):
|
|
14
|
+
"""Structured error returned by the XTikAPI gateway."""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
message: str,
|
|
19
|
+
*,
|
|
20
|
+
code: str,
|
|
21
|
+
status: int,
|
|
22
|
+
charged: bool = False,
|
|
23
|
+
retry: bool = False,
|
|
24
|
+
request_id: Optional[str] = None,
|
|
25
|
+
retry_after_seconds: Optional[int] = None,
|
|
26
|
+
) -> None:
|
|
27
|
+
super().__init__(message)
|
|
28
|
+
self.code = code
|
|
29
|
+
self.status = status
|
|
30
|
+
self.charged = charged
|
|
31
|
+
self.retry = retry
|
|
32
|
+
self.request_id = request_id
|
|
33
|
+
self.retry_after_seconds = retry_after_seconds
|
|
34
|
+
|
|
35
|
+
def __repr__(self) -> str:
|
|
36
|
+
return f"XTikError(code={self.code!r}, status={self.status}, charged={self.charged}, message={str(self)!r})"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _clean_params(params: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
|
40
|
+
if not params:
|
|
41
|
+
return {}
|
|
42
|
+
return {k: v for k, v in params.items() if v is not None and v != ""}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _parse_error(response: httpx.Response) -> XTikError:
|
|
46
|
+
try:
|
|
47
|
+
payload = response.json()
|
|
48
|
+
except Exception:
|
|
49
|
+
payload = {}
|
|
50
|
+
err = payload.get("error") if isinstance(payload, dict) else {}
|
|
51
|
+
meta = payload.get("meta") if isinstance(payload, dict) else {}
|
|
52
|
+
if not isinstance(err, dict):
|
|
53
|
+
err = {}
|
|
54
|
+
if not isinstance(meta, dict):
|
|
55
|
+
meta = {}
|
|
56
|
+
return XTikError(
|
|
57
|
+
err.get("message") or response.text or f"Request failed with HTTP {response.status_code}",
|
|
58
|
+
code=err.get("code") or f"http_{response.status_code}",
|
|
59
|
+
status=response.status_code,
|
|
60
|
+
charged=bool(err.get("charged", False)),
|
|
61
|
+
retry=bool(err.get("retry", response.status_code >= 500)),
|
|
62
|
+
request_id=meta.get("request_id"),
|
|
63
|
+
retry_after_seconds=err.get("retry_after_seconds"),
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _score_endpoints(endpoints: List[Dict[str, Any]], query: str, platform: Optional[str], limit: int) -> List[Dict[str, Any]]:
|
|
68
|
+
terms = [t for t in re.split(r"[^a-z0-9\u4e00-\u9fff]+", query.lower()) if t]
|
|
69
|
+
filtered = [e for e in endpoints if not platform or e.get("platform") == platform]
|
|
70
|
+
if not terms:
|
|
71
|
+
return filtered[:limit]
|
|
72
|
+
scored = []
|
|
73
|
+
for ep in filtered:
|
|
74
|
+
hay = " ".join(
|
|
75
|
+
str(ep.get(k, "")) for k in ("id", "platform", "resource", "action", "summary", "description")
|
|
76
|
+
).lower()
|
|
77
|
+
score = 0
|
|
78
|
+
for t in terms:
|
|
79
|
+
if ep.get("platform") == t:
|
|
80
|
+
score += 6
|
|
81
|
+
elif ep.get("resource") == t or ep.get("action") == t:
|
|
82
|
+
score += 4
|
|
83
|
+
elif t in hay:
|
|
84
|
+
score += 2
|
|
85
|
+
if score > 0:
|
|
86
|
+
scored.append((score, ep))
|
|
87
|
+
scored.sort(key=lambda pair: pair[0], reverse=True)
|
|
88
|
+
return [ep for _, ep in scored[:limit]]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class XTikClient:
|
|
92
|
+
"""Synchronous client for XTikAPI (https://xtikapi.com)."""
|
|
93
|
+
|
|
94
|
+
def __init__(
|
|
95
|
+
self,
|
|
96
|
+
api_key: Optional[str] = None,
|
|
97
|
+
*,
|
|
98
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
99
|
+
timeout: float = 30.0,
|
|
100
|
+
client: Optional[httpx.Client] = None,
|
|
101
|
+
) -> None:
|
|
102
|
+
self.api_key = api_key if api_key is not None else os.environ.get("XTIKAPI_API_KEY")
|
|
103
|
+
self.base_url = base_url.rstrip("/")
|
|
104
|
+
self._owns_client = client is None
|
|
105
|
+
self._client = client or httpx.Client(
|
|
106
|
+
base_url=self.base_url,
|
|
107
|
+
timeout=timeout,
|
|
108
|
+
headers={"Accept": "application/json", "User-Agent": "xtikapi-python/0.1.0"},
|
|
109
|
+
)
|
|
110
|
+
self._catalog_cache: Dict[str, Dict[str, Any]] = {}
|
|
111
|
+
|
|
112
|
+
def close(self) -> None:
|
|
113
|
+
if self._owns_client:
|
|
114
|
+
self._client.close()
|
|
115
|
+
|
|
116
|
+
def __enter__(self) -> "XTikClient":
|
|
117
|
+
return self
|
|
118
|
+
|
|
119
|
+
def __exit__(self, *_: Any) -> None:
|
|
120
|
+
self.close()
|
|
121
|
+
|
|
122
|
+
def status(self) -> Dict[str, Any]:
|
|
123
|
+
"""Free public gateway status check."""
|
|
124
|
+
return self._request("GET", "/v1/status", auth=False)
|
|
125
|
+
|
|
126
|
+
def catalog(self, *, force_refresh: bool = False) -> List[Dict[str, Any]]:
|
|
127
|
+
"""Fetch all public endpoint specifications (free, cached in memory)."""
|
|
128
|
+
if self._catalog_cache and not force_refresh:
|
|
129
|
+
return list(self._catalog_cache.values())
|
|
130
|
+
data = self._request("GET", "/v1/catalog", auth=False)
|
|
131
|
+
endpoints = data.get("endpoints", [])
|
|
132
|
+
self._catalog_cache = {ep["id"]: ep for ep in endpoints}
|
|
133
|
+
return endpoints
|
|
134
|
+
|
|
135
|
+
def endpoint(self, endpoint_id: str) -> Dict[str, Any]:
|
|
136
|
+
"""Fetch one endpoint specification by ID (free)."""
|
|
137
|
+
if endpoint_id in self._catalog_cache:
|
|
138
|
+
return self._catalog_cache[endpoint_id]
|
|
139
|
+
spec = self._request("GET", f"/v1/catalog/{quote(endpoint_id, safe='')}", auth=False)
|
|
140
|
+
self._catalog_cache[endpoint_id] = spec
|
|
141
|
+
return spec
|
|
142
|
+
|
|
143
|
+
def search_catalog(self, query: str, *, platform: Optional[str] = None, limit: int = 10) -> List[Dict[str, Any]]:
|
|
144
|
+
"""Search all endpoints locally by keyword and optional platform (free)."""
|
|
145
|
+
return _score_endpoints(self.catalog(), query, platform, limit)
|
|
146
|
+
|
|
147
|
+
def call(
|
|
148
|
+
self,
|
|
149
|
+
endpoint_id: str,
|
|
150
|
+
params: Optional[Dict[str, Any]] = None,
|
|
151
|
+
*,
|
|
152
|
+
max_price_usd: Optional[float] = None,
|
|
153
|
+
idempotency_key: Optional[str] = None,
|
|
154
|
+
method: Optional[str] = None,
|
|
155
|
+
) -> Dict[str, Any]:
|
|
156
|
+
"""Call any XTikAPI endpoint by ID (e.g. `douyin.videos.search`)."""
|
|
157
|
+
clean = _clean_params(params)
|
|
158
|
+
if method is None:
|
|
159
|
+
spec = self.endpoint(endpoint_id)
|
|
160
|
+
http_method = spec["method"].upper()
|
|
161
|
+
path = spec["path"]
|
|
162
|
+
else:
|
|
163
|
+
http_method = method.upper()
|
|
164
|
+
parts = endpoint_id.split(".")
|
|
165
|
+
if len(parts) != 3:
|
|
166
|
+
raise XTikError(
|
|
167
|
+
f'Invalid endpoint id "{endpoint_id}". Expected "<platform>.<resource>.<action>".',
|
|
168
|
+
code="invalid_endpoint_id",
|
|
169
|
+
status=400,
|
|
170
|
+
)
|
|
171
|
+
path = f"/v1/{'/'.join(parts)}"
|
|
172
|
+
|
|
173
|
+
headers: Dict[str, str] = {}
|
|
174
|
+
if max_price_usd is not None:
|
|
175
|
+
headers["X-Max-Price"] = str(max_price_usd)
|
|
176
|
+
if idempotency_key:
|
|
177
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
178
|
+
|
|
179
|
+
if http_method == "GET":
|
|
180
|
+
return self._request("GET", path, auth=True, params=clean, headers=headers)
|
|
181
|
+
return self._request("POST", path, auth=True, json_body=clean, headers=headers)
|
|
182
|
+
|
|
183
|
+
def paginate(
|
|
184
|
+
self,
|
|
185
|
+
endpoint_id: str,
|
|
186
|
+
params: Optional[Dict[str, Any]] = None,
|
|
187
|
+
*,
|
|
188
|
+
max_pages: int = 5,
|
|
189
|
+
max_price_usd: Optional[float] = None,
|
|
190
|
+
idempotency_key: Optional[str] = None,
|
|
191
|
+
) -> Iterator[Dict[str, Any]]:
|
|
192
|
+
"""Iterate pages automatically by merging `data.next` until exhausted."""
|
|
193
|
+
current = dict(params or {})
|
|
194
|
+
for page_index in range(max_pages):
|
|
195
|
+
key = f"{idempotency_key}-p{page_index}" if idempotency_key else None
|
|
196
|
+
res = self.call(
|
|
197
|
+
endpoint_id,
|
|
198
|
+
current,
|
|
199
|
+
max_price_usd=max_price_usd,
|
|
200
|
+
idempotency_key=key,
|
|
201
|
+
)
|
|
202
|
+
yield res
|
|
203
|
+
next_cursor = (res.get("data") or {}).get("next")
|
|
204
|
+
if not isinstance(next_cursor, dict) or not next_cursor:
|
|
205
|
+
return
|
|
206
|
+
current.update(next_cursor)
|
|
207
|
+
|
|
208
|
+
def _request(
|
|
209
|
+
self,
|
|
210
|
+
method: str,
|
|
211
|
+
path: str,
|
|
212
|
+
*,
|
|
213
|
+
auth: bool,
|
|
214
|
+
params: Optional[Dict[str, Any]] = None,
|
|
215
|
+
json_body: Optional[Dict[str, Any]] = None,
|
|
216
|
+
headers: Optional[Dict[str, str]] = None,
|
|
217
|
+
) -> Dict[str, Any]:
|
|
218
|
+
req_headers = dict(headers or {})
|
|
219
|
+
if auth:
|
|
220
|
+
if not self.api_key:
|
|
221
|
+
raise XTikError(
|
|
222
|
+
"XTIKAPI_API_KEY is required. Pass api_key=... or set XTIKAPI_API_KEY. "
|
|
223
|
+
"Get a key at https://xtikapi.com/settings/apikeys",
|
|
224
|
+
code="unauthorized",
|
|
225
|
+
status=401,
|
|
226
|
+
)
|
|
227
|
+
req_headers["Authorization"] = f"Bearer {self.api_key}"
|
|
228
|
+
response = self._client.request(method, path, params=params, json=json_body, headers=req_headers)
|
|
229
|
+
if response.status_code >= 400:
|
|
230
|
+
raise _parse_error(response)
|
|
231
|
+
return response.json()
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
class AsyncXTikClient:
|
|
235
|
+
"""Asynchronous client for XTikAPI (https://xtikapi.com)."""
|
|
236
|
+
|
|
237
|
+
def __init__(
|
|
238
|
+
self,
|
|
239
|
+
api_key: Optional[str] = None,
|
|
240
|
+
*,
|
|
241
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
242
|
+
timeout: float = 30.0,
|
|
243
|
+
client: Optional[httpx.AsyncClient] = None,
|
|
244
|
+
) -> None:
|
|
245
|
+
self.api_key = api_key if api_key is not None else os.environ.get("XTIKAPI_API_KEY")
|
|
246
|
+
self.base_url = base_url.rstrip("/")
|
|
247
|
+
self._owns_client = client is None
|
|
248
|
+
self._client = client or httpx.AsyncClient(
|
|
249
|
+
base_url=self.base_url,
|
|
250
|
+
timeout=timeout,
|
|
251
|
+
headers={"Accept": "application/json", "User-Agent": "xtikapi-python/0.1.0"},
|
|
252
|
+
)
|
|
253
|
+
self._catalog_cache: Dict[str, Dict[str, Any]] = {}
|
|
254
|
+
|
|
255
|
+
async def aclose(self) -> None:
|
|
256
|
+
if self._owns_client:
|
|
257
|
+
await self._client.aclose()
|
|
258
|
+
|
|
259
|
+
async def __aenter__(self) -> "AsyncXTikClient":
|
|
260
|
+
return self
|
|
261
|
+
|
|
262
|
+
async def __aexit__(self, *_: Any) -> None:
|
|
263
|
+
await self.aclose()
|
|
264
|
+
|
|
265
|
+
async def status(self) -> Dict[str, Any]:
|
|
266
|
+
return await self._request("GET", "/v1/status", auth=False)
|
|
267
|
+
|
|
268
|
+
async def catalog(self, *, force_refresh: bool = False) -> List[Dict[str, Any]]:
|
|
269
|
+
if self._catalog_cache and not force_refresh:
|
|
270
|
+
return list(self._catalog_cache.values())
|
|
271
|
+
data = await self._request("GET", "/v1/catalog", auth=False)
|
|
272
|
+
endpoints = data.get("endpoints", [])
|
|
273
|
+
self._catalog_cache = {ep["id"]: ep for ep in endpoints}
|
|
274
|
+
return endpoints
|
|
275
|
+
|
|
276
|
+
async def endpoint(self, endpoint_id: str) -> Dict[str, Any]:
|
|
277
|
+
if endpoint_id in self._catalog_cache:
|
|
278
|
+
return self._catalog_cache[endpoint_id]
|
|
279
|
+
spec = await self._request("GET", f"/v1/catalog/{quote(endpoint_id, safe='')}", auth=False)
|
|
280
|
+
self._catalog_cache[endpoint_id] = spec
|
|
281
|
+
return spec
|
|
282
|
+
|
|
283
|
+
async def search_catalog(self, query: str, *, platform: Optional[str] = None, limit: int = 10) -> List[Dict[str, Any]]:
|
|
284
|
+
return _score_endpoints(await self.catalog(), query, platform, limit)
|
|
285
|
+
|
|
286
|
+
async def call(
|
|
287
|
+
self,
|
|
288
|
+
endpoint_id: str,
|
|
289
|
+
params: Optional[Dict[str, Any]] = None,
|
|
290
|
+
*,
|
|
291
|
+
max_price_usd: Optional[float] = None,
|
|
292
|
+
idempotency_key: Optional[str] = None,
|
|
293
|
+
method: Optional[str] = None,
|
|
294
|
+
) -> Dict[str, Any]:
|
|
295
|
+
clean = _clean_params(params)
|
|
296
|
+
if method is None:
|
|
297
|
+
spec = await self.endpoint(endpoint_id)
|
|
298
|
+
http_method = spec["method"].upper()
|
|
299
|
+
path = spec["path"]
|
|
300
|
+
else:
|
|
301
|
+
http_method = method.upper()
|
|
302
|
+
parts = endpoint_id.split(".")
|
|
303
|
+
if len(parts) != 3:
|
|
304
|
+
raise XTikError(
|
|
305
|
+
f'Invalid endpoint id "{endpoint_id}". Expected "<platform>.<resource>.<action>".',
|
|
306
|
+
code="invalid_endpoint_id",
|
|
307
|
+
status=400,
|
|
308
|
+
)
|
|
309
|
+
path = f"/v1/{'/'.join(parts)}"
|
|
310
|
+
|
|
311
|
+
headers: Dict[str, str] = {}
|
|
312
|
+
if max_price_usd is not None:
|
|
313
|
+
headers["X-Max-Price"] = str(max_price_usd)
|
|
314
|
+
if idempotency_key:
|
|
315
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
316
|
+
|
|
317
|
+
if http_method == "GET":
|
|
318
|
+
return await self._request("GET", path, auth=True, params=clean, headers=headers)
|
|
319
|
+
return await self._request("POST", path, auth=True, json_body=clean, headers=headers)
|
|
320
|
+
|
|
321
|
+
async def paginate(
|
|
322
|
+
self,
|
|
323
|
+
endpoint_id: str,
|
|
324
|
+
params: Optional[Dict[str, Any]] = None,
|
|
325
|
+
*,
|
|
326
|
+
max_pages: int = 5,
|
|
327
|
+
max_price_usd: Optional[float] = None,
|
|
328
|
+
idempotency_key: Optional[str] = None,
|
|
329
|
+
) -> AsyncIterator[Dict[str, Any]]:
|
|
330
|
+
current = dict(params or {})
|
|
331
|
+
for page_index in range(max_pages):
|
|
332
|
+
key = f"{idempotency_key}-p{page_index}" if idempotency_key else None
|
|
333
|
+
res = await self.call(
|
|
334
|
+
endpoint_id,
|
|
335
|
+
current,
|
|
336
|
+
max_price_usd=max_price_usd,
|
|
337
|
+
idempotency_key=key,
|
|
338
|
+
)
|
|
339
|
+
yield res
|
|
340
|
+
next_cursor = (res.get("data") or {}).get("next")
|
|
341
|
+
if not isinstance(next_cursor, dict) or not next_cursor:
|
|
342
|
+
return
|
|
343
|
+
current.update(next_cursor)
|
|
344
|
+
|
|
345
|
+
async def _request(
|
|
346
|
+
self,
|
|
347
|
+
method: str,
|
|
348
|
+
path: str,
|
|
349
|
+
*,
|
|
350
|
+
auth: bool,
|
|
351
|
+
params: Optional[Dict[str, Any]] = None,
|
|
352
|
+
json_body: Optional[Dict[str, Any]] = None,
|
|
353
|
+
headers: Optional[Dict[str, str]] = None,
|
|
354
|
+
) -> Dict[str, Any]:
|
|
355
|
+
req_headers = dict(headers or {})
|
|
356
|
+
if auth:
|
|
357
|
+
if not self.api_key:
|
|
358
|
+
raise XTikError(
|
|
359
|
+
"XTIKAPI_API_KEY is required. Pass api_key=... or set XTIKAPI_API_KEY. "
|
|
360
|
+
"Get a key at https://xtikapi.com/settings/apikeys",
|
|
361
|
+
code="unauthorized",
|
|
362
|
+
status=401,
|
|
363
|
+
)
|
|
364
|
+
req_headers["Authorization"] = f"Bearer {self.api_key}"
|
|
365
|
+
response = await self._client.request(method, path, params=params, json=json_body, headers=req_headers)
|
|
366
|
+
if response.status_code >= 400:
|
|
367
|
+
raise _parse_error(response)
|
|
368
|
+
return response.json()
|