Skip to content

Commit 6ea18c6

Browse files
Noah Bennettclaude
andcommitted
Release 0.1.6: 120s default timeout, error .code for both error shapes
- Default timeout 60s -> 120s (the API's own ceiling; slow successful scrapes run 70s+). - AmazonScraperAPIError.code and error_code(): reads both {error: code} and {error: {code: ...}}; the message now shows the code. - README: examples match the real response shape, error table matches the API, 502 retry advice 60s, removed claims of client-side retries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f365495 commit 6ea18c6

4 files changed

Lines changed: 68 additions & 44 deletions

File tree

‎README.md‎

Lines changed: 40 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -40,29 +40,33 @@ asa = AmazonScraperAPI(api_key="asa_live_...")
4040
product = asa.product(query="B09HN3Q81F", domain="com")
4141

4242
print(product["title"])
43-
# "Apple AirPods Pro (2nd Generation)..."
44-
print(product["price"]["current"])
45-
# 199.00
46-
print(product["rating"]["average"], product["rating"]["count"])
47-
# 4.7 58214
43+
# "LEGEND COOKWARE 5-Ply Stainless Steel Cookware Set, 14-Piece..."
44+
print(product["price"], product["currency"])
45+
# 549.99 USD
46+
print(product["rating"], product["reviews_count"])
47+
# 4.5 865
4848
```
4949

50-
### Example output (trimmed)
50+
### Example output (trimmed, ~55 fields in total)
5151

5252
```python
5353
{
5454
"asin": "B09HN3Q81F",
55-
"title": "Apple AirPods Pro (2nd Generation)...",
56-
"brand": "Apple",
57-
"price": {"current": 199.00, "currency": "USD", "was": 249.00, "savings_pct": 20},
58-
"rating": {"average": 4.7, "count": 58214, "distribution": {"5": 0.81, "4": 0.12}},
59-
"availability": "In Stock",
60-
"buybox": {"seller": "Amazon.com", "ships_from": "Amazon.com", "prime": True},
61-
"images": ["https://m.media-amazon.com/images/I/...jpg"],
62-
"bullets": ["Active Noise Cancellation...", "Adaptive Audio..."],
63-
"variants": [{"asin": "B0BDHB9Y8H", "name": "USB-C", "price": 249.00}],
64-
"categories": ["Electronics", "Headphones", "Earbud Headphones"],
65-
"_meta": {"tier": "direct", "duration_ms": 2634, "marketplace": "amazon.com"},
55+
"title": "LEGEND COOKWARE 5-Ply Stainless Steel Cookware Set, 14-Piece...",
56+
"brand": "LEGEND COOKWARE",
57+
"price": 549.99,
58+
"price_strikethrough": None,
59+
"currency": "USD",
60+
"rating": 4.5,
61+
"reviews_count": 865,
62+
"stock": "In Stock",
63+
"is_prime": True,
64+
"images": ["https://m.media-amazon.com/images/I/71Q3a8JH5NL._AC_SY355_.jpg", "..."],
65+
"bullet_points": "5-PLY STAINLESS STEEL COOKWARE HEATS EVENLY - Five layers of steel...",
66+
"sales_rank": [
67+
{"ladder": [{"name": "Kitchen & Dining", "url": None}], "rank": 36177},
68+
{"ladder": [{"name": "Kitchen Cookware Sets", "url": None}], "rank": 174},
69+
],
6670
}
6771
```
6872

@@ -76,8 +80,9 @@ results = asa.search(
7680
pages=1,
7781
)
7882

79-
for r in results["results"]:
80-
print(r["position"], r["asin"], r["title"], r["price"].get("current"))
83+
for p in results["products"]:
84+
# Sponsored cards have sponsored_position instead of organic_position.
85+
print(p["organic_position"], p["asin"], p["title"], p["price"], p["rating"])
8186
```
8287

8388
## Async batch (up to 1,000 ASINs with webhook callback)
@@ -130,51 +135,51 @@ Building a production-grade Amazon scraper in-house is a 2-4 week engineering pr
130135
| **Amazon CAPTCHAs / robot pages** | Auto-detected, retried through a heavier proxy tier (datacenter, residential, premium) |
131136
| **Brittle CSS selectors** | Extractors update as Amazon changes layouts. Your code stays the same. |
132137
| **20+ marketplaces** | `amazon.de`, `.co.uk`, `.co.jp`, `.com.br`, and more. Each with marketplace-specific parsing quirks. |
133-
| **Country-matched residential IPs** | `amazon.de` auto-routes through German IPs. Pass `country="DE"` to override. |
138+
| **Country-matched residential IPs** | `amazon.de` auto-routes through German IPs. |
134139
| **Rotating proxies + anti-fingerprinting** | TLS fingerprints, headers, cookies handled server-side. |
135-
| **Rate-limit retries** | Transparent exponential backoff. |
136-
| **Structured JSON output** | Title, price, rating, reviews, variants, seller, images. Parsed, typed. |
140+
| **Structured JSON output** | Title, price, rating, reviews, variants, seller, images. Parsed. |
137141
| **Batch/async jobs** | 1,000 ASINs submitted, webhook-delivered on completion. |
138142

139143
**Time saved:** a greenfield Python Amazon scraper built to this spec takes roughly 80 engineer-hours (including anti-bot handling and marketplace variants). This SDK is 10 minutes.
140144

141145
## Error handling
142146

143-
All failures follow a stable shape so you can match on `code`:
147+
Every failed call raises `AmazonScraperAPIError` with `status_code`, `code` (the API's error code, or `None`) and `body` (the parsed JSON body). The SDK does not retry on its own, so match on `e.code` and decide:
144148

145149
```python
146-
from amazonscraperapi import AmazonScraperAPI, AsaError
147150
import time
151+
from amazonscraperapi import AmazonScraperAPI, AmazonScraperAPIError
148152

149153
asa = AmazonScraperAPI(api_key="asa_live_...")
150154

151155
try:
152-
product = asa.product(query="INVALID_ASIN", domain="com")
153-
except AsaError as e:
156+
product = asa.product(query="B09HN3Q81F", domain="com")
157+
except AmazonScraperAPIError as e:
154158
if e.code == "INSUFFICIENT_CREDITS":
155159
pass # top up
156160
elif e.code == "RATE_LIMITED":
157-
time.sleep(e.retry_after)
158-
elif e.code in ("target_unreachable", "amazon-robot-or-human"):
159-
# non-2xx, you were not charged. safe to retry.
160-
pass
161+
time.sleep(e.body["error"].get("retry_after_ms", 1000) / 1000)
162+
elif e.code == "target_unreachable":
163+
time.sleep(60) # not charged; retry once
161164
else:
162165
raise
163166
```
164167

165168
| HTTP | `code` | When you see it | Recommended action |
166169
|---|---|---|---|
167-
| 400 | `INVALID_PARAMS` | Missing `query`, unsupported `domain`, bad `sort_by` | Fix request; don't retry |
170+
| 400 | `invalid_params` | Missing `query`, unsupported `domain`, bad `sort_by` | Fix request; don't retry |
168171
| 401 | `INVALID_API_KEY` | Missing, malformed, revoked | Verify `ASA_API_KEY`; rotate if leaked |
169172
| 402 | `INSUFFICIENT_CREDITS` | Balance empty | Top up; renews each billing cycle |
170-
| 429 | `RATE_LIMITED` | Over 120 req/60s per user | Honor `Retry-After`; retry |
173+
| 404 | `product_not_found` | ASIN delisted, malformed, or not on this marketplace | Don't retry; drop the ASIN |
174+
| 429 | `RATE_LIMITED` | Over request-rate budget | Wait `error.retry_after_ms`; retry |
171175
| 429 | `CONCURRENCY_LIMIT` | Over plan's parallel cap | Reduce parallelism or upgrade. `X-Concurrency-*` headers guide backoff |
172-
| 502 | `target_unreachable` | Amazon down / all proxy tiers blocked | Retry after 30s (already retried through 3 tiers on our side) |
173-
| 502 | `amazon-robot-or-human` | Amazon challenge not resolvable | Retry. Often transient. Not charged |
174-
| 502 | `extraction_failed` | Layout we can't parse | Report with `X-Request-Id`. Not charged |
176+
| 502 | `target_unreachable` | Amazon blocked every internal retry (`last_block_reason` says why) | Retry after 60s or more. Not charged |
177+
| 502 | `extraction_failed` | Layout we can't parse | Retry later; report with `X-Request-Id` if it persists. Not charged |
175178
| 503 | `SERVICE_OVERLOADED` | Global circuit breaker | Honor `Retry-After: 60`. Rare |
176179
| 500 | `INTERNAL_ERROR` | Our bug | Report with `X-Request-Id` |
177180

181+
The default request timeout is 120s (the API's own ceiling); override it with `AmazonScraperAPI(api_key=..., timeout=...)`.
182+
178183
**Flat-credit promise:** non-2xx responses are free. A basic request costs 5 credits (billing unit; end-customer price is $0.90 per 1,000 basic requests PAYG). Future JS-rendered calls will cost 15 credits. Every response has `X-Request-Id` for traceability — quote it in any support ticket.
179184

180185
## Get an API key
@@ -185,7 +190,6 @@ except AsaError as e:
185190

186191
- **Website:** https://www.amazonscraperapi.com/
187192
- **Docs:** https://amazonscraperapi.com/docs
188-
- **Status:** https://amazonscraperapi.com/status
189193
- **Pricing:** https://amazonscraperapi.com/pricing
190194
- **Node SDK:** [amazon-scraper-api-sdk](https://www.npmjs.com/package/amazon-scraper-api-sdk) · **Go SDK:** [github.com/ChocoData-com/amazon-scraper-api-sdk-go](https://github.com/ChocoData-com/amazon-scraper-api-sdk-go) · **CLI:** [amazon-scraper-api-cli](https://www.npmjs.com/package/amazon-scraper-api-cli) · **MCP server:** [amazon-scraper-api-mcp](https://www.npmjs.com/package/amazon-scraper-api-mcp)
191195

‎amazonscraperapi/__init__.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
product = client.product(query="B09HN3Q81F", domain="com")
99
print(product["title"])
1010
"""
11-
from .client import AmazonScraperAPI, AmazonScraperAPIError, verify_webhook_signature
11+
from .client import AmazonScraperAPI, AmazonScraperAPIError, error_code, verify_webhook_signature
1212

13-
__version__ = "0.1.0"
14-
__all__ = ["AmazonScraperAPI", "AmazonScraperAPIError", "verify_webhook_signature"]
13+
__version__ = "0.1.6"
14+
__all__ = ["AmazonScraperAPI", "AmazonScraperAPIError", "error_code", "verify_webhook_signature"]

‎amazonscraperapi/client.py‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,44 @@
88
import httpx
99

1010

11+
def error_code(body: Any) -> Optional[str]:
12+
"""Error code from a response body, or None.
13+
14+
The API returns two shapes: ``{"error": "target_unreachable", ...}`` for
15+
scrape outcomes and ``{"error": {"code": "INVALID_API_KEY", ...}}`` for
16+
account and limit errors.
17+
"""
18+
if not isinstance(body, dict):
19+
return None
20+
err = body.get("error")
21+
if isinstance(err, str):
22+
return err
23+
if isinstance(err, dict) and isinstance(err.get("code"), str):
24+
return err["code"]
25+
return None
26+
27+
1128
class AmazonScraperAPIError(Exception):
1229
"""Raised when the API returns a non-2xx response."""
1330

1431
def __init__(self, status_code: int, body: Any, message: str) -> None:
1532
super().__init__(message)
1633
self.status_code = status_code
1734
self.body = body
35+
#: e.g. ``"target_unreachable"`` or ``"INSUFFICIENT_CREDITS"``
36+
self.code = error_code(body)
1837

1938

2039
class AmazonScraperAPI:
21-
"""Synchronous client. For async, use :class:`AsyncAmazonScraperAPI`."""
40+
"""Synchronous client."""
2241

2342
def __init__(
2443
self,
2544
api_key: str,
2645
*,
2746
base_url: str = "https://api.amazonscraperapi.com",
28-
timeout: float = 60.0,
47+
# 120s: the API's own ceiling. Slow but successful scrapes can take 70s+.
48+
timeout: float = 120.0,
2949
) -> None:
3050
if not api_key:
3151
raise ValueError("api_key is required")
@@ -34,7 +54,7 @@ def __init__(
3454
self._client = httpx.Client(
3555
timeout=timeout,
3656
headers={
37-
"User-Agent": "amazonscraperapi-python/0.1.0",
57+
"User-Agent": "amazonscraperapi-python/0.1.6",
3858
},
3959
)
4060

@@ -119,7 +139,7 @@ def _request(
119139
except ValueError:
120140
body = None
121141
if not resp.is_success:
122-
err = (body or {}).get("error", "request failed") if isinstance(body, dict) else "request failed"
142+
err = error_code(body) or "request failed"
123143
raise AmazonScraperAPIError(resp.status_code, body, f"HTTP {resp.status_code}: {err}")
124144
return body if isinstance(body, dict) else {}
125145

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
44

55
[project]
66
name = "amazonscraperapi-sdk"
7-
version = "0.1.5"
7+
version = "0.1.6"
88
description = "Official Python client for Amazon Scraper API (https://amazonscraperapi.com)"
99
readme = "README.md"
1010
license = "MIT"

0 commit comments

Comments
 (0)