apish-sdk 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.
@@ -0,0 +1,5 @@
1
+ node_modules/
2
+ dist/
3
+ *.egg-info/
4
+ __pycache__/
5
+ .pytest_cache/
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 api.sh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.3
2
+ Name: apish-sdk
3
+ Version: 0.1.0
4
+ Summary: Official client for api.sh: public web data (TikTok, Instagram, Amazon, Zillow, Google and 70+ platforms) as clean JSON.
5
+ Project-URL: Homepage, https://api.sh
6
+ Project-URL: Documentation, https://api.sh/docs/sdks
7
+ Author-email: "api.sh" <support@api.sh>
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: amazon,api.sh,apish,instagram,json,scraping,serp,tiktok,web scraping
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.9
17
+ Requires-Dist: httpx<1,>=0.24
18
+ Provides-Extra: langchain
19
+ Requires-Dist: langchain-core>=0.2; extra == 'langchain'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # api.sh for Python
23
+
24
+ Official Python client for [api.sh](https://api.sh): public web data from TikTok, Instagram, Amazon, Zillow, Google and 70+ platforms as clean JSON. Every endpoint is a typed method.
25
+
26
+ ```sh
27
+ pip install api-sh
28
+ ```
29
+
30
+ ```python
31
+ from apish import Apish
32
+
33
+ apish = Apish() # reads APISH_API_KEY; or Apish("ash_live_…") (https://app.api.sh/keys)
34
+
35
+ profile = apish.tiktok.profile(username="nasa")
36
+ print(profile["followers"], profile.meta.credits_used, profile.meta.request_id)
37
+
38
+ results = apish.amazon.search(q="headphones", options={"raw": False})
39
+ ```
40
+
41
+ Python 3.9+, sync (`Apish`) and asyncio (`AsyncApish`).
42
+
43
+ ## Calls
44
+
45
+ - `apish.<platform>.<endpoint>(**params, options=...)`: one method per endpoint, with keyword-only typed parameters and the price in its docstring.
46
+ - `apish.call(route, params, options)`: any route, e.g. `apish.call("/reddit/v1/subreddit", {"subreddit": "python"})`.
47
+ - Options: `raw` (False leaves out raw source blocks), `fields`, `fresh`, `output` ("csv" / "ndjson" returns text), `timeout`, `max_retries`.
48
+ - Results are dicts with `.meta` (`request_id`, `credits_used`, `credits_remaining`, `status`, `seconds`).
49
+ - Retries 502/503/504 and network errors with backoff (failed calls are never charged).
50
+
51
+ ```python
52
+ for page in apish.paginate("/reddit/v1/subreddit", {"subreddit": "python"}, max_pages=5):
53
+ print(len(page["posts"]))
54
+
55
+ from apish import ApishError
56
+ try:
57
+ apish.zillow.property(url=url)
58
+ except ApishError as e:
59
+ print(e.status, e.message, e.insufficient_credits, e.spend_limit, e.request_id)
60
+ ```
61
+
62
+ ## Async
63
+
64
+ ```python
65
+ import asyncio
66
+ from apish import AsyncApish
67
+
68
+ async def main():
69
+ async with AsyncApish() as apish:
70
+ print((await apish.reddit.subreddit(subreddit="python"))["posts"][0]["title"])
71
+
72
+ asyncio.run(main())
73
+ ```
74
+
75
+ ## Account (free)
76
+
77
+ ```python
78
+ apish.account.get() # balance, plan, spend, limits
79
+ apish.account.usage(days=30)
80
+ apish.account.logs(status="error")
81
+ apish.account.result(request_id) # a past response again, free, 30 days
82
+ ```
83
+
84
+ ## AI agents
85
+
86
+ ```python
87
+ from apish.tools import openai_tools, anthropic_tools, run_tool
88
+ tools = openai_tools() # apish_search + apish_call (or openai_tools(["/tiktok/v1/profile"]))
89
+ text = run_tool(apish, name, arguments) # when the model calls a tool
90
+
91
+ # LangChain: pip install "api-sh[langchain]"
92
+ from apish.langchain import apish_tools
93
+ tools = apish_tools(apish)
94
+ ```
95
+
96
+ For Claude Desktop, Cursor and other MCP clients, use the [MCP server](https://api.sh/mcp).
97
+
98
+ Docs: https://api.sh/docs/sdks · License: MIT
@@ -0,0 +1,77 @@
1
+ # api.sh for Python
2
+
3
+ Official Python client for [api.sh](https://api.sh): public web data from TikTok, Instagram, Amazon, Zillow, Google and 70+ platforms as clean JSON. Every endpoint is a typed method.
4
+
5
+ ```sh
6
+ pip install api-sh
7
+ ```
8
+
9
+ ```python
10
+ from apish import Apish
11
+
12
+ apish = Apish() # reads APISH_API_KEY; or Apish("ash_live_…") (https://app.api.sh/keys)
13
+
14
+ profile = apish.tiktok.profile(username="nasa")
15
+ print(profile["followers"], profile.meta.credits_used, profile.meta.request_id)
16
+
17
+ results = apish.amazon.search(q="headphones", options={"raw": False})
18
+ ```
19
+
20
+ Python 3.9+, sync (`Apish`) and asyncio (`AsyncApish`).
21
+
22
+ ## Calls
23
+
24
+ - `apish.<platform>.<endpoint>(**params, options=...)`: one method per endpoint, with keyword-only typed parameters and the price in its docstring.
25
+ - `apish.call(route, params, options)`: any route, e.g. `apish.call("/reddit/v1/subreddit", {"subreddit": "python"})`.
26
+ - Options: `raw` (False leaves out raw source blocks), `fields`, `fresh`, `output` ("csv" / "ndjson" returns text), `timeout`, `max_retries`.
27
+ - Results are dicts with `.meta` (`request_id`, `credits_used`, `credits_remaining`, `status`, `seconds`).
28
+ - Retries 502/503/504 and network errors with backoff (failed calls are never charged).
29
+
30
+ ```python
31
+ for page in apish.paginate("/reddit/v1/subreddit", {"subreddit": "python"}, max_pages=5):
32
+ print(len(page["posts"]))
33
+
34
+ from apish import ApishError
35
+ try:
36
+ apish.zillow.property(url=url)
37
+ except ApishError as e:
38
+ print(e.status, e.message, e.insufficient_credits, e.spend_limit, e.request_id)
39
+ ```
40
+
41
+ ## Async
42
+
43
+ ```python
44
+ import asyncio
45
+ from apish import AsyncApish
46
+
47
+ async def main():
48
+ async with AsyncApish() as apish:
49
+ print((await apish.reddit.subreddit(subreddit="python"))["posts"][0]["title"])
50
+
51
+ asyncio.run(main())
52
+ ```
53
+
54
+ ## Account (free)
55
+
56
+ ```python
57
+ apish.account.get() # balance, plan, spend, limits
58
+ apish.account.usage(days=30)
59
+ apish.account.logs(status="error")
60
+ apish.account.result(request_id) # a past response again, free, 30 days
61
+ ```
62
+
63
+ ## AI agents
64
+
65
+ ```python
66
+ from apish.tools import openai_tools, anthropic_tools, run_tool
67
+ tools = openai_tools() # apish_search + apish_call (or openai_tools(["/tiktok/v1/profile"]))
68
+ text = run_tool(apish, name, arguments) # when the model calls a tool
69
+
70
+ # LangChain: pip install "api-sh[langchain]"
71
+ from apish.langchain import apish_tools
72
+ tools = apish_tools(apish)
73
+ ```
74
+
75
+ For Claude Desktop, Cursor and other MCP clients, use the [MCP server](https://api.sh/mcp).
76
+
77
+ Docs: https://api.sh/docs/sdks · License: MIT
@@ -0,0 +1,13 @@
1
+ """Official Python client for api.sh: public web data from 70+ platforms as clean JSON.
2
+
3
+ from apish import Apish
4
+ apish = Apish() # reads APISH_API_KEY
5
+ print(apish.reddit.subreddit(subreddit="python")["posts"][0]["title"])
6
+
7
+ Docs: https://api.sh/docs/sdks
8
+ """
9
+ from ._client import DEFAULT_BASE_URL, Apish, AsyncApish, __version__
10
+ from ._types import CallMeta, CallOptions, Result, TextResult
11
+ from .errors import ApishError
12
+
13
+ __all__ = ["Apish", "AsyncApish", "ApishError", "CallMeta", "CallOptions", "Result", "TextResult", "DEFAULT_BASE_URL", "__version__"]
@@ -0,0 +1,258 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import random
5
+ import time
6
+ import asyncio
7
+ from typing import Any, AsyncIterator, Dict, Iterator, Optional, Union
8
+ from urllib.parse import quote
9
+
10
+ import httpx
11
+
12
+ from ._endpoints import CREDITS, PAGINATION, AsyncPlatforms, Platforms
13
+ from ._types import CallMeta, CallOptions, Result, TextResult
14
+ from .errors import ApishError
15
+
16
+ __version__ = "0.1.0"
17
+ DEFAULT_BASE_URL = "https://api.api.sh"
18
+
19
+
20
+ def _query(params: Dict[str, Any], options: Optional[CallOptions]) -> Dict[str, str]:
21
+ q: Dict[str, str] = {}
22
+ for k, v in params.items():
23
+ if v is None or v == "":
24
+ continue
25
+ q[k] = ("true" if v else "false") if isinstance(v, bool) else str(v)
26
+ o = options or {}
27
+ if "raw" in o:
28
+ q["raw"] = "1" if o["raw"] else "0"
29
+ if o.get("fields"):
30
+ f = o["fields"]
31
+ q["fields"] = f if isinstance(f, str) else ",".join(f)
32
+ if o.get("fresh"):
33
+ q["fresh"] = "1"
34
+ if o.get("output") and o["output"] != "json":
35
+ q["output"] = o["output"]
36
+ if o.get("records"):
37
+ q["records"] = o["records"]
38
+ return q
39
+
40
+
41
+ def _meta(res: httpx.Response, started: float) -> CallMeta:
42
+ rem = res.headers.get("x-credits-remaining")
43
+ return CallMeta(
44
+ request_id=res.headers.get("x-request-id"),
45
+ credits_used=int(res.headers.get("x-credits-used") or 0),
46
+ credits_remaining=int(rem) if rem is not None else None,
47
+ status=res.status_code,
48
+ seconds=round(time.monotonic() - started, 3),
49
+ )
50
+
51
+
52
+ def _result(res: httpx.Response, started: float) -> Union[Result, TextResult]:
53
+ meta = _meta(res, started)
54
+ if "json" not in res.headers.get("content-type", ""):
55
+ return TextResult(res.text, meta)
56
+ data = res.json()
57
+ return Result(data if isinstance(data, dict) else {"items": data}, meta)
58
+
59
+
60
+ def _error(res: httpx.Response) -> ApishError:
61
+ try:
62
+ body = res.json()
63
+ except ValueError:
64
+ body = {}
65
+ if not isinstance(body, dict):
66
+ body = {}
67
+ return ApishError(res.status_code, str(body.get("error") or body.get("message") or f"api.sh returned {res.status_code}"), body, res.headers.get("x-request-id"))
68
+
69
+
70
+ def _wait(res: Optional[httpx.Response], attempt: int) -> float:
71
+ if res is not None:
72
+ try:
73
+ after = float(res.headers.get("retry-after", ""))
74
+ if after > 0:
75
+ return min(after, 30.0)
76
+ except ValueError:
77
+ pass
78
+ return min(2 ** attempt, 10) + random.random() / 4
79
+
80
+
81
+ def _key(api_key: Optional[str]) -> str:
82
+ key = api_key or os.environ.get("APISH_API_KEY", "")
83
+ if not key:
84
+ raise ValueError("api.sh: pass api_key=... or set APISH_API_KEY (create a key at https://app.api.sh/keys)")
85
+ return key
86
+
87
+
88
+ class Apish(Platforms):
89
+ """The api.sh client.
90
+
91
+ from apish import Apish
92
+ apish = Apish() # reads APISH_API_KEY
93
+ profile = apish.tiktok.profile(username="nasa")
94
+ print(profile["followers"], profile.meta.credits_used)
95
+
96
+ Every platform is an attribute (apish.amazon, apish.google_maps, ...); every endpoint a method with typed,
97
+ keyword-only parameters. `apish.call(route, params)` runs any route; `apish.account` covers your balance,
98
+ usage, logs and past responses (free).
99
+ """
100
+
101
+ def __init__(self, api_key: Optional[str] = None, *, base_url: str = DEFAULT_BASE_URL, timeout: float = 120.0, max_retries: int = 2, http_client: Optional[httpx.Client] = None) -> None:
102
+ self._key = _key(api_key)
103
+ self.base_url = base_url.rstrip("/")
104
+ self.timeout = timeout
105
+ self.max_retries = max_retries
106
+ self._http = http_client or httpx.Client(timeout=timeout, headers={"user-agent": f"apish-python/{__version__}"})
107
+ super().__init__(self.call)
108
+ self.account = _Account(self.call)
109
+
110
+ def call(self, route: str, params: Optional[Dict[str, Any]] = None, options: Optional[CallOptions] = None) -> Union[Result, TextResult]:
111
+ """Runs any endpoint: apish.call("/reddit/v1/subreddit", {"subreddit": "python"})."""
112
+ o = options or {}
113
+ retries = o.get("max_retries", self.max_retries)
114
+ started = time.monotonic()
115
+ attempt = 0
116
+ while True:
117
+ try:
118
+ res = self._http.get(self.base_url + route, params=_query(params or {}, o), headers={"x-api-key": self._key, "accept": "application/json"}, timeout=o.get("timeout", self.timeout))
119
+ except httpx.TransportError:
120
+ if attempt >= retries:
121
+ raise
122
+ time.sleep(_wait(None, attempt))
123
+ attempt += 1
124
+ continue
125
+ if res.is_success:
126
+ return _result(res, started)
127
+ err = _error(res)
128
+ if not err.retryable or attempt >= retries:
129
+ raise err
130
+ time.sleep(_wait(res, attempt))
131
+ attempt += 1
132
+
133
+ def paginate(self, route: str, params: Optional[Dict[str, Any]] = None, options: Optional[CallOptions] = None, *, max_pages: Optional[int] = None) -> Iterator[Union[Result, TextResult]]:
134
+ """Every page of a paginated endpoint: for page in apish.paginate("/reddit/v1/subreddit", {"subreddit": "python"}, max_pages=5)."""
135
+ rule = PAGINATION.get(route)
136
+ p = dict(params or {})
137
+ n = 0
138
+ while max_pages is None or n < max_pages:
139
+ page = self.call(route, p, options)
140
+ yield page
141
+ n += 1
142
+ nxt = page.get(rule[0]) if rule and isinstance(page, dict) else None
143
+ if nxt in (None, "", False):
144
+ return
145
+ p[rule[1]] = nxt # type: ignore[index]
146
+
147
+ @staticmethod
148
+ def credits(route: str) -> Optional[int]:
149
+ """Credits per successful call for a route, as of this SDK version."""
150
+ return CREDITS.get(route)
151
+
152
+ def close(self) -> None:
153
+ self._http.close()
154
+
155
+ def __enter__(self) -> "Apish":
156
+ return self
157
+
158
+ def __exit__(self, *exc: Any) -> None:
159
+ self.close()
160
+
161
+
162
+ class AsyncApish(AsyncPlatforms):
163
+ """The api.sh client for asyncio: `await apish.tiktok.profile(username="nasa")`."""
164
+
165
+ def __init__(self, api_key: Optional[str] = None, *, base_url: str = DEFAULT_BASE_URL, timeout: float = 120.0, max_retries: int = 2, http_client: Optional[httpx.AsyncClient] = None) -> None:
166
+ self._key = _key(api_key)
167
+ self.base_url = base_url.rstrip("/")
168
+ self.timeout = timeout
169
+ self.max_retries = max_retries
170
+ self._http = http_client or httpx.AsyncClient(timeout=timeout, headers={"user-agent": f"apish-python/{__version__}"})
171
+ super().__init__(self.call)
172
+ self.account = _AsyncAccount(self.call)
173
+
174
+ async def call(self, route: str, params: Optional[Dict[str, Any]] = None, options: Optional[CallOptions] = None) -> Union[Result, TextResult]:
175
+ o = options or {}
176
+ retries = o.get("max_retries", self.max_retries)
177
+ started = time.monotonic()
178
+ attempt = 0
179
+ while True:
180
+ try:
181
+ res = await self._http.get(self.base_url + route, params=_query(params or {}, o), headers={"x-api-key": self._key, "accept": "application/json"}, timeout=o.get("timeout", self.timeout))
182
+ except httpx.TransportError:
183
+ if attempt >= retries:
184
+ raise
185
+ await asyncio.sleep(_wait(None, attempt))
186
+ attempt += 1
187
+ continue
188
+ if res.is_success:
189
+ return _result(res, started)
190
+ err = _error(res)
191
+ if not err.retryable or attempt >= retries:
192
+ raise err
193
+ await asyncio.sleep(_wait(res, attempt))
194
+ attempt += 1
195
+
196
+ async def paginate(self, route: str, params: Optional[Dict[str, Any]] = None, options: Optional[CallOptions] = None, *, max_pages: Optional[int] = None) -> AsyncIterator[Union[Result, TextResult]]:
197
+ rule = PAGINATION.get(route)
198
+ p = dict(params or {})
199
+ n = 0
200
+ while max_pages is None or n < max_pages:
201
+ page = await self.call(route, p, options)
202
+ yield page
203
+ n += 1
204
+ nxt = page.get(rule[0]) if rule and isinstance(page, dict) else None
205
+ if nxt in (None, "", False):
206
+ return
207
+ p[rule[1]] = nxt # type: ignore[index]
208
+
209
+ async def aclose(self) -> None:
210
+ await self._http.aclose()
211
+
212
+ async def __aenter__(self) -> "AsyncApish":
213
+ return self
214
+
215
+ async def __aexit__(self, *exc: Any) -> None:
216
+ await self.aclose()
217
+
218
+
219
+ class _Account:
220
+ """Your balance, usage, logs and past responses. Free (no credits)."""
221
+
222
+ def __init__(self, call: Any) -> None:
223
+ self._call = call
224
+
225
+ def get(self) -> Result:
226
+ """Credits by bucket, plan, spend today / this month (UTC) and spend limits."""
227
+ return self._call("/v1/account", {})
228
+
229
+ def usage(self, days: int = 30) -> Result:
230
+ """Calls, errors and credits per UTC day (1-90 days) and the top endpoints."""
231
+ return self._call("/v1/account/usage", {"days": days})
232
+
233
+ def logs(self, *, limit: int = 50, status: Optional[str] = None, route: Optional[str] = None, key: Optional[str] = None, since: Optional[str] = None, before: Optional[str] = None) -> Result:
234
+ """Calls of the last 30 days, newest first; next page with before=result["next"]."""
235
+ return self._call("/v1/account/logs", {"limit": limit, "status": status, "route": route, "key": key, "since": since, "before": before})
236
+
237
+ def result(self, request_id: str, *, output: Optional[str] = None) -> Union[Result, TextResult]:
238
+ """The response of an earlier call (its x-request-id) again, free, for 30 days."""
239
+ return self._call(f"/v1/results/{quote(request_id)}", {}, {"output": output} if output else None)
240
+
241
+
242
+ class _AsyncAccount:
243
+ """Your balance, usage, logs and past responses. Free (no credits)."""
244
+
245
+ def __init__(self, call: Any) -> None:
246
+ self._call = call
247
+
248
+ async def get(self) -> Result:
249
+ return await self._call("/v1/account", {})
250
+
251
+ async def usage(self, days: int = 30) -> Result:
252
+ return await self._call("/v1/account/usage", {"days": days})
253
+
254
+ async def logs(self, *, limit: int = 50, status: Optional[str] = None, route: Optional[str] = None, key: Optional[str] = None, since: Optional[str] = None, before: Optional[str] = None) -> Result:
255
+ return await self._call("/v1/account/logs", {"limit": limit, "status": status, "route": route, "key": key, "since": since, "before": before})
256
+
257
+ async def result(self, request_id: str, *, output: Optional[str] = None) -> Union[Result, TextResult]:
258
+ return await self._call(f"/v1/results/{quote(request_id)}", {}, {"output": output} if output else None)