dataguru-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.
- dataguru_sdk-0.1.0/.gitignore +2 -0
- dataguru_sdk-0.1.0/LICENSE +21 -0
- dataguru_sdk-0.1.0/PKG-INFO +128 -0
- dataguru_sdk-0.1.0/README.md +101 -0
- dataguru_sdk-0.1.0/pyproject.toml +43 -0
- dataguru_sdk-0.1.0/src/dataguru/__init__.py +32 -0
- dataguru_sdk-0.1.0/src/dataguru/_version.py +1 -0
- dataguru_sdk-0.1.0/src/dataguru/client.py +467 -0
- dataguru_sdk-0.1.0/src/dataguru/errors.py +138 -0
- dataguru_sdk-0.1.0/src/dataguru/py.typed +0 -0
- dataguru_sdk-0.1.0/tests/test_client.py +173 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Developers 360 LLC
|
|
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,128 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dataguru-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python client for the DataGuru API: Amazon, Walmart, Google, TikTok, 1688 and 100+ other sites as JSON APIs.
|
|
5
|
+
Project-URL: Homepage, https://dataguru.cc
|
|
6
|
+
Project-URL: Documentation, https://dataguru.cc/documentation/
|
|
7
|
+
Project-URL: API catalog, https://dataguru.cc/apis
|
|
8
|
+
Project-URL: Dashboard, https://dashboard.dataguru.cc
|
|
9
|
+
Author: Developers 360 LLC
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: amazon api,dataguru,ecommerce data,json api,scraping api,web scraping
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Requires-Dist: httpx<1,>=0.24
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest>=7; extra == 'dev'
|
|
25
|
+
Requires-Dist: respx>=0.20; extra == 'dev'
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# DataGuru Python SDK
|
|
29
|
+
|
|
30
|
+
The official Python client for [DataGuru](https://dataguru.cc). DataGuru turns websites like Amazon, Walmart, Google, TikTok and 1688 into JSON APIs.
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install dataguru-sdk
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from dataguru import DataGuru
|
|
38
|
+
|
|
39
|
+
dg = DataGuru(api_key="YOUR_API_KEY") # or set DATAGURU_API_KEY
|
|
40
|
+
|
|
41
|
+
product = dg.call(
|
|
42
|
+
"amazon-products-search",
|
|
43
|
+
product_url="https://www.amazon.com/dp/B0CHWRXH8B",
|
|
44
|
+
)
|
|
45
|
+
print(product["title"], product["price"])
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Get an API key from the [dashboard](https://dashboard.dataguru.cc). Each call is billed to your balance at the API's listed price. You can browse every API, with its parameters and price, at [dataguru.cc/apis](https://dataguru.cc/apis).
|
|
49
|
+
|
|
50
|
+
## Find an API
|
|
51
|
+
|
|
52
|
+
The catalog is public, so these calls don't need a key.
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
for api in dg.apis.search("walmart"):
|
|
56
|
+
print(api["slug"], api["pricing"]["customer_price"], [p["name"] for p in api["parameters"]])
|
|
57
|
+
|
|
58
|
+
details = dg.apis.get("amazon-products-search") # parameters, pricing, limits, sample_response, docs_url
|
|
59
|
+
everything = dg.apis.list(category="E-Commerce")
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`dg.call()` takes an API's slug (`amazon-products-search`) or its endpoint path (`amazon/products/search`). You can pass parameters as keyword arguments or as a dict. The client checks them against the API's declared parameters before it sends anything.
|
|
63
|
+
|
|
64
|
+
## Async jobs
|
|
65
|
+
|
|
66
|
+
Use a job when you don't want to hold a connection open for a slow scrape. Funds are held when you submit and charged only if the job succeeds.
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
job = dg.jobs.submit("amazon-products-search", {"product_url": "https://www.amazon.com/dp/B0CHWRXH8B"})
|
|
70
|
+
data = dg.jobs.wait(job["job_id"]) # polls; raises JobFailedError if it fails
|
|
71
|
+
|
|
72
|
+
data = dg.jobs.run("amazon-products-search", product_url="...") # submit + wait
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Batches
|
|
76
|
+
|
|
77
|
+
Upload a CSV with one request per row. Its columns are the API's parameter names.
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
batch = dg.batches.create("amazon-products-search", "products.csv")
|
|
81
|
+
dg.batches.wait(batch["batch_id"]) # or poll dg.batches.get(...)["progress"]
|
|
82
|
+
|
|
83
|
+
for row in dg.batches.iter_results(batch["batch_id"]): # streams JSON Lines
|
|
84
|
+
print(row["status"], row.get("data"))
|
|
85
|
+
|
|
86
|
+
dg.batches.download(batch["batch_id"], "results.csv") # json, jsonl or csv summary
|
|
87
|
+
dg.batches.cancel(batch["batch_id"]) # unstarted rows are refunded
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Errors
|
|
91
|
+
|
|
92
|
+
Every error inherits from `dataguru.DataGuruError`. HTTP errors are `APIError` subclasses with `status_code`, `code`, `message`, `details` and `request_id`:
|
|
93
|
+
|
|
94
|
+
| Exception | When |
|
|
95
|
+
|---|---|
|
|
96
|
+
| `ValidationError` | 400: a parameter is missing or invalid (see `.details`) |
|
|
97
|
+
| `AuthenticationError` | 401/403: the key is missing, invalid or revoked |
|
|
98
|
+
| `InsufficientBalanceError` | 402: your balance is too low, so [top up](https://dashboard.dataguru.cc) |
|
|
99
|
+
| `NotFoundError` | 404 |
|
|
100
|
+
| `RateLimitError` | 429: `.retry_after` gives the wait in seconds |
|
|
101
|
+
| `ServerError` | 5xx |
|
|
102
|
+
| `JobFailedError` | an async job failed (failed jobs are not billed) |
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from dataguru import DataGuru, InsufficientBalanceError, ValidationError
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
dg.call("amazon-products-search", product_url="not a url")
|
|
109
|
+
except ValidationError as e:
|
|
110
|
+
print(e.details)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
The client retries read requests (catalog lookups, job and batch status) on 429, 5xx and connection errors. Billed requests are retried only when the connection failed before the request was sent, so a retry never charges you twice.
|
|
114
|
+
|
|
115
|
+
## Configuration
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
DataGuru(
|
|
119
|
+
api_key=None, # default: $DATAGURU_API_KEY
|
|
120
|
+
base_url=None, # default: $DATAGURU_BASE_URL or https://api.dataguru.cc
|
|
121
|
+
timeout=120.0, # seconds per HTTP response
|
|
122
|
+
max_retries=2,
|
|
123
|
+
)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
`DataGuru` can be used as a context manager (`with DataGuru() as dg: ...`) and closes its connection pool on exit.
|
|
127
|
+
|
|
128
|
+
Requires Python 3.9+. Released under the MIT license.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# DataGuru Python SDK
|
|
2
|
+
|
|
3
|
+
The official Python client for [DataGuru](https://dataguru.cc). DataGuru turns websites like Amazon, Walmart, Google, TikTok and 1688 into JSON APIs.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install dataguru-sdk
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from dataguru import DataGuru
|
|
11
|
+
|
|
12
|
+
dg = DataGuru(api_key="YOUR_API_KEY") # or set DATAGURU_API_KEY
|
|
13
|
+
|
|
14
|
+
product = dg.call(
|
|
15
|
+
"amazon-products-search",
|
|
16
|
+
product_url="https://www.amazon.com/dp/B0CHWRXH8B",
|
|
17
|
+
)
|
|
18
|
+
print(product["title"], product["price"])
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Get an API key from the [dashboard](https://dashboard.dataguru.cc). Each call is billed to your balance at the API's listed price. You can browse every API, with its parameters and price, at [dataguru.cc/apis](https://dataguru.cc/apis).
|
|
22
|
+
|
|
23
|
+
## Find an API
|
|
24
|
+
|
|
25
|
+
The catalog is public, so these calls don't need a key.
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
for api in dg.apis.search("walmart"):
|
|
29
|
+
print(api["slug"], api["pricing"]["customer_price"], [p["name"] for p in api["parameters"]])
|
|
30
|
+
|
|
31
|
+
details = dg.apis.get("amazon-products-search") # parameters, pricing, limits, sample_response, docs_url
|
|
32
|
+
everything = dg.apis.list(category="E-Commerce")
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`dg.call()` takes an API's slug (`amazon-products-search`) or its endpoint path (`amazon/products/search`). You can pass parameters as keyword arguments or as a dict. The client checks them against the API's declared parameters before it sends anything.
|
|
36
|
+
|
|
37
|
+
## Async jobs
|
|
38
|
+
|
|
39
|
+
Use a job when you don't want to hold a connection open for a slow scrape. Funds are held when you submit and charged only if the job succeeds.
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
job = dg.jobs.submit("amazon-products-search", {"product_url": "https://www.amazon.com/dp/B0CHWRXH8B"})
|
|
43
|
+
data = dg.jobs.wait(job["job_id"]) # polls; raises JobFailedError if it fails
|
|
44
|
+
|
|
45
|
+
data = dg.jobs.run("amazon-products-search", product_url="...") # submit + wait
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Batches
|
|
49
|
+
|
|
50
|
+
Upload a CSV with one request per row. Its columns are the API's parameter names.
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
batch = dg.batches.create("amazon-products-search", "products.csv")
|
|
54
|
+
dg.batches.wait(batch["batch_id"]) # or poll dg.batches.get(...)["progress"]
|
|
55
|
+
|
|
56
|
+
for row in dg.batches.iter_results(batch["batch_id"]): # streams JSON Lines
|
|
57
|
+
print(row["status"], row.get("data"))
|
|
58
|
+
|
|
59
|
+
dg.batches.download(batch["batch_id"], "results.csv") # json, jsonl or csv summary
|
|
60
|
+
dg.batches.cancel(batch["batch_id"]) # unstarted rows are refunded
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Errors
|
|
64
|
+
|
|
65
|
+
Every error inherits from `dataguru.DataGuruError`. HTTP errors are `APIError` subclasses with `status_code`, `code`, `message`, `details` and `request_id`:
|
|
66
|
+
|
|
67
|
+
| Exception | When |
|
|
68
|
+
|---|---|
|
|
69
|
+
| `ValidationError` | 400: a parameter is missing or invalid (see `.details`) |
|
|
70
|
+
| `AuthenticationError` | 401/403: the key is missing, invalid or revoked |
|
|
71
|
+
| `InsufficientBalanceError` | 402: your balance is too low, so [top up](https://dashboard.dataguru.cc) |
|
|
72
|
+
| `NotFoundError` | 404 |
|
|
73
|
+
| `RateLimitError` | 429: `.retry_after` gives the wait in seconds |
|
|
74
|
+
| `ServerError` | 5xx |
|
|
75
|
+
| `JobFailedError` | an async job failed (failed jobs are not billed) |
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
from dataguru import DataGuru, InsufficientBalanceError, ValidationError
|
|
79
|
+
|
|
80
|
+
try:
|
|
81
|
+
dg.call("amazon-products-search", product_url="not a url")
|
|
82
|
+
except ValidationError as e:
|
|
83
|
+
print(e.details)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
The client retries read requests (catalog lookups, job and batch status) on 429, 5xx and connection errors. Billed requests are retried only when the connection failed before the request was sent, so a retry never charges you twice.
|
|
87
|
+
|
|
88
|
+
## Configuration
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
DataGuru(
|
|
92
|
+
api_key=None, # default: $DATAGURU_API_KEY
|
|
93
|
+
base_url=None, # default: $DATAGURU_BASE_URL or https://api.dataguru.cc
|
|
94
|
+
timeout=120.0, # seconds per HTTP response
|
|
95
|
+
max_retries=2,
|
|
96
|
+
)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`DataGuru` can be used as a context manager (`with DataGuru() as dg: ...`) and closes its connection pool on exit.
|
|
100
|
+
|
|
101
|
+
Requires Python 3.9+. Released under the MIT license.
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "dataguru-sdk"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Official Python client for the DataGuru API: Amazon, Walmart, Google, TikTok, 1688 and 100+ other sites as JSON APIs."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Developers 360 LLC" }]
|
|
14
|
+
keywords = ["dataguru", "web scraping", "scraping api", "amazon api", "ecommerce data", "json api"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
21
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
22
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
23
|
+
"Typing :: Typed",
|
|
24
|
+
]
|
|
25
|
+
dependencies = ["httpx>=0.24,<1"]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://dataguru.cc"
|
|
29
|
+
Documentation = "https://dataguru.cc/documentation/"
|
|
30
|
+
"API catalog" = "https://dataguru.cc/apis"
|
|
31
|
+
Dashboard = "https://dashboard.dataguru.cc"
|
|
32
|
+
|
|
33
|
+
[project.optional-dependencies]
|
|
34
|
+
dev = ["pytest>=7", "respx>=0.20"]
|
|
35
|
+
|
|
36
|
+
[tool.hatch.version]
|
|
37
|
+
path = "src/dataguru/_version.py"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["src/dataguru"]
|
|
41
|
+
|
|
42
|
+
[tool.hatch.build.targets.sdist]
|
|
43
|
+
include = ["src", "tests", "README.md", "LICENSE", "pyproject.toml"]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Official Python client for the DataGuru API (https://dataguru.cc)."""
|
|
2
|
+
from ._version import __version__
|
|
3
|
+
from .client import DataGuru
|
|
4
|
+
from .errors import (
|
|
5
|
+
APIError,
|
|
6
|
+
AuthenticationError,
|
|
7
|
+
ConflictError,
|
|
8
|
+
DataGuruError,
|
|
9
|
+
InsufficientBalanceError,
|
|
10
|
+
JobFailedError,
|
|
11
|
+
NotFoundError,
|
|
12
|
+
RateLimitError,
|
|
13
|
+
ServerError,
|
|
14
|
+
TimeoutError,
|
|
15
|
+
ValidationError,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"DataGuru",
|
|
20
|
+
"DataGuruError",
|
|
21
|
+
"APIError",
|
|
22
|
+
"AuthenticationError",
|
|
23
|
+
"ConflictError",
|
|
24
|
+
"InsufficientBalanceError",
|
|
25
|
+
"JobFailedError",
|
|
26
|
+
"NotFoundError",
|
|
27
|
+
"RateLimitError",
|
|
28
|
+
"ServerError",
|
|
29
|
+
"TimeoutError",
|
|
30
|
+
"ValidationError",
|
|
31
|
+
"__version__",
|
|
32
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
"""Synchronous DataGuru API client."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import random
|
|
6
|
+
import re
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import IO, Any, Dict, Iterator, List, Mapping, Optional, Union
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from ._version import __version__
|
|
14
|
+
from .errors import DataGuruError, JobFailedError, TimeoutError, error_for
|
|
15
|
+
|
|
16
|
+
DEFAULT_BASE_URL = "https://api.dataguru.cc"
|
|
17
|
+
DEFAULT_TIMEOUT = 120.0 # some scrapes take a while; the API itself caps long calls
|
|
18
|
+
CATALOG_TTL = 600.0
|
|
19
|
+
|
|
20
|
+
JOB_ACTIVE = ("SUBMITTED", "QUEUED", "PROCESSING", "RETRYING")
|
|
21
|
+
JOB_FAILED = ("FAILED", "EXPIRED", "CANCELLED")
|
|
22
|
+
|
|
23
|
+
FileInput = Union[str, os.PathLike, bytes, IO[bytes]]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DataGuru:
|
|
27
|
+
"""Client for https://api.dataguru.cc.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
api_key: Your DataGuru API key. Defaults to the ``DATAGURU_API_KEY`` environment variable.
|
|
31
|
+
Create one at https://dashboard.dataguru.cc.
|
|
32
|
+
base_url: API host. Defaults to ``DATAGURU_BASE_URL`` or ``https://api.dataguru.cc``.
|
|
33
|
+
timeout: Seconds to wait for each HTTP response.
|
|
34
|
+
max_retries: How many times to retry reads (catalog, job and batch status) on 429, 5xx and
|
|
35
|
+
connection errors. Billed calls (``call``, ``jobs.submit``, ``batches.create``) are only
|
|
36
|
+
retried when the connection failed before the request was sent, so you are never charged twice.
|
|
37
|
+
|
|
38
|
+
Example::
|
|
39
|
+
|
|
40
|
+
from dataguru import DataGuru
|
|
41
|
+
|
|
42
|
+
dg = DataGuru() # reads DATAGURU_API_KEY
|
|
43
|
+
product = dg.call("amazon-products-search", product_url="https://www.amazon.com/dp/B0CHWRXH8B")
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
api_key: Optional[str] = None,
|
|
49
|
+
*,
|
|
50
|
+
base_url: Optional[str] = None,
|
|
51
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
52
|
+
max_retries: int = 2,
|
|
53
|
+
http_client: Optional[httpx.Client] = None,
|
|
54
|
+
) -> None:
|
|
55
|
+
self.api_key = api_key or os.environ.get("DATAGURU_API_KEY")
|
|
56
|
+
self.base_url = (base_url or os.environ.get("DATAGURU_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
57
|
+
self.max_retries = max(0, int(max_retries))
|
|
58
|
+
self._own_http = http_client is None
|
|
59
|
+
self._http = http_client or httpx.Client(timeout=httpx.Timeout(timeout, connect=15.0))
|
|
60
|
+
self._catalog: Optional[tuple] = None # (fetched_at, {slug: api}, {path: api})
|
|
61
|
+
|
|
62
|
+
self.apis = Apis(self)
|
|
63
|
+
self.jobs = Jobs(self)
|
|
64
|
+
self.batches = Batches(self)
|
|
65
|
+
|
|
66
|
+
# -- lifecycle ---------------------------------------------------------------------------
|
|
67
|
+
def close(self) -> None:
|
|
68
|
+
if self._own_http:
|
|
69
|
+
self._http.close()
|
|
70
|
+
|
|
71
|
+
def __enter__(self) -> "DataGuru":
|
|
72
|
+
return self
|
|
73
|
+
|
|
74
|
+
def __exit__(self, *exc: Any) -> None:
|
|
75
|
+
self.close()
|
|
76
|
+
|
|
77
|
+
def __repr__(self) -> str:
|
|
78
|
+
return f"DataGuru(base_url={self.base_url!r})"
|
|
79
|
+
|
|
80
|
+
# -- main entry point --------------------------------------------------------------------
|
|
81
|
+
def call(self, api: str, params: Optional[Mapping[str, Any]] = None, /, **kwargs: Any) -> Any:
|
|
82
|
+
"""Runs an API and returns its JSON.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
api: The API's slug (``"amazon-products-search"``) or endpoint path (``"amazon/products/search"``).
|
|
86
|
+
Find both at https://dataguru.cc/apis or with ``dg.apis.search(...)``.
|
|
87
|
+
params: Parameters as a dict. Keyword arguments are merged on top, so
|
|
88
|
+
``dg.call("x", query="shoes")`` and ``dg.call("x", {"query": "shoes"})`` are the same.
|
|
89
|
+
File parameters accept a path, ``bytes`` or an open binary file.
|
|
90
|
+
|
|
91
|
+
Billed to your balance at the API's listed price (see ``dg.apis.get(slug)["pricing"]``).
|
|
92
|
+
"""
|
|
93
|
+
spec = self.apis._resolve(api)
|
|
94
|
+
values = {**(params or {}), **kwargs}
|
|
95
|
+
declared = {p["name"]: p for p in spec.get("parameters") or []}
|
|
96
|
+
|
|
97
|
+
unknown = sorted(set(values) - set(declared))
|
|
98
|
+
if unknown and declared:
|
|
99
|
+
raise DataGuruError(
|
|
100
|
+
f"Unknown parameter(s) {unknown} for '{spec['slug']}'. Valid: {sorted(declared)}."
|
|
101
|
+
)
|
|
102
|
+
missing = sorted(
|
|
103
|
+
n for n, p in declared.items()
|
|
104
|
+
if p.get("required") and values.get(n) in (None, "") and p.get("default_value") in (None, "")
|
|
105
|
+
)
|
|
106
|
+
if missing:
|
|
107
|
+
raise DataGuruError(f"Missing required parameter(s) {missing} for '{spec['slug']}'.")
|
|
108
|
+
|
|
109
|
+
method = (spec.get("http_method") or "POST").upper()
|
|
110
|
+
path = spec["endpoint_path"].lstrip("/")
|
|
111
|
+
query: Dict[str, Any] = {}
|
|
112
|
+
body: Dict[str, Any] = {}
|
|
113
|
+
headers: Dict[str, str] = {}
|
|
114
|
+
files: Dict[str, Any] = {}
|
|
115
|
+
for name, value in values.items():
|
|
116
|
+
if value is None:
|
|
117
|
+
continue
|
|
118
|
+
p = declared.get(name, {})
|
|
119
|
+
loc = (p.get("location") or ("QUERY" if method == "GET" else "BODY")).upper()
|
|
120
|
+
if "file" in (p.get("data_type") or "").lower():
|
|
121
|
+
files[name] = _file_tuple(value, name)
|
|
122
|
+
elif loc == "PATH" or f"{{{name}}}" in path:
|
|
123
|
+
path = path.replace(f"{{{name}}}", str(value)).replace(f":{name}", str(value))
|
|
124
|
+
elif loc == "HEADER":
|
|
125
|
+
headers[name] = str(value)
|
|
126
|
+
elif loc == "QUERY" or method == "GET":
|
|
127
|
+
query[name] = _query_value(value)
|
|
128
|
+
else:
|
|
129
|
+
body[name] = value
|
|
130
|
+
|
|
131
|
+
kw: Dict[str, Any] = {"params": query or None, "headers": headers or None}
|
|
132
|
+
if files:
|
|
133
|
+
kw["files"] = files
|
|
134
|
+
kw["data"] = {k: _form_value(v) for k, v in body.items()}
|
|
135
|
+
elif method != "GET":
|
|
136
|
+
kw["json"] = body
|
|
137
|
+
return self._request(method, f"/api/v1/{path}", billed=True, **kw)
|
|
138
|
+
|
|
139
|
+
# -- HTTP plumbing -----------------------------------------------------------------------
|
|
140
|
+
def _headers(self, extra: Optional[Mapping[str, str]], auth: bool) -> Dict[str, str]:
|
|
141
|
+
h = {"Accept": "application/json", "User-Agent": f"dataguru-python/{__version__}"}
|
|
142
|
+
if auth:
|
|
143
|
+
if not self.api_key:
|
|
144
|
+
raise DataGuruError(
|
|
145
|
+
"No API key. Pass DataGuru(api_key=...) or set DATAGURU_API_KEY. "
|
|
146
|
+
"Create a key at https://dashboard.dataguru.cc."
|
|
147
|
+
)
|
|
148
|
+
h["Authorization"] = f"Api-Key {self.api_key}"
|
|
149
|
+
if extra:
|
|
150
|
+
h.update(extra)
|
|
151
|
+
return h
|
|
152
|
+
|
|
153
|
+
def _send(
|
|
154
|
+
self,
|
|
155
|
+
method: str,
|
|
156
|
+
path: str,
|
|
157
|
+
*,
|
|
158
|
+
billed: bool = False,
|
|
159
|
+
auth: bool = True,
|
|
160
|
+
headers: Optional[Mapping[str, str]] = None,
|
|
161
|
+
stream: bool = False,
|
|
162
|
+
**kwargs: Any,
|
|
163
|
+
) -> httpx.Response:
|
|
164
|
+
url = path if path.startswith("http") else f"{self.base_url}{path}"
|
|
165
|
+
req_headers = self._headers(headers, auth)
|
|
166
|
+
attempt = 0
|
|
167
|
+
while True:
|
|
168
|
+
try:
|
|
169
|
+
request = self._http.build_request(method, url, headers=req_headers, **kwargs)
|
|
170
|
+
response = self._http.send(request, stream=stream)
|
|
171
|
+
except (httpx.ConnectError, httpx.ConnectTimeout) as exc:
|
|
172
|
+
# Nothing reached the server, so even a billed call is safe to retry.
|
|
173
|
+
if attempt < self.max_retries:
|
|
174
|
+
attempt += 1
|
|
175
|
+
time.sleep(_backoff(attempt))
|
|
176
|
+
continue
|
|
177
|
+
raise DataGuruError(f"Could not connect to {self.base_url}: {exc}") from exc
|
|
178
|
+
except httpx.TimeoutException as exc:
|
|
179
|
+
raise DataGuruError(
|
|
180
|
+
f"{method} {path} timed out. Raise DataGuru(timeout=...) or use dg.jobs.submit() for slow APIs."
|
|
181
|
+
) from exc
|
|
182
|
+
except httpx.HTTPError as exc:
|
|
183
|
+
raise DataGuruError(f"{method} {path} failed: {exc}") from exc
|
|
184
|
+
|
|
185
|
+
retryable = response.status_code in (429, 502, 503, 504)
|
|
186
|
+
if retryable and not billed and attempt < self.max_retries:
|
|
187
|
+
wait = _retry_after(response) or _backoff(attempt + 1)
|
|
188
|
+
response.close()
|
|
189
|
+
attempt += 1
|
|
190
|
+
time.sleep(min(wait, 30.0))
|
|
191
|
+
continue
|
|
192
|
+
|
|
193
|
+
if response.status_code >= 400:
|
|
194
|
+
if stream:
|
|
195
|
+
response.read()
|
|
196
|
+
raise _error(response)
|
|
197
|
+
return response
|
|
198
|
+
|
|
199
|
+
def _request(self, method: str, path: str, **kwargs: Any) -> Any:
|
|
200
|
+
response = self._send(method, path, **kwargs)
|
|
201
|
+
if response.status_code == 204 or not response.content:
|
|
202
|
+
return None
|
|
203
|
+
try:
|
|
204
|
+
data = response.json()
|
|
205
|
+
except ValueError:
|
|
206
|
+
return response.text
|
|
207
|
+
if isinstance(data, dict) and data.get("success") is False:
|
|
208
|
+
raise _error(response, data)
|
|
209
|
+
return data
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class Apis:
|
|
213
|
+
"""The public API catalog (no key needed)."""
|
|
214
|
+
|
|
215
|
+
def __init__(self, client: DataGuru) -> None:
|
|
216
|
+
self._c = client
|
|
217
|
+
|
|
218
|
+
def list(self, *, category: Optional[str] = None, refresh: bool = False) -> List[dict]:
|
|
219
|
+
"""Every live API with its slug, endpoint path, method, parameters, pricing and limits."""
|
|
220
|
+
apis = list(self._index(refresh)[1].values())
|
|
221
|
+
if category:
|
|
222
|
+
apis = [a for a in apis if (a.get("category") or "").lower() == category.lower()]
|
|
223
|
+
return apis
|
|
224
|
+
|
|
225
|
+
def search(self, query: str, *, limit: int = 10) -> List[dict]:
|
|
226
|
+
"""Simple keyword search over API names, slugs, vendors, categories and descriptions."""
|
|
227
|
+
words = [w for w in re.split(r"\W+", query.lower()) if w]
|
|
228
|
+
scored = []
|
|
229
|
+
for a in self.list():
|
|
230
|
+
name = f"{a.get('name', '')} {a.get('slug', '')} {a.get('vendor_name', '')}".lower()
|
|
231
|
+
rest = f"{a.get('category', '')} {a.get('description', '')}".lower()
|
|
232
|
+
score = sum(3 * (w in name) + (w in rest) for w in words)
|
|
233
|
+
if score and all(w in name or w in rest for w in words):
|
|
234
|
+
scored.append((score, -int(a.get("display_order") or 0), a))
|
|
235
|
+
scored.sort(key=lambda t: (t[0], t[1]), reverse=True)
|
|
236
|
+
return [a for *_, a in scored[:limit]]
|
|
237
|
+
|
|
238
|
+
def get(self, api: str) -> dict:
|
|
239
|
+
"""Full details for one API (slug or endpoint path): parameters, pricing, limits and an example response."""
|
|
240
|
+
spec = self._resolve(api)
|
|
241
|
+
page = self._c._request("GET", f"/api/v1/product-pages/{spec['slug']}/", auth=False)
|
|
242
|
+
details = dict(spec)
|
|
243
|
+
data = (page or {}).get("data") or {}
|
|
244
|
+
for key in ("endpoint_url", "sample_response", "response_fields", "free_balance", "docs_slug"):
|
|
245
|
+
if data.get(key) is not None:
|
|
246
|
+
details[key] = data[key]
|
|
247
|
+
details["docs_url"] = f"https://dataguru.cc/documentation/{data.get('docs_slug') or spec['slug']}/"
|
|
248
|
+
return details
|
|
249
|
+
|
|
250
|
+
def _index(self, refresh: bool = False) -> tuple:
|
|
251
|
+
cached = self._c._catalog
|
|
252
|
+
if cached and not refresh and time.monotonic() - cached[0] < CATALOG_TTL:
|
|
253
|
+
return cached
|
|
254
|
+
body = self._c._request("GET", "/api/v1/marketplace/", auth=False)
|
|
255
|
+
apis = [a for a in (body or {}).get("apis") or [] if (a.get("status") or "active").lower() == "active"]
|
|
256
|
+
by_slug = {a["slug"]: a for a in apis}
|
|
257
|
+
by_path = {a["endpoint_path"].strip("/"): a for a in apis}
|
|
258
|
+
self._c._catalog = (time.monotonic(), by_slug, by_path)
|
|
259
|
+
return self._c._catalog
|
|
260
|
+
|
|
261
|
+
def _resolve(self, api: str) -> dict:
|
|
262
|
+
key = (api or "").strip()
|
|
263
|
+
if key.startswith(("http://", "https://")):
|
|
264
|
+
key = re.sub(r"^https?://[^/]+/api/v1/", "", key)
|
|
265
|
+
key = key.strip("/")
|
|
266
|
+
if key.startswith("api/v1/"):
|
|
267
|
+
key = key[len("api/v1/"):]
|
|
268
|
+
for refresh in (False, True): # a new API may have launched since the catalog was cached
|
|
269
|
+
_, by_slug, by_path = self._index(refresh)
|
|
270
|
+
spec = by_slug.get(key) or by_path.get(key)
|
|
271
|
+
if spec:
|
|
272
|
+
return spec
|
|
273
|
+
raise DataGuruError(f"No DataGuru API '{api}'. Browse https://dataguru.cc/apis or use dg.apis.search().")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class Jobs:
|
|
277
|
+
"""Async jobs: submit now, collect the result later. Funds are held on submit and only charged on success."""
|
|
278
|
+
|
|
279
|
+
def __init__(self, client: DataGuru) -> None:
|
|
280
|
+
self._c = client
|
|
281
|
+
|
|
282
|
+
def submit(self, api: str, params: Optional[Mapping[str, Any]] = None, /, **kwargs: Any) -> dict:
|
|
283
|
+
"""Queues a call and returns ``{"job_id", "status", "reserved_amount", ...}`` immediately."""
|
|
284
|
+
spec = self._c.apis._resolve(api)
|
|
285
|
+
payload = {"endpoint_path": spec["endpoint_path"], "parameters": {**(params or {}), **kwargs}}
|
|
286
|
+
return self._c._request("POST", "/api/v1/jobs/submit/", json=payload, billed=True)
|
|
287
|
+
|
|
288
|
+
def get(self, job_id: str) -> dict:
|
|
289
|
+
"""Current job state. Completed jobs include ``data`` and ``telemetry``; failed ones an ``error``."""
|
|
290
|
+
return self._c._request("GET", f"/api/v1/jobs/{job_id}/")
|
|
291
|
+
|
|
292
|
+
def wait(self, job_id: str, *, timeout: Optional[float] = 600.0, poll_interval: float = 2.0) -> Any:
|
|
293
|
+
"""Polls until the job finishes and returns its ``data``. Raises JobFailedError or TimeoutError."""
|
|
294
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
295
|
+
interval = poll_interval
|
|
296
|
+
while True:
|
|
297
|
+
job = self._get_any(job_id)
|
|
298
|
+
status = job.get("status")
|
|
299
|
+
if status == "COMPLETED":
|
|
300
|
+
return job.get("data")
|
|
301
|
+
if status in JOB_FAILED:
|
|
302
|
+
raise JobFailedError(job)
|
|
303
|
+
if deadline is not None and time.monotonic() + interval > deadline:
|
|
304
|
+
raise TimeoutError(f"Job {job_id} still {status} after {timeout:g}s; it keeps running — check later.")
|
|
305
|
+
time.sleep(interval)
|
|
306
|
+
interval = min(interval * 1.5, 15.0)
|
|
307
|
+
|
|
308
|
+
def run(self, api: str, params: Optional[Mapping[str, Any]] = None, /, *, timeout: Optional[float] = 600.0,
|
|
309
|
+
**kwargs: Any) -> Any:
|
|
310
|
+
"""``submit`` + ``wait`` in one go."""
|
|
311
|
+
job = self.submit(api, params, **kwargs)
|
|
312
|
+
return self.wait(job["job_id"], timeout=timeout)
|
|
313
|
+
|
|
314
|
+
def _get_any(self, job_id: str) -> dict:
|
|
315
|
+
# Failed jobs come back as HTTP 200 with success=false; read them without raising.
|
|
316
|
+
response = self._c._send("GET", f"/api/v1/jobs/{job_id}/")
|
|
317
|
+
return response.json()
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class Batches:
|
|
321
|
+
"""Batch processing: upload a CSV (one request per row), follow progress, download results."""
|
|
322
|
+
|
|
323
|
+
def __init__(self, client: DataGuru) -> None:
|
|
324
|
+
self._c = client
|
|
325
|
+
|
|
326
|
+
def create(self, api: str, file: FileInput, *, file_name: Optional[str] = None) -> dict:
|
|
327
|
+
"""Uploads a CSV whose columns are the API's parameter names. Returns the batch with its ``batch_id``.
|
|
328
|
+
|
|
329
|
+
Funds are held a chunk of rows at a time; if the balance runs out the batch pauses
|
|
330
|
+
(status ``WAITING_FOR_FUNDS``) and resumes after a top-up.
|
|
331
|
+
"""
|
|
332
|
+
spec = self._c.apis._resolve(api)
|
|
333
|
+
name, content, ctype = _file_tuple(file, "batch.csv")
|
|
334
|
+
if file_name:
|
|
335
|
+
name = file_name
|
|
336
|
+
return self._c._request(
|
|
337
|
+
"POST", "/api/v1/batches/",
|
|
338
|
+
data={"endpoint_path": spec["endpoint_path"]},
|
|
339
|
+
files={"file": (name, content, ctype if ctype != "application/octet-stream" else "text/csv")},
|
|
340
|
+
billed=True,
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
def get(self, batch_id: str) -> dict:
|
|
344
|
+
"""Status, row counts (``rows``), ``progress`` (0-1) and ``billing`` of a batch."""
|
|
345
|
+
return self._c._request("GET", f"/api/v1/batches/{batch_id}/")
|
|
346
|
+
|
|
347
|
+
def list(self, *, status: Optional[str] = None, page: int = 1, page_size: int = 20) -> dict:
|
|
348
|
+
"""Your batches, newest first. ``status`` may be ACTIVE, PROCESSING, WAITING_FOR_FUNDS, COMPLETED, CANCELLED or EXPIRED."""
|
|
349
|
+
params = {"page": page, "page_size": page_size}
|
|
350
|
+
if status:
|
|
351
|
+
params["status"] = status.upper()
|
|
352
|
+
return self._c._request("GET", "/api/v1/batches/", params=params)
|
|
353
|
+
|
|
354
|
+
def cancel(self, batch_id: str) -> dict:
|
|
355
|
+
"""Stops a batch. Rows not yet started are cancelled and refunded; running rows finish."""
|
|
356
|
+
return self._c._request("POST", f"/api/v1/batches/{batch_id}/cancel/")
|
|
357
|
+
|
|
358
|
+
def rows(self, batch_id: str, *, status: Optional[str] = None, page: int = 1, page_size: int = 100) -> dict:
|
|
359
|
+
"""Per-row status without result payloads. ``status``: succeeded, failed or pending."""
|
|
360
|
+
params: Dict[str, Any] = {"page": page, "page_size": page_size}
|
|
361
|
+
if status:
|
|
362
|
+
params["status"] = status.lower()
|
|
363
|
+
return self._c._request("GET", f"/api/v1/batches/{batch_id}/rows/", params=params)
|
|
364
|
+
|
|
365
|
+
def wait(self, batch_id: str, *, timeout: Optional[float] = None, poll_interval: float = 10.0) -> dict:
|
|
366
|
+
"""Polls until the batch finishes (completed, cancelled or expired) and returns its final state."""
|
|
367
|
+
deadline = None if timeout is None else time.monotonic() + timeout
|
|
368
|
+
while True:
|
|
369
|
+
batch = self.get(batch_id)
|
|
370
|
+
if batch.get("finished"):
|
|
371
|
+
return batch
|
|
372
|
+
if deadline is not None and time.monotonic() + poll_interval > deadline:
|
|
373
|
+
raise TimeoutError(
|
|
374
|
+
f"Batch {batch_id} is {batch.get('status')} at {batch.get('progress', 0):.0%} after {timeout:g}s; "
|
|
375
|
+
"it keeps running — check later."
|
|
376
|
+
)
|
|
377
|
+
time.sleep(poll_interval)
|
|
378
|
+
|
|
379
|
+
def results(self, batch_id: str) -> List[dict]:
|
|
380
|
+
"""All rows as a list of ``{input, status, data | error, ...}``. Pending rows show status PENDING."""
|
|
381
|
+
return self._c._request("GET", f"/api/v1/batches/{batch_id}/results.json")
|
|
382
|
+
|
|
383
|
+
def iter_results(self, batch_id: str) -> Iterator[dict]:
|
|
384
|
+
"""Streams rows one at a time (JSON Lines) — use this for very large batches."""
|
|
385
|
+
import json
|
|
386
|
+
|
|
387
|
+
response = self._c._send("GET", f"/api/v1/batches/{batch_id}/results.jsonl", stream=True)
|
|
388
|
+
try:
|
|
389
|
+
for line in response.iter_lines():
|
|
390
|
+
if line.strip():
|
|
391
|
+
yield json.loads(line)
|
|
392
|
+
finally:
|
|
393
|
+
response.close()
|
|
394
|
+
|
|
395
|
+
def download(self, batch_id: str, path: Union[str, os.PathLike], *, format: Optional[str] = None) -> Path:
|
|
396
|
+
"""Saves results to ``path``. ``format`` is json, jsonl or csv (the CSV is a per-row summary
|
|
397
|
+
without the data payloads); by default it is taken from the file extension."""
|
|
398
|
+
dest = Path(path)
|
|
399
|
+
fmt = (format or dest.suffix.lstrip(".") or "json").lower()
|
|
400
|
+
if fmt not in ("json", "jsonl", "csv"):
|
|
401
|
+
raise DataGuruError("format must be 'json', 'jsonl' or 'csv'.")
|
|
402
|
+
response = self._c._send("GET", f"/api/v1/batches/{batch_id}/results.{fmt}", stream=True)
|
|
403
|
+
try:
|
|
404
|
+
with dest.open("wb") as fh:
|
|
405
|
+
for chunk in response.iter_bytes():
|
|
406
|
+
fh.write(chunk)
|
|
407
|
+
finally:
|
|
408
|
+
response.close()
|
|
409
|
+
return dest
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
# -- helpers ---------------------------------------------------------------------------------
|
|
413
|
+
def _file_tuple(value: FileInput, default_name: str) -> tuple:
|
|
414
|
+
if isinstance(value, (str, os.PathLike)):
|
|
415
|
+
p = Path(value)
|
|
416
|
+
return (p.name, p.read_bytes(), _guess_type(p.name))
|
|
417
|
+
if isinstance(value, (bytes, bytearray)):
|
|
418
|
+
return (default_name, bytes(value), _guess_type(default_name))
|
|
419
|
+
if hasattr(value, "read"):
|
|
420
|
+
name = os.path.basename(getattr(value, "name", "") or "") or default_name
|
|
421
|
+
return (name, value.read(), _guess_type(name))
|
|
422
|
+
if isinstance(value, tuple):
|
|
423
|
+
return value
|
|
424
|
+
raise DataGuruError(f"Unsupported file value for '{default_name}': {type(value).__name__}")
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _guess_type(name: str) -> str:
|
|
428
|
+
import mimetypes
|
|
429
|
+
|
|
430
|
+
return mimetypes.guess_type(name)[0] or "application/octet-stream"
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _query_value(value: Any) -> Any:
|
|
434
|
+
if isinstance(value, bool):
|
|
435
|
+
return "true" if value else "false"
|
|
436
|
+
return value
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _form_value(value: Any) -> str:
|
|
440
|
+
if isinstance(value, bool):
|
|
441
|
+
return "true" if value else "false"
|
|
442
|
+
if isinstance(value, (dict, list)):
|
|
443
|
+
import json
|
|
444
|
+
|
|
445
|
+
return json.dumps(value)
|
|
446
|
+
return str(value)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _retry_after(response: httpx.Response) -> Optional[float]:
|
|
450
|
+
raw = response.headers.get("Retry-After")
|
|
451
|
+
try:
|
|
452
|
+
return max(0.0, float(raw)) if raw else None
|
|
453
|
+
except ValueError:
|
|
454
|
+
return None
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _backoff(attempt: int) -> float:
|
|
458
|
+
return min(0.5 * 2 ** (attempt - 1), 8.0) + random.uniform(0, 0.25)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _error(response: httpx.Response, body: Any = None) -> Exception:
|
|
462
|
+
if body is None:
|
|
463
|
+
try:
|
|
464
|
+
body = response.json()
|
|
465
|
+
except ValueError:
|
|
466
|
+
body = response.text
|
|
467
|
+
return error_for(response.status_code, body, response.headers.get("X-Request-ID"), _retry_after(response))
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Exceptions raised by the DataGuru client."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any, Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class DataGuruError(Exception):
|
|
8
|
+
"""Base class for every error raised by this package."""
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class APIError(DataGuruError):
|
|
12
|
+
"""The API answered with an error status (or ``"success": false``).
|
|
13
|
+
|
|
14
|
+
Attributes:
|
|
15
|
+
status_code: HTTP status of the response.
|
|
16
|
+
code: DataGuru error code when the API sent one (e.g. ``"INSUFFICIENT_BALANCE"``).
|
|
17
|
+
message: Human-readable error message.
|
|
18
|
+
details: Extra error details, such as per-parameter validation errors.
|
|
19
|
+
request_id: The ``X-Request-ID`` of the call; include it when contacting support.
|
|
20
|
+
body: The decoded response body.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
message: str,
|
|
26
|
+
*,
|
|
27
|
+
status_code: int,
|
|
28
|
+
code: Optional[str] = None,
|
|
29
|
+
details: Any = None,
|
|
30
|
+
request_id: Optional[str] = None,
|
|
31
|
+
body: Any = None,
|
|
32
|
+
) -> None:
|
|
33
|
+
super().__init__(message)
|
|
34
|
+
self.message = message
|
|
35
|
+
self.status_code = status_code
|
|
36
|
+
self.code = code
|
|
37
|
+
self.details = details
|
|
38
|
+
self.request_id = request_id
|
|
39
|
+
self.body = body
|
|
40
|
+
|
|
41
|
+
def __str__(self) -> str:
|
|
42
|
+
parts = [f"HTTP {self.status_code}"]
|
|
43
|
+
if self.code:
|
|
44
|
+
parts.append(self.code)
|
|
45
|
+
text = f"[{' '.join(parts)}] {self.message}"
|
|
46
|
+
if self.details:
|
|
47
|
+
text += f" — {self.details}"
|
|
48
|
+
if self.request_id:
|
|
49
|
+
text += f" (request_id={self.request_id})"
|
|
50
|
+
return text
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ValidationError(APIError):
|
|
54
|
+
"""400: a parameter is missing or invalid. See ``details``."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class AuthenticationError(APIError):
|
|
58
|
+
"""401/403: the API key is missing, invalid, revoked or lacks access."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class InsufficientBalanceError(APIError):
|
|
62
|
+
"""402: the account balance is too low for this request. Top up at https://dashboard.dataguru.cc."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class NotFoundError(APIError):
|
|
66
|
+
"""404: the API, job or batch does not exist (or belongs to another account)."""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class ConflictError(APIError):
|
|
70
|
+
"""409: the resource is in a state that does not allow this action (e.g. cancelling a finished batch)."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class RateLimitError(APIError):
|
|
74
|
+
"""429: too many requests. ``retry_after`` holds the server's suggested wait in seconds, if sent."""
|
|
75
|
+
|
|
76
|
+
def __init__(self, *args: Any, retry_after: Optional[float] = None, **kwargs: Any) -> None:
|
|
77
|
+
super().__init__(*args, **kwargs)
|
|
78
|
+
self.retry_after = retry_after
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class ServerError(APIError):
|
|
82
|
+
"""5xx: DataGuru or the upstream site failed. Usually safe to retry later."""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class JobFailedError(DataGuruError):
|
|
86
|
+
"""An async job finished as FAILED, EXPIRED or CANCELLED. Failed jobs are not billed."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, job: dict) -> None:
|
|
89
|
+
self.job = job
|
|
90
|
+
self.job_id = job.get("job_id")
|
|
91
|
+
self.status = job.get("status")
|
|
92
|
+
err = job.get("error") or {}
|
|
93
|
+
self.code = err.get("code") if isinstance(err, dict) else None
|
|
94
|
+
msg = err.get("message") if isinstance(err, dict) else str(err or "")
|
|
95
|
+
super().__init__(f"Job {self.job_id} {str(self.status).lower()}: {msg or 'no details'}")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class TimeoutError(DataGuruError): # noqa: A001 - deliberately scoped to this package
|
|
99
|
+
"""Waiting for a job or batch exceeded the given timeout. The job/batch keeps running server-side."""
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
_BY_STATUS = {
|
|
103
|
+
400: ValidationError,
|
|
104
|
+
401: AuthenticationError,
|
|
105
|
+
403: AuthenticationError,
|
|
106
|
+
402: InsufficientBalanceError,
|
|
107
|
+
404: NotFoundError,
|
|
108
|
+
409: ConflictError,
|
|
109
|
+
429: RateLimitError,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def error_for(status_code: int, body: Any, request_id: Optional[str], retry_after: Optional[float]) -> APIError:
|
|
114
|
+
"""Builds the right APIError subclass from any of the API's error body shapes."""
|
|
115
|
+
code = message = details = None
|
|
116
|
+
if isinstance(body, dict):
|
|
117
|
+
err = body.get("error")
|
|
118
|
+
if isinstance(err, dict): # {"error": {"code": ..., "message": ...}}
|
|
119
|
+
code, message, details = err.get("code"), err.get("message"), err.get("details")
|
|
120
|
+
elif isinstance(err, str):
|
|
121
|
+
# {"error": "message", "code": ...} or {"error": "code_slug", "message": "..."}
|
|
122
|
+
if body.get("message"):
|
|
123
|
+
code, message = err, body["message"]
|
|
124
|
+
else:
|
|
125
|
+
message, code = err, body.get("code")
|
|
126
|
+
message = message or body.get("message") or body.get("detail")
|
|
127
|
+
details = details or body.get("details")
|
|
128
|
+
request_id = request_id or body.get("request_id")
|
|
129
|
+
code = code or body.get("code")
|
|
130
|
+
elif isinstance(body, str) and body.strip():
|
|
131
|
+
message = body.strip()[:500]
|
|
132
|
+
message = str(message or f"Request failed with HTTP {status_code}")
|
|
133
|
+
|
|
134
|
+
cls = _BY_STATUS.get(status_code) or (ServerError if status_code >= 500 else APIError)
|
|
135
|
+
kwargs = dict(status_code=status_code, code=code, details=details, request_id=request_id, body=body)
|
|
136
|
+
if cls is RateLimitError:
|
|
137
|
+
return RateLimitError(message, retry_after=retry_after, **kwargs)
|
|
138
|
+
return cls(message, **kwargs)
|
|
File without changes
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import pytest
|
|
5
|
+
import respx
|
|
6
|
+
|
|
7
|
+
from dataguru import (
|
|
8
|
+
AuthenticationError,
|
|
9
|
+
DataGuru,
|
|
10
|
+
DataGuruError,
|
|
11
|
+
InsufficientBalanceError,
|
|
12
|
+
JobFailedError,
|
|
13
|
+
RateLimitError,
|
|
14
|
+
ValidationError,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
BASE = "https://api.dataguru.cc"
|
|
18
|
+
CATALOG = {
|
|
19
|
+
"count": 3,
|
|
20
|
+
"apis": [
|
|
21
|
+
{
|
|
22
|
+
"slug": "amazon-products-search", "name": "Amazon Product Search", "category": "E-Commerce",
|
|
23
|
+
"description": "Search for products on Amazon.", "endpoint_path": "amazon/products/search",
|
|
24
|
+
"http_method": "POST", "status": "active", "vendor_name": "Amazon", "display_order": 1,
|
|
25
|
+
"parameters": [{"name": "product_url", "data_type": "string", "location": "BODY", "required": True}],
|
|
26
|
+
"pricing": {"customer_price": 0.0012},
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
"slug": "inspiring-quotes", "name": "Inspiring Quotes", "category": "Utility",
|
|
30
|
+
"description": "Random quotes.", "endpoint_path": "quotes/random", "http_method": "GET",
|
|
31
|
+
"status": "active", "vendor_name": "Zen Quotes", "display_order": 5,
|
|
32
|
+
"parameters": [{"name": "limit", "data_type": "integer", "location": "QUERY", "required": False}],
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
"slug": "pdf-parser", "name": "PDF Parser", "category": "Documents", "description": "Parse PDFs.",
|
|
36
|
+
"endpoint_path": "documents/pdf/parse", "http_method": "POST", "status": "active",
|
|
37
|
+
"parameters": [
|
|
38
|
+
{"name": "file", "data_type": "file", "location": "BODY", "required": True},
|
|
39
|
+
{"name": "pages", "data_type": "string", "location": "BODY", "required": False},
|
|
40
|
+
],
|
|
41
|
+
},
|
|
42
|
+
],
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@pytest.fixture
|
|
47
|
+
def dg():
|
|
48
|
+
with respx.mock(base_url=BASE, assert_all_called=False) as mock:
|
|
49
|
+
mock.get("/api/v1/marketplace/").respond(json=CATALOG)
|
|
50
|
+
client = DataGuru(api_key="pk.secret", max_retries=2)
|
|
51
|
+
client._mock = mock
|
|
52
|
+
yield client
|
|
53
|
+
client.close()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_call_post_by_slug_sends_json_and_key(dg):
|
|
57
|
+
route = dg._mock.post("/api/v1/amazon/products/search").respond(json={"title": "Echo"})
|
|
58
|
+
assert dg.call("amazon-products-search", product_url="https://amazon.com/dp/B000000000") == {"title": "Echo"}
|
|
59
|
+
req = route.calls.last.request
|
|
60
|
+
assert req.headers["Authorization"] == "Api-Key pk.secret"
|
|
61
|
+
assert json.loads(req.content) == {"product_url": "https://amazon.com/dp/B000000000"}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_call_get_by_path_uses_query(dg):
|
|
65
|
+
route = dg._mock.get("/api/v1/quotes/random").respond(json=[{"q": "hi"}])
|
|
66
|
+
assert dg.call("/quotes/random", {"limit": 2}) == [{"q": "hi"}]
|
|
67
|
+
assert route.calls.last.request.url.params["limit"] == "2"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def test_call_file_param_is_multipart(dg):
|
|
71
|
+
route = dg._mock.post("/api/v1/documents/pdf/parse").respond(json={"text": "x"})
|
|
72
|
+
dg.call("pdf-parser", file=b"%PDF-1.4", pages="1-2")
|
|
73
|
+
req = route.calls.last.request
|
|
74
|
+
assert req.headers["Content-Type"].startswith("multipart/form-data")
|
|
75
|
+
assert b"%PDF-1.4" in req.content and b"1-2" in req.content
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_unknown_and_missing_params_fail_locally(dg):
|
|
79
|
+
with pytest.raises(DataGuruError, match="Unknown"):
|
|
80
|
+
dg.call("amazon-products-search", product_url="u", bogus=1)
|
|
81
|
+
with pytest.raises(DataGuruError, match="Missing"):
|
|
82
|
+
dg.call("amazon-products-search")
|
|
83
|
+
with pytest.raises(DataGuruError, match="No DataGuru API"):
|
|
84
|
+
dg.call("nope")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_error_mapping(dg):
|
|
88
|
+
dg._mock.post("/api/v1/amazon/products/search").mock(side_effect=[
|
|
89
|
+
httpx.Response(402, json={"success": False, "error": "Insufficient balance", "code": "INSUFFICIENT_BALANCE"}),
|
|
90
|
+
httpx.Response(400, json={"success": False, "error": "Validation error", "details": {"product_url": ["bad"]}}),
|
|
91
|
+
httpx.Response(401, json={"detail": "Authentication credentials were not provided."}),
|
|
92
|
+
httpx.Response(429, json={"success": False, "error": {"code": "RATE_LIMITED", "message": "slow down"}},
|
|
93
|
+
headers={"Retry-After": "7", "X-Request-ID": "req-1"}),
|
|
94
|
+
])
|
|
95
|
+
with pytest.raises(InsufficientBalanceError) as e:
|
|
96
|
+
dg.call("amazon-products-search", product_url="u")
|
|
97
|
+
assert e.value.code == "INSUFFICIENT_BALANCE"
|
|
98
|
+
with pytest.raises(ValidationError) as e:
|
|
99
|
+
dg.call("amazon-products-search", product_url="u")
|
|
100
|
+
assert e.value.details == {"product_url": ["bad"]}
|
|
101
|
+
with pytest.raises(AuthenticationError, match="credentials"):
|
|
102
|
+
dg.call("amazon-products-search", product_url="u")
|
|
103
|
+
with pytest.raises(RateLimitError) as e: # billed call: not retried
|
|
104
|
+
dg.call("amazon-products-search", product_url="u")
|
|
105
|
+
assert e.value.retry_after == 7 and e.value.request_id == "req-1" and e.value.code == "RATE_LIMITED"
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def test_reads_retry_but_billed_calls_do_not(dg, monkeypatch):
|
|
109
|
+
monkeypatch.setattr("time.sleep", lambda s: None)
|
|
110
|
+
job = dg._mock.get("/api/v1/jobs/j1/").mock(side_effect=[
|
|
111
|
+
httpx.Response(503), httpx.Response(200, json={"success": True, "status": "PROCESSING"}),
|
|
112
|
+
])
|
|
113
|
+
assert dg.jobs.get("j1")["status"] == "PROCESSING" and job.call_count == 2
|
|
114
|
+
call = dg._mock.post("/api/v1/amazon/products/search").respond(503, json={"success": False, "error": "down"})
|
|
115
|
+
with pytest.raises(DataGuruError):
|
|
116
|
+
dg.call("amazon-products-search", product_url="u")
|
|
117
|
+
assert call.call_count == 1
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_missing_key_is_clear(monkeypatch):
|
|
121
|
+
monkeypatch.delenv("DATAGURU_API_KEY", raising=False)
|
|
122
|
+
with respx.mock(base_url=BASE) as mock:
|
|
123
|
+
mock.get("/api/v1/marketplace/").respond(json=CATALOG)
|
|
124
|
+
with pytest.raises(DataGuruError, match="No API key"):
|
|
125
|
+
DataGuru().call("inspiring-quotes")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def test_search_and_list(dg):
|
|
129
|
+
assert [a["slug"] for a in dg.apis.search("amazon")] == ["amazon-products-search"]
|
|
130
|
+
assert [a["slug"] for a in dg.apis.list(category="utility")] == ["inspiring-quotes"]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def test_jobs_submit_and_wait(dg, monkeypatch):
|
|
134
|
+
monkeypatch.setattr("time.sleep", lambda s: None)
|
|
135
|
+
sub = dg._mock.post("/api/v1/jobs/submit/").respond(202, json={"success": True, "job_id": "j2", "status": "SUBMITTED"})
|
|
136
|
+
dg._mock.get("/api/v1/jobs/j2/").mock(side_effect=[
|
|
137
|
+
httpx.Response(200, json={"success": True, "status": "QUEUED"}),
|
|
138
|
+
httpx.Response(200, json={"success": True, "status": "COMPLETED", "data": {"ok": 1}}),
|
|
139
|
+
])
|
|
140
|
+
assert dg.jobs.run("amazon-products-search", product_url="u") == {"ok": 1}
|
|
141
|
+
assert json.loads(sub.calls.last.request.content) == {
|
|
142
|
+
"endpoint_path": "amazon/products/search", "parameters": {"product_url": "u"},
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def test_job_failure(dg):
|
|
147
|
+
dg._mock.get("/api/v1/jobs/j3/").respond(json={
|
|
148
|
+
"success": False, "job_id": "j3", "status": "FAILED", "error": {"code": "NOT_FOUND", "message": "gone"},
|
|
149
|
+
})
|
|
150
|
+
with pytest.raises(JobFailedError) as e:
|
|
151
|
+
dg.jobs.wait("j3")
|
|
152
|
+
assert e.value.code == "NOT_FOUND"
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def test_batches(dg, tmp_path, monkeypatch):
|
|
156
|
+
monkeypatch.setattr("time.sleep", lambda s: None)
|
|
157
|
+
csv = tmp_path / "rows.csv"
|
|
158
|
+
csv.write_text("product_url\nhttps://amazon.com/dp/B000000000\n")
|
|
159
|
+
create = dg._mock.post("/api/v1/batches/").respond(202, json={"success": True, "batch_id": "b1", "finished": False})
|
|
160
|
+
dg._mock.get("/api/v1/batches/b1/").mock(side_effect=[
|
|
161
|
+
httpx.Response(200, json={"success": True, "finished": False, "status": "PROCESSING", "progress": 0.5}),
|
|
162
|
+
httpx.Response(200, json={"success": True, "finished": True, "status": "COMPLETED", "progress": 1.0}),
|
|
163
|
+
])
|
|
164
|
+
dg._mock.get("/api/v1/batches/b1/results.jsonl").respond(text='{"status": "SUCCEEDED"}\n{"status": "FAILED"}\n')
|
|
165
|
+
dg._mock.get("/api/v1/batches/b1/results.csv").respond(text="product_url,status\n")
|
|
166
|
+
|
|
167
|
+
assert dg.batches.create("amazon-products-search", csv)["batch_id"] == "b1"
|
|
168
|
+
body = create.calls.last.request.content
|
|
169
|
+
assert b'name="endpoint_path"' in body and b"amazon/products/search" in body and b'filename="rows.csv"' in body
|
|
170
|
+
assert dg.batches.wait("b1")["status"] == "COMPLETED"
|
|
171
|
+
assert [r["status"] for r in dg.batches.iter_results("b1")] == ["SUCCEEDED", "FAILED"]
|
|
172
|
+
out = dg.batches.download("b1", tmp_path / "out.csv")
|
|
173
|
+
assert out.read_text() == "product_url,status\n"
|