findcheap 0.1.0__py3-none-any.whl
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.
findcheap/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""The Findcheap API in Python: where the product on a page is sold for less.
|
|
2
|
+
|
|
3
|
+
from findcheap import Findcheap
|
|
4
|
+
fc = Findcheap() # FINDCHEAP_API_KEY in the environment
|
|
5
|
+
answer = fc.search("https://www.jlab.com/products/jbuds-lux-anc-headphones")
|
|
6
|
+
|
|
7
|
+
Reference: https://findcheap.ai/developers/docs.md
|
|
8
|
+
"""
|
|
9
|
+
from .client import (
|
|
10
|
+
Findcheap,
|
|
11
|
+
FindcheapApiError,
|
|
12
|
+
FindcheapConnectionError,
|
|
13
|
+
FindcheapError,
|
|
14
|
+
Card,
|
|
15
|
+
ReadAnswer,
|
|
16
|
+
ResolveAnswer,
|
|
17
|
+
SearchAnswer,
|
|
18
|
+
SearchEcho,
|
|
19
|
+
__version__,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"Findcheap", "FindcheapError", "FindcheapApiError", "FindcheapConnectionError",
|
|
24
|
+
"Card", "ReadAnswer", "ResolveAnswer", "SearchAnswer", "SearchEcho", "__version__",
|
|
25
|
+
]
|
findcheap/client.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""The client: three POSTs over urllib, the answer as the API sends it.
|
|
2
|
+
|
|
3
|
+
Nothing is reshaped. A search answer opens with `request_id` and `search`
|
|
4
|
+
(what was searched), then `product`, `product_name`, `same_product`,
|
|
5
|
+
`similar_products`, `page_is_cheapest`, `credits_used`; the TypedDicts
|
|
6
|
+
below name the fields for an editor, and `extra="allow"` on the API's
|
|
7
|
+
side means a field added later arrives here untouched.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import socket
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.request
|
|
16
|
+
from typing import Any, Dict, List, Literal, Optional, TypedDict
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
|
19
|
+
|
|
20
|
+
DEFAULT_BASE_URL = "https://api.findcheap.ai"
|
|
21
|
+
# Above the API's own walls (a search answers within 90 s, a read within 30),
|
|
22
|
+
# so the API's timeout envelope, not a client cut-off, is what a caller sees.
|
|
23
|
+
SEARCH_TIMEOUT_S = 100.0
|
|
24
|
+
EXTRACT_TIMEOUT_S = 40.0
|
|
25
|
+
RESOLVE_TIMEOUT_S = 20.0
|
|
26
|
+
|
|
27
|
+
Condition = Literal["new", "used"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SearchEcho(TypedDict):
|
|
31
|
+
"""What was searched: the address as sent, the market the search ran in, the condition, the cap."""
|
|
32
|
+
url: str
|
|
33
|
+
market: str
|
|
34
|
+
condition: str
|
|
35
|
+
max_results: int
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Product(TypedDict):
|
|
39
|
+
"""The page as read."""
|
|
40
|
+
title: Optional[str]
|
|
41
|
+
image: Optional[str]
|
|
42
|
+
price: Optional[float]
|
|
43
|
+
currency: Optional[str]
|
|
44
|
+
brand: Optional[str]
|
|
45
|
+
url: str
|
|
46
|
+
market: str
|
|
47
|
+
in_stock: Optional[bool]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Card(TypedDict, total=False):
|
|
51
|
+
"""One listing elsewhere. `url` None means a `resolve_id` to pass to resolve()."""
|
|
52
|
+
title: str
|
|
53
|
+
price: float
|
|
54
|
+
currency: str
|
|
55
|
+
url: Optional[str]
|
|
56
|
+
resolve_id: Optional[str]
|
|
57
|
+
image: str
|
|
58
|
+
retailer: str
|
|
59
|
+
rating: Optional[float]
|
|
60
|
+
ratings_count: Optional[int]
|
|
61
|
+
over_page_price: Optional[bool] # same_product cards only
|
|
62
|
+
unit_size: Optional[str]
|
|
63
|
+
pack_count: Optional[int]
|
|
64
|
+
normalized_price: Optional[float]
|
|
65
|
+
coupon: Optional[str]
|
|
66
|
+
promo_code: Optional[str]
|
|
67
|
+
price_before_discount: Optional[float]
|
|
68
|
+
discount_type: Optional[str]
|
|
69
|
+
discount_value: Optional[float]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class SearchAnswer(TypedDict):
|
|
73
|
+
request_id: str
|
|
74
|
+
search: SearchEcho
|
|
75
|
+
product: Product
|
|
76
|
+
product_name: Optional[str]
|
|
77
|
+
same_product: List[Card]
|
|
78
|
+
similar_products: List[Card]
|
|
79
|
+
page_is_cheapest: bool
|
|
80
|
+
credits_used: int
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class ReadAnswer(TypedDict):
|
|
84
|
+
request_id: str
|
|
85
|
+
is_product_page: bool
|
|
86
|
+
url: str
|
|
87
|
+
market: str
|
|
88
|
+
title: Optional[str]
|
|
89
|
+
image: Optional[str]
|
|
90
|
+
price: Optional[float]
|
|
91
|
+
currency: Optional[str]
|
|
92
|
+
brand: Optional[str]
|
|
93
|
+
in_stock: Optional[bool]
|
|
94
|
+
reason: Optional[str]
|
|
95
|
+
credits_used: int
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class ResolveAnswer(TypedDict):
|
|
99
|
+
request_id: str
|
|
100
|
+
resolved: bool
|
|
101
|
+
url: Optional[str]
|
|
102
|
+
retailer: Optional[str]
|
|
103
|
+
credits_used: int
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class FindcheapError(Exception):
|
|
107
|
+
"""Anything that stopped a call: the API's answer (FindcheapApiError) or the network (FindcheapConnectionError)."""
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class FindcheapApiError(FindcheapError):
|
|
111
|
+
"""The API answered an error: its envelope's type, message, credits_used and request_id, plus the HTTP status.
|
|
112
|
+
|
|
113
|
+
`type` is one of the reference's: invalid_request, invalid_url, unknown_market, unauthorized,
|
|
114
|
+
credits_exhausted, account_suspended, not_searchable, refused, rate_limited, unreachable,
|
|
115
|
+
timeout, search_failed, account_service_unavailable — or "http_error" when the body was not
|
|
116
|
+
the API's envelope (a proxy's page). `retry_after` is the 429's header, in seconds, else None.
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
def __init__(self, status: int, type_: str, message: str, credits_used: int = 0,
|
|
120
|
+
request_id: Optional[str] = None, retry_after: Optional[int] = None):
|
|
121
|
+
super().__init__(f"{status} {type_}: {message}")
|
|
122
|
+
self.status, self.type, self.message = status, type_, message
|
|
123
|
+
self.credits_used, self.request_id, self.retry_after = credits_used, request_id, retry_after
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class FindcheapConnectionError(FindcheapError):
|
|
127
|
+
"""The call never got an answer: no connection, a DNS failure, or the client's own timeout."""
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class Findcheap:
|
|
131
|
+
"""The client. `api_key` defaults to the FINDCHEAP_API_KEY environment variable; `timeout`, when
|
|
132
|
+
given, replaces the per-call defaults (100 s search, 40 s extract, 20 s resolve)."""
|
|
133
|
+
|
|
134
|
+
def __init__(self, api_key: Optional[str] = None, *, base_url: str = DEFAULT_BASE_URL,
|
|
135
|
+
timeout: Optional[float] = None, user_agent: Optional[str] = None):
|
|
136
|
+
key = api_key or os.environ.get("FINDCHEAP_API_KEY")
|
|
137
|
+
if not key:
|
|
138
|
+
raise ValueError("Findcheap needs an API key: pass api_key=... or set FINDCHEAP_API_KEY "
|
|
139
|
+
"(create one at https://findcheap.ai/signin?next=/dashboard/keys).")
|
|
140
|
+
self._key = key
|
|
141
|
+
self._base = base_url.rstrip("/")
|
|
142
|
+
self._timeout = timeout
|
|
143
|
+
self._user_agent = user_agent or f"findcheap-python/{__version__}"
|
|
144
|
+
|
|
145
|
+
# ── The three calls ──────────────────────────────────────────────
|
|
146
|
+
|
|
147
|
+
def search(self, url: str, *, market: Optional[str] = None, marketplaces: Optional[List[str]] = None,
|
|
148
|
+
condition: Condition = "new", max_results: Optional[int] = None) -> SearchAnswer:
|
|
149
|
+
"""Where the product on the page is sold for less (10 credits; up to 90 s). Only the options
|
|
150
|
+
given travel in the body, so the API's defaults apply to the rest."""
|
|
151
|
+
body: Dict[str, Any] = {"url": url}
|
|
152
|
+
if market is not None:
|
|
153
|
+
body["market"] = market
|
|
154
|
+
if marketplaces is not None:
|
|
155
|
+
body["marketplaces"] = list(marketplaces)
|
|
156
|
+
if condition != "new":
|
|
157
|
+
body["condition"] = condition
|
|
158
|
+
if max_results is not None:
|
|
159
|
+
body["max_results"] = max_results
|
|
160
|
+
return self._post("/v1/search", body, SEARCH_TIMEOUT_S) # type: ignore[return-value]
|
|
161
|
+
|
|
162
|
+
def extract(self, url: str, *, market: Optional[str] = None) -> ReadAnswer:
|
|
163
|
+
"""What the page sells, without a search (1 credit; up to 30 s)."""
|
|
164
|
+
body: Dict[str, Any] = {"url": url}
|
|
165
|
+
if market is not None:
|
|
166
|
+
body["market"] = market
|
|
167
|
+
return self._post("/v1/extract", body, EXTRACT_TIMEOUT_S) # type: ignore[return-value]
|
|
168
|
+
|
|
169
|
+
def resolve(self, resolve_id: str) -> ResolveAnswer:
|
|
170
|
+
"""The merchant's link for a card that came with a resolve_id (1 credit when a link came back)."""
|
|
171
|
+
return self._post("/v1/resolve", {"id": resolve_id}, RESOLVE_TIMEOUT_S) # type: ignore[return-value]
|
|
172
|
+
|
|
173
|
+
# ── The wire ─────────────────────────────────────────────────────
|
|
174
|
+
|
|
175
|
+
def _post(self, path: str, body: Dict[str, Any], default_timeout: float) -> Dict[str, Any]:
|
|
176
|
+
data = json.dumps(body).encode("utf-8")
|
|
177
|
+
request = urllib.request.Request(
|
|
178
|
+
self._base + path, data=data, method="POST",
|
|
179
|
+
headers={"Authorization": f"Bearer {self._key}", "Content-Type": "application/json",
|
|
180
|
+
"Accept": "application/json", "User-Agent": self._user_agent})
|
|
181
|
+
timeout = self._timeout if self._timeout is not None else default_timeout
|
|
182
|
+
try:
|
|
183
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
184
|
+
return json.loads(response.read().decode("utf-8"))
|
|
185
|
+
except urllib.error.HTTPError as exc:
|
|
186
|
+
raise _api_error(exc) from None
|
|
187
|
+
except (urllib.error.URLError, socket.timeout, TimeoutError, ConnectionError) as exc:
|
|
188
|
+
raise FindcheapConnectionError(f"Findcheap could not be reached: {exc}") from exc
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _api_error(exc: urllib.error.HTTPError) -> FindcheapApiError:
|
|
192
|
+
"""The API's envelope as an exception; a body that is not the envelope (a proxy's page) is
|
|
193
|
+
"http_error" with the status's reason."""
|
|
194
|
+
raw = exc.read()
|
|
195
|
+
try:
|
|
196
|
+
error = json.loads(raw.decode("utf-8")).get("error") or {}
|
|
197
|
+
except (ValueError, UnicodeDecodeError):
|
|
198
|
+
error = {}
|
|
199
|
+
retry_after = exc.headers.get("Retry-After") if exc.headers else None
|
|
200
|
+
return FindcheapApiError(
|
|
201
|
+
exc.code, str(error.get("type") or "http_error"),
|
|
202
|
+
str(error.get("message") or exc.reason or f"HTTP {exc.code}"),
|
|
203
|
+
credits_used=int(error.get("credits_used") or 0), request_id=error.get("request_id"),
|
|
204
|
+
retry_after=int(retry_after) if retry_after and str(retry_after).isdigit() else None)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: findcheap
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Find where the product on a page is sold for less: the Findcheap API's search, extract and resolve calls.
|
|
5
|
+
Author-email: Findcheap <support@findcheap.ai>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://findcheap.ai/developers
|
|
8
|
+
Project-URL: Documentation, https://findcheap.ai/developers/docs
|
|
9
|
+
Keywords: findcheap,price comparison,shopping,agents,product search
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# findcheap
|
|
19
|
+
|
|
20
|
+
The Findcheap API in Python: where the product on a page is sold for less. Standard library only, Python 3.9+.
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install findcheap
|
|
24
|
+
export FINDCHEAP_API_KEY=fc_live_... # from https://findcheap.ai/signin?next=/dashboard/keys
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
from findcheap import Findcheap, FindcheapApiError
|
|
29
|
+
|
|
30
|
+
fc = Findcheap() # reads FINDCHEAP_API_KEY; or Findcheap(api_key="fc_live_...")
|
|
31
|
+
|
|
32
|
+
answer = fc.search("https://www.jlab.com/products/jbuds-lux-anc-headphones", max_results=3)
|
|
33
|
+
print(answer["product"]["title"], "read in", answer["search"]["market"])
|
|
34
|
+
for card in answer["same_product"]:
|
|
35
|
+
print(card["price"], card["currency"], card["retailer"], card["url"] or card["resolve_id"])
|
|
36
|
+
|
|
37
|
+
page = fc.extract("https://www.jlab.com/products/jbuds-lux-anc-headphones")
|
|
38
|
+
if page["is_product_page"]:
|
|
39
|
+
print(page["title"], page["price"], page["currency"])
|
|
40
|
+
|
|
41
|
+
link = fc.resolve(answer["similar_products"][0]["resolve_id"]) # for a card whose url is None
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Every answer opens with `request_id` and closes with `credits_used`. A failed call raises `FindcheapApiError` with `.status`, `.type`, `.message`, `.credits_used`, `.request_id` and `.retry_after` (seconds, on a 429); a call that never reached the API raises `FindcheapConnectionError`. Both subclass `FindcheapError`.
|
|
45
|
+
|
|
46
|
+
Timeouts sit above the API's own ceilings (a search answers within 90 seconds, a read within 30): 100, 40 and 20 seconds for search, extract and resolve, or one `timeout=` for all three.
|
|
47
|
+
|
|
48
|
+
The reference, with every field: https://findcheap.ai/developers/docs.md.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
findcheap/__init__.py,sha256=Pw5qph8kykjuTzYv4LT1pkz_Wo-t0wMzKj0NybxcoL0,728
|
|
2
|
+
findcheap/client.py,sha256=odmYzsMyLmB156rHWD3bQm-X6oMj5r2W8fO3cjbCGTY,8391
|
|
3
|
+
findcheap-0.1.0.dist-info/licenses/LICENSE,sha256=SJ1AcOqzWzREBMJabQkjHDbZswog3aJVySbF6nEE8l8,1066
|
|
4
|
+
findcheap-0.1.0.dist-info/METADATA,sha256=4sLt23gAgu7FCdWm_5Agu07hXSX3Gav9VSt-arnqGJQ,2214
|
|
5
|
+
findcheap-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
findcheap-0.1.0.dist-info/top_level.txt,sha256=DXaRaMOv71m4si3ojFQ3w68vhLUg5HbkQ8CdjbNyXAc,10
|
|
7
|
+
findcheap-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 llmbender
|
|
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 @@
|
|
|
1
|
+
findcheap
|