compsapi 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.
- compsapi/__init__.py +38 -0
- compsapi/_client.py +519 -0
- compsapi/_errors.py +80 -0
- compsapi/_version.py +1 -0
- compsapi/py.typed +0 -0
- compsapi/types.py +335 -0
- compsapi-0.1.0.dist-info/METADATA +207 -0
- compsapi-0.1.0.dist-info/RECORD +11 -0
- compsapi-0.1.0.dist-info/WHEEL +5 -0
- compsapi-0.1.0.dist-info/licenses/LICENSE +21 -0
- compsapi-0.1.0.dist-info/top_level.txt +1 -0
compsapi/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""eBay sold listings API client for Python: sold prices, comps and live listings from CompsAPI.
|
|
2
|
+
|
|
3
|
+
Docs: https://compsapi.com/docs
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from ._client import DEFAULT_BASE_URL, CompsAPI, RateLimitInfo, to_dataframe
|
|
7
|
+
from ._errors import (
|
|
8
|
+
APIConnectionError,
|
|
9
|
+
AuthenticationError,
|
|
10
|
+
BadRequestError,
|
|
11
|
+
CompsAPIError,
|
|
12
|
+
NotFoundError,
|
|
13
|
+
PermissionDeniedError,
|
|
14
|
+
QuotaExceededError,
|
|
15
|
+
RateLimitError,
|
|
16
|
+
ServerError,
|
|
17
|
+
)
|
|
18
|
+
from ._version import __version__
|
|
19
|
+
|
|
20
|
+
Client = CompsAPI
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"CompsAPI",
|
|
24
|
+
"Client",
|
|
25
|
+
"DEFAULT_BASE_URL",
|
|
26
|
+
"RateLimitInfo",
|
|
27
|
+
"to_dataframe",
|
|
28
|
+
"CompsAPIError",
|
|
29
|
+
"APIConnectionError",
|
|
30
|
+
"AuthenticationError",
|
|
31
|
+
"BadRequestError",
|
|
32
|
+
"NotFoundError",
|
|
33
|
+
"PermissionDeniedError",
|
|
34
|
+
"QuotaExceededError",
|
|
35
|
+
"RateLimitError",
|
|
36
|
+
"ServerError",
|
|
37
|
+
"__version__",
|
|
38
|
+
]
|
compsapi/_client.py
ADDED
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
"""CompsAPI client: eBay sold listings, comps, live listings and 12 more marketplaces from one key."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime as _dt
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Union
|
|
9
|
+
|
|
10
|
+
import requests
|
|
11
|
+
|
|
12
|
+
from ._errors import APIConnectionError, AuthenticationError, CompsAPIError, error_for_status
|
|
13
|
+
from ._version import __version__
|
|
14
|
+
from .types import (
|
|
15
|
+
ActiveFormat,
|
|
16
|
+
ActiveItem,
|
|
17
|
+
ActiveResponse,
|
|
18
|
+
ActiveSort,
|
|
19
|
+
BestOffer,
|
|
20
|
+
CertResponse,
|
|
21
|
+
Kids,
|
|
22
|
+
LookupResponse,
|
|
23
|
+
Match,
|
|
24
|
+
PopulationResponse,
|
|
25
|
+
Site,
|
|
26
|
+
SoldItem,
|
|
27
|
+
SoldResponse,
|
|
28
|
+
Source,
|
|
29
|
+
SourcesResponse,
|
|
30
|
+
UsageResponse,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
DEFAULT_BASE_URL = "https://api.compsapi.com"
|
|
34
|
+
DEFAULT_TIMEOUT = 90.0
|
|
35
|
+
ENV_KEYS = ("COMPSAPI_API_KEY", "COMPSAPI_KEY")
|
|
36
|
+
|
|
37
|
+
# How Python values become query strings. The API takes "1" for switches, "true"/"false" for a few
|
|
38
|
+
# card filters, and comma separated lists everywhere a parameter accepts several values.
|
|
39
|
+
_ONE_SWITCHES = {"cards", "stats", "ai", "native_price"}
|
|
40
|
+
_TRUE_FALSE = {"graded", "first_edition"}
|
|
41
|
+
_RESERVED = {"self", "extra", "q"}
|
|
42
|
+
|
|
43
|
+
StrList = Union[str, Sequence[str]]
|
|
44
|
+
NumList = Union[str, int, float, Sequence[Union[str, int, float]]]
|
|
45
|
+
DateLike = Union[str, _dt.date, _dt.datetime]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _encode(name: str, value: Any) -> Optional[str]:
|
|
49
|
+
if value is None:
|
|
50
|
+
return None
|
|
51
|
+
if isinstance(value, bool):
|
|
52
|
+
if name in _TRUE_FALSE:
|
|
53
|
+
return "true" if value else "false"
|
|
54
|
+
if name == "kids":
|
|
55
|
+
return "1" if value else "0"
|
|
56
|
+
if name in _ONE_SWITCHES or name == "best_offer":
|
|
57
|
+
return "1" if value else None
|
|
58
|
+
return "1" if value else "0"
|
|
59
|
+
if isinstance(value, _dt.datetime):
|
|
60
|
+
return value.date().isoformat()
|
|
61
|
+
if isinstance(value, _dt.date):
|
|
62
|
+
return value.isoformat()
|
|
63
|
+
if isinstance(value, (list, tuple, set, frozenset)):
|
|
64
|
+
parts = [str(v) for v in value if v is not None and str(v) != ""]
|
|
65
|
+
return ",".join(parts) if parts else None
|
|
66
|
+
return str(value)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _params(values: Mapping[str, Any], extra: Optional[Mapping[str, Any]] = None) -> Dict[str, str]:
|
|
70
|
+
out: Dict[str, str] = {}
|
|
71
|
+
q = values.get("q")
|
|
72
|
+
if q is not None:
|
|
73
|
+
out["q"] = str(q)
|
|
74
|
+
for name, value in values.items():
|
|
75
|
+
if name in _RESERVED:
|
|
76
|
+
continue
|
|
77
|
+
enc = _encode(name, value)
|
|
78
|
+
if enc is not None:
|
|
79
|
+
out[name] = enc
|
|
80
|
+
for name, value in (extra or {}).items():
|
|
81
|
+
enc = _encode(name, value)
|
|
82
|
+
if enc is not None:
|
|
83
|
+
out[name] = enc
|
|
84
|
+
return out
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _retry_after(resp: requests.Response) -> Optional[float]:
|
|
88
|
+
raw = resp.headers.get("Retry-After")
|
|
89
|
+
if not raw:
|
|
90
|
+
return None
|
|
91
|
+
try:
|
|
92
|
+
return max(0.0, float(raw))
|
|
93
|
+
except ValueError:
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class RateLimitInfo(dict):
|
|
98
|
+
"""The X-RateLimit-* and X-Quota-* headers of the last response (console keys send them)."""
|
|
99
|
+
|
|
100
|
+
@property
|
|
101
|
+
def limit(self) -> Optional[int]:
|
|
102
|
+
return self.get("limit")
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def remaining(self) -> Optional[int]:
|
|
106
|
+
return self.get("remaining")
|
|
107
|
+
|
|
108
|
+
@property
|
|
109
|
+
def quota_monthly(self) -> Optional[int]:
|
|
110
|
+
return self.get("quota_monthly")
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def quota_used(self) -> Optional[int]:
|
|
114
|
+
return self.get("quota_used")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class CompsAPI:
|
|
118
|
+
"""Client for https://api.compsapi.com.
|
|
119
|
+
|
|
120
|
+
>>> from compsapi import CompsAPI
|
|
121
|
+
>>> client = CompsAPI() # reads COMPSAPI_API_KEY
|
|
122
|
+
>>> res = client.sold("nintendo switch oled", days=30, condition="used")
|
|
123
|
+
>>> res["stats"] # only with stats=True on /v1/sold; /v1/comps always has it
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
def __init__(
|
|
127
|
+
self,
|
|
128
|
+
api_key: Optional[str] = None,
|
|
129
|
+
*,
|
|
130
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
131
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
132
|
+
max_retries: int = 2,
|
|
133
|
+
session: Optional[requests.Session] = None,
|
|
134
|
+
user_agent: Optional[str] = None,
|
|
135
|
+
) -> None:
|
|
136
|
+
if api_key is None:
|
|
137
|
+
for env in ENV_KEYS:
|
|
138
|
+
if os.environ.get(env):
|
|
139
|
+
api_key = os.environ[env].strip()
|
|
140
|
+
break
|
|
141
|
+
self.api_key = api_key
|
|
142
|
+
self.base_url = base_url.rstrip("/")
|
|
143
|
+
self.timeout = timeout
|
|
144
|
+
self.max_retries = max(0, int(max_retries))
|
|
145
|
+
self.session = session or requests.Session()
|
|
146
|
+
ua = f"compsapi-python/{__version__} (+https://compsapi.com/docs) requests/{requests.__version__}"
|
|
147
|
+
self.user_agent = f"{user_agent} {ua}" if user_agent else ua
|
|
148
|
+
self.last_rate_limit: RateLimitInfo = RateLimitInfo()
|
|
149
|
+
|
|
150
|
+
# ------------------------------------------------------------------ transport
|
|
151
|
+
|
|
152
|
+
def _request(self, path: str, params: Optional[Dict[str, str]] = None, *, auth: bool = True) -> Dict[str, Any]:
|
|
153
|
+
headers = {"User-Agent": self.user_agent, "Accept": "application/json"}
|
|
154
|
+
if auth:
|
|
155
|
+
if not self.api_key:
|
|
156
|
+
raise AuthenticationError(
|
|
157
|
+
"No API key. Pass CompsAPI(api_key=...) or set COMPSAPI_API_KEY. "
|
|
158
|
+
"Free keys: https://compsapi.com"
|
|
159
|
+
)
|
|
160
|
+
headers["X-API-Key"] = self.api_key
|
|
161
|
+
url = self.base_url + path
|
|
162
|
+
attempt = 0
|
|
163
|
+
while True:
|
|
164
|
+
try:
|
|
165
|
+
resp = self.session.get(url, params=params or None, headers=headers, timeout=self.timeout)
|
|
166
|
+
except requests.RequestException as exc:
|
|
167
|
+
if attempt < self.max_retries:
|
|
168
|
+
attempt += 1
|
|
169
|
+
time.sleep(min(2.0 ** attempt, 8.0))
|
|
170
|
+
continue
|
|
171
|
+
raise APIConnectionError(f"{type(exc).__name__}: {exc}") from exc
|
|
172
|
+
|
|
173
|
+
self._read_rate_headers(resp)
|
|
174
|
+
try:
|
|
175
|
+
body = resp.json()
|
|
176
|
+
except ValueError:
|
|
177
|
+
body = {"ok": False, "error": (resp.text or "")[:300] or f"HTTP {resp.status_code}"}
|
|
178
|
+
if not isinstance(body, dict):
|
|
179
|
+
body = {"ok": True, "data": body}
|
|
180
|
+
|
|
181
|
+
if resp.status_code < 400:
|
|
182
|
+
if body.get("ok") is False:
|
|
183
|
+
raise CompsAPIError(str(body.get("error") or "request failed"), resp.status_code, body)
|
|
184
|
+
return body
|
|
185
|
+
|
|
186
|
+
err = error_for_status(resp.status_code, body, _retry_after(resp))
|
|
187
|
+
retryable = resp.status_code in (500, 502, 503, 504) or (
|
|
188
|
+
resp.status_code == 429 and "quota" not in err.message.lower()
|
|
189
|
+
)
|
|
190
|
+
if retryable and attempt < self.max_retries:
|
|
191
|
+
attempt += 1
|
|
192
|
+
wait = err.retry_after if err.retry_after is not None else min(2.0 ** attempt, 8.0)
|
|
193
|
+
time.sleep(min(wait, 60.0))
|
|
194
|
+
continue
|
|
195
|
+
raise err
|
|
196
|
+
|
|
197
|
+
def _read_rate_headers(self, resp: requests.Response) -> None:
|
|
198
|
+
info = RateLimitInfo()
|
|
199
|
+
for header, key in (
|
|
200
|
+
("X-RateLimit-Limit", "limit"),
|
|
201
|
+
("X-RateLimit-Remaining", "remaining"),
|
|
202
|
+
("X-Quota-Monthly", "quota_monthly"),
|
|
203
|
+
("X-Quota-Used", "quota_used"),
|
|
204
|
+
):
|
|
205
|
+
val = resp.headers.get(header)
|
|
206
|
+
if val is not None:
|
|
207
|
+
try:
|
|
208
|
+
info[key] = int(val)
|
|
209
|
+
except ValueError:
|
|
210
|
+
info[key] = val
|
|
211
|
+
self.last_rate_limit = info
|
|
212
|
+
|
|
213
|
+
# ------------------------------------------------------------------ sold
|
|
214
|
+
|
|
215
|
+
def sold(
|
|
216
|
+
self,
|
|
217
|
+
q: Optional[str] = None,
|
|
218
|
+
*,
|
|
219
|
+
source: Optional[Source] = None,
|
|
220
|
+
days: Optional[int] = None,
|
|
221
|
+
start: Optional[DateLike] = None,
|
|
222
|
+
end: Optional[DateLike] = None,
|
|
223
|
+
size: Optional[int] = None,
|
|
224
|
+
page: Optional[int] = None,
|
|
225
|
+
condition: Optional[StrList] = None,
|
|
226
|
+
best_offer: Union[BestOffer, bool, None] = None,
|
|
227
|
+
cards: Optional[bool] = None,
|
|
228
|
+
grader: Optional[StrList] = None,
|
|
229
|
+
grade: Optional[NumList] = None,
|
|
230
|
+
graded: Optional[bool] = None,
|
|
231
|
+
lang: Optional[StrList] = None,
|
|
232
|
+
first_edition: Optional[bool] = None,
|
|
233
|
+
card_condition: Optional[StrList] = None,
|
|
234
|
+
exclude: Optional[StrList] = None,
|
|
235
|
+
ai: Optional[bool] = None,
|
|
236
|
+
require: Optional[StrList] = None,
|
|
237
|
+
match: Optional[Match] = None,
|
|
238
|
+
print_run: Union[int, str, None] = None,
|
|
239
|
+
stats: Optional[bool] = None,
|
|
240
|
+
site: Optional[Site] = None,
|
|
241
|
+
category: Optional[NumList] = None,
|
|
242
|
+
min_price: Optional[float] = None,
|
|
243
|
+
max_price: Optional[float] = None,
|
|
244
|
+
native_price: Optional[bool] = None,
|
|
245
|
+
market: Optional[StrList] = None,
|
|
246
|
+
include: Optional[str] = None,
|
|
247
|
+
product_id: Optional[StrList] = None,
|
|
248
|
+
style_id: Optional[str] = None,
|
|
249
|
+
item_size: Optional[StrList] = None,
|
|
250
|
+
kids: Union[Kids, bool, None] = None,
|
|
251
|
+
**extra: Any,
|
|
252
|
+
) -> SoldResponse:
|
|
253
|
+
"""GET /v1/sold: sold listings for a search, newest sale first.
|
|
254
|
+
|
|
255
|
+
``q`` is required unless ``product_id`` is given (StockX and GOAT). Lists are sent comma separated
|
|
256
|
+
(``condition=["new", "open_box"]``, ``grade=[9, 10]``). Booleans become the API's own switches
|
|
257
|
+
(``stats=True`` sends ``stats=1``, ``graded=False`` sends ``graded=false``). Any parameter the API
|
|
258
|
+
adds later can be passed as a keyword and is sent as is.
|
|
259
|
+
"""
|
|
260
|
+
if not q and not product_id:
|
|
261
|
+
raise ValueError("q is required (or product_id for source=stockx / goat)")
|
|
262
|
+
return self._request("/v1/sold", _params(locals(), extra)) # type: ignore[return-value]
|
|
263
|
+
|
|
264
|
+
def comps(
|
|
265
|
+
self,
|
|
266
|
+
q: Optional[str] = None,
|
|
267
|
+
*,
|
|
268
|
+
source: Optional[Source] = None,
|
|
269
|
+
days: Optional[int] = None,
|
|
270
|
+
start: Optional[DateLike] = None,
|
|
271
|
+
end: Optional[DateLike] = None,
|
|
272
|
+
size: Optional[int] = None,
|
|
273
|
+
condition: Optional[StrList] = None,
|
|
274
|
+
best_offer: Union[BestOffer, bool, None] = None,
|
|
275
|
+
grader: Optional[StrList] = None,
|
|
276
|
+
grade: Optional[NumList] = None,
|
|
277
|
+
graded: Optional[bool] = None,
|
|
278
|
+
lang: Optional[StrList] = None,
|
|
279
|
+
first_edition: Optional[bool] = None,
|
|
280
|
+
card_condition: Optional[StrList] = None,
|
|
281
|
+
exclude: Optional[StrList] = None,
|
|
282
|
+
ai: Optional[bool] = None,
|
|
283
|
+
require: Optional[StrList] = None,
|
|
284
|
+
match: Optional[Match] = None,
|
|
285
|
+
print_run: Union[int, str, None] = None,
|
|
286
|
+
min_price: Optional[float] = None,
|
|
287
|
+
max_price: Optional[float] = None,
|
|
288
|
+
native_price: Optional[bool] = None,
|
|
289
|
+
market: Optional[StrList] = None,
|
|
290
|
+
product_id: Optional[StrList] = None,
|
|
291
|
+
style_id: Optional[str] = None,
|
|
292
|
+
item_size: Optional[StrList] = None,
|
|
293
|
+
kids: Union[Kids, bool, None] = None,
|
|
294
|
+
**extra: Any,
|
|
295
|
+
) -> SoldResponse:
|
|
296
|
+
"""GET /v1/comps: price stats over every matching sale plus the 10 newest sales.
|
|
297
|
+
|
|
298
|
+
Junk listings are dropped by default (``exclude="junk"``); pass ``exclude="none"`` to keep them.
|
|
299
|
+
Not pageable: use :meth:`sold` or :meth:`iter_sold` when you need every sale.
|
|
300
|
+
"""
|
|
301
|
+
if not q and not product_id:
|
|
302
|
+
raise ValueError("q is required (or product_id for source=stockx / goat)")
|
|
303
|
+
return self._request("/v1/comps", _params(locals(), extra)) # type: ignore[return-value]
|
|
304
|
+
|
|
305
|
+
def iter_sold_pages(
|
|
306
|
+
self,
|
|
307
|
+
q: Optional[str] = None,
|
|
308
|
+
*,
|
|
309
|
+
max_pages: Optional[int] = None,
|
|
310
|
+
start_page: int = 1,
|
|
311
|
+
**params: Any,
|
|
312
|
+
) -> Iterator[SoldResponse]:
|
|
313
|
+
"""Yield one /v1/sold answer per page, oldest last, until ``next_page`` is false.
|
|
314
|
+
|
|
315
|
+
Pages are walked in order, as the API expects. With ``match="strict"`` one answer can cover several
|
|
316
|
+
pages; the walk continues from ``deepen.next_page`` so nothing is read twice. Your plan caps the page
|
|
317
|
+
number (free 10, Starter 25, Growth and up 200); for deep history, narrow with ``start``/``end`` windows.
|
|
318
|
+
"""
|
|
319
|
+
page = max(1, int(start_page))
|
|
320
|
+
read = 0
|
|
321
|
+
while True:
|
|
322
|
+
res = self.sold(q, page=page, **params)
|
|
323
|
+
yield res
|
|
324
|
+
read += 1
|
|
325
|
+
if not res.get("next_page") or (max_pages is not None and read >= max_pages):
|
|
326
|
+
return
|
|
327
|
+
deepen = res.get("deepen") or {}
|
|
328
|
+
nxt = deepen.get("next_page") if isinstance(deepen, dict) else None
|
|
329
|
+
if isinstance(nxt, int) and nxt > page:
|
|
330
|
+
page = nxt
|
|
331
|
+
else:
|
|
332
|
+
page += max(1, int(res.get("upstream_pages_read") or 1))
|
|
333
|
+
|
|
334
|
+
def iter_sold(
|
|
335
|
+
self,
|
|
336
|
+
q: Optional[str] = None,
|
|
337
|
+
*,
|
|
338
|
+
max_pages: Optional[int] = None,
|
|
339
|
+
max_items: Optional[int] = None,
|
|
340
|
+
dedupe: bool = True,
|
|
341
|
+
**params: Any,
|
|
342
|
+
) -> Iterator[SoldItem]:
|
|
343
|
+
"""Yield every sold item across pages, newest first. See :meth:`iter_sold_pages`."""
|
|
344
|
+
seen = set()
|
|
345
|
+
n = 0
|
|
346
|
+
for res in self.iter_sold_pages(q, max_pages=max_pages, **params):
|
|
347
|
+
for item in res.get("items") or []:
|
|
348
|
+
if dedupe:
|
|
349
|
+
key = (item.get("source"), item.get("item_id"), item.get("last_sold"))
|
|
350
|
+
if key in seen:
|
|
351
|
+
continue
|
|
352
|
+
seen.add(key)
|
|
353
|
+
yield item
|
|
354
|
+
n += 1
|
|
355
|
+
if max_items is not None and n >= max_items:
|
|
356
|
+
return
|
|
357
|
+
|
|
358
|
+
def sold_all(
|
|
359
|
+
self,
|
|
360
|
+
q: Optional[str] = None,
|
|
361
|
+
*,
|
|
362
|
+
max_pages: Optional[int] = None,
|
|
363
|
+
max_items: Optional[int] = None,
|
|
364
|
+
**params: Any,
|
|
365
|
+
) -> List[SoldItem]:
|
|
366
|
+
"""Every sold item across pages as a list. Set ``max_pages`` to bound the number of requests."""
|
|
367
|
+
return list(self.iter_sold(q, max_pages=max_pages, max_items=max_items, **params))
|
|
368
|
+
|
|
369
|
+
def sold_df(
|
|
370
|
+
self,
|
|
371
|
+
q: Optional[str] = None,
|
|
372
|
+
*,
|
|
373
|
+
max_pages: Optional[int] = 1,
|
|
374
|
+
max_items: Optional[int] = None,
|
|
375
|
+
**params: Any,
|
|
376
|
+
) -> "Any":
|
|
377
|
+
"""Sold items as a pandas DataFrame (one row per sale, nested fields flattened). Needs pandas."""
|
|
378
|
+
return to_dataframe(self.sold_all(q, max_pages=max_pages, max_items=max_items, **params))
|
|
379
|
+
|
|
380
|
+
# ------------------------------------------------------------------ live listings
|
|
381
|
+
|
|
382
|
+
def active(
|
|
383
|
+
self,
|
|
384
|
+
q: Optional[str] = None,
|
|
385
|
+
*,
|
|
386
|
+
source: Optional[Source] = None,
|
|
387
|
+
sort: Optional[ActiveSort] = None,
|
|
388
|
+
per_page: Optional[int] = None,
|
|
389
|
+
page: Optional[int] = None,
|
|
390
|
+
min_price: Optional[float] = None,
|
|
391
|
+
max_price: Optional[float] = None,
|
|
392
|
+
condition: Optional[StrList] = None,
|
|
393
|
+
format: Optional[ActiveFormat] = None,
|
|
394
|
+
category: Optional[NumList] = None,
|
|
395
|
+
require: Optional[StrList] = None,
|
|
396
|
+
match: Optional[Match] = None,
|
|
397
|
+
product_id: Optional[StrList] = None,
|
|
398
|
+
style_id: Optional[str] = None,
|
|
399
|
+
item_size: Optional[StrList] = None,
|
|
400
|
+
kids: Union[Kids, bool, None] = None,
|
|
401
|
+
cursor: Optional[str] = None,
|
|
402
|
+
**extra: Any,
|
|
403
|
+
) -> ActiveResponse:
|
|
404
|
+
"""GET /v1/active: listings for sale right now on eBay US or a marketplace."""
|
|
405
|
+
if not q and not product_id:
|
|
406
|
+
raise ValueError("q is required (or product_id for source=stockx / goat)")
|
|
407
|
+
return self._request("/v1/active", _params(locals(), extra)) # type: ignore[return-value]
|
|
408
|
+
|
|
409
|
+
def iter_active(
|
|
410
|
+
self,
|
|
411
|
+
q: Optional[str] = None,
|
|
412
|
+
*,
|
|
413
|
+
max_pages: Optional[int] = None,
|
|
414
|
+
max_items: Optional[int] = None,
|
|
415
|
+
**params: Any,
|
|
416
|
+
) -> Iterator[ActiveItem]:
|
|
417
|
+
"""Yield live listings across pages. Follows ``next_cursor`` where a marketplace gives one."""
|
|
418
|
+
page = int(params.pop("page", None) or 1)
|
|
419
|
+
cursor = params.pop("cursor", None)
|
|
420
|
+
read = n = 0
|
|
421
|
+
while True:
|
|
422
|
+
if cursor:
|
|
423
|
+
res = self.active(q, cursor=cursor, **params)
|
|
424
|
+
else:
|
|
425
|
+
res = self.active(q, page=page, **params)
|
|
426
|
+
read += 1
|
|
427
|
+
for item in res.get("items") or []:
|
|
428
|
+
yield item
|
|
429
|
+
n += 1
|
|
430
|
+
if max_items is not None and n >= max_items:
|
|
431
|
+
return
|
|
432
|
+
if max_pages is not None and read >= max_pages:
|
|
433
|
+
return
|
|
434
|
+
nxt = res.get("next_cursor")
|
|
435
|
+
if nxt:
|
|
436
|
+
cursor = nxt
|
|
437
|
+
elif res.get("next_page"):
|
|
438
|
+
cursor = None
|
|
439
|
+
page += 1
|
|
440
|
+
else:
|
|
441
|
+
return
|
|
442
|
+
|
|
443
|
+
# ------------------------------------------------------------------ account and service
|
|
444
|
+
|
|
445
|
+
def usage(self) -> UsageResponse:
|
|
446
|
+
"""GET /v1/usage: today's usage, caps and plan. Free: does not count against your quota."""
|
|
447
|
+
return self._request("/v1/usage") # type: ignore[return-value]
|
|
448
|
+
|
|
449
|
+
def health(self) -> Dict[str, Any]:
|
|
450
|
+
"""GET /v1/health: service status. Needs no key."""
|
|
451
|
+
return self._request("/v1/health", auth=False)
|
|
452
|
+
|
|
453
|
+
def sources(self) -> SourcesResponse:
|
|
454
|
+
"""GET /v1/sources: the valid ``source`` values."""
|
|
455
|
+
return self._request("/v1/sources", auth=False) # type: ignore[return-value]
|
|
456
|
+
|
|
457
|
+
# ------------------------------------------------------------------ PSA
|
|
458
|
+
|
|
459
|
+
def lookup(self, q: str, *, limit: Optional[int] = None) -> LookupResponse:
|
|
460
|
+
"""GET /v1/lookup: card keyword to PSA spec ids, best match first."""
|
|
461
|
+
return self._request("/v1/lookup", _params({"q": q, "limit": limit})) # type: ignore[return-value]
|
|
462
|
+
|
|
463
|
+
def population(
|
|
464
|
+
self,
|
|
465
|
+
*,
|
|
466
|
+
spec: Union[int, str, None] = None,
|
|
467
|
+
q: Optional[str] = None,
|
|
468
|
+
set: Union[int, str, None] = None, # noqa: A002 (the API parameter is called set)
|
|
469
|
+
page: Optional[int] = None,
|
|
470
|
+
page_size: Optional[int] = None,
|
|
471
|
+
) -> PopulationResponse:
|
|
472
|
+
"""GET /v1/population: PSA census for a spec id, the top match of a keyword, or a whole set."""
|
|
473
|
+
if spec is None and not q and set is None:
|
|
474
|
+
raise ValueError("pass one of spec=, q= or set=")
|
|
475
|
+
values = {"q": q, "spec": spec, "set": set, "page": page, "page_size": page_size}
|
|
476
|
+
return self._request("/v1/population", _params(values)) # type: ignore[return-value]
|
|
477
|
+
|
|
478
|
+
def cert(self, cert: Union[int, str], *, recent: Optional[int] = None) -> CertResponse:
|
|
479
|
+
"""GET /v1/cert: a PSA cert number to the card, grade, population and recent sales."""
|
|
480
|
+
return self._request("/v1/cert", _params({"cert": cert, "recent": recent})) # type: ignore[return-value]
|
|
481
|
+
|
|
482
|
+
# ------------------------------------------------------------------ misc
|
|
483
|
+
|
|
484
|
+
def close(self) -> None:
|
|
485
|
+
self.session.close()
|
|
486
|
+
|
|
487
|
+
def __enter__(self) -> "CompsAPI":
|
|
488
|
+
return self
|
|
489
|
+
|
|
490
|
+
def __exit__(self, *exc: Any) -> None:
|
|
491
|
+
self.close()
|
|
492
|
+
|
|
493
|
+
def __repr__(self) -> str:
|
|
494
|
+
masked = (self.api_key[:6] + "...") if self.api_key else None
|
|
495
|
+
return f"CompsAPI(base_url={self.base_url!r}, api_key={masked!r})"
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def to_dataframe(data: Union[Mapping[str, Any], Iterable[Mapping[str, Any]]], *, sep: str = "_") -> "Any":
|
|
499
|
+
"""Turn a response (or a list of items) into a pandas DataFrame.
|
|
500
|
+
|
|
501
|
+
Nested objects are flattened (``card.grade`` becomes ``card_grade``), ``last_sold`` and ``ends_at``
|
|
502
|
+
become UTC datetimes. Install pandas with ``pip install "compsapi[pandas]"``.
|
|
503
|
+
"""
|
|
504
|
+
try:
|
|
505
|
+
import pandas as pd
|
|
506
|
+
except ImportError as exc: # pragma: no cover
|
|
507
|
+
raise ImportError('to_dataframe needs pandas: pip install "compsapi[pandas]"') from exc
|
|
508
|
+
|
|
509
|
+
if isinstance(data, Mapping):
|
|
510
|
+
rows = list(data.get("items") or [])
|
|
511
|
+
else:
|
|
512
|
+
rows = list(data)
|
|
513
|
+
if not rows:
|
|
514
|
+
return pd.DataFrame()
|
|
515
|
+
df = pd.json_normalize(rows, sep=sep)
|
|
516
|
+
for col in ("last_sold", "ends_at", "ended_at"):
|
|
517
|
+
if col in df.columns:
|
|
518
|
+
df[col] = pd.to_datetime(df[col], utc=True, errors="coerce")
|
|
519
|
+
return df
|
compsapi/_errors.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Exceptions raised by the CompsAPI client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class CompsAPIError(Exception):
|
|
9
|
+
"""Base error. Every API error body is JSON with ``ok: false`` and an ``error`` message."""
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
message: str,
|
|
14
|
+
status: Optional[int] = None,
|
|
15
|
+
body: Optional[Dict[str, Any]] = None,
|
|
16
|
+
retry_after: Optional[float] = None,
|
|
17
|
+
) -> None:
|
|
18
|
+
super().__init__(message)
|
|
19
|
+
self.message = message
|
|
20
|
+
self.status = status
|
|
21
|
+
self.body = body or {}
|
|
22
|
+
self.retry_after = retry_after
|
|
23
|
+
|
|
24
|
+
def __str__(self) -> str:
|
|
25
|
+
if self.status:
|
|
26
|
+
return f"HTTP {self.status}: {self.message}"
|
|
27
|
+
return self.message
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class BadRequestError(CompsAPIError):
|
|
31
|
+
"""400: a missing or invalid parameter, a page past your plan's limit, or a search too broad."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class AuthenticationError(CompsAPIError):
|
|
35
|
+
"""401: missing or invalid API key."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class PermissionDeniedError(CompsAPIError):
|
|
39
|
+
"""403: key expired, or the request was refused (for example no User-Agent)."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class NotFoundError(CompsAPIError):
|
|
43
|
+
"""404: unknown endpoint or path."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class RateLimitError(CompsAPIError):
|
|
47
|
+
"""429: too many requests at once. ``retry_after`` holds the seconds to wait when the API sent it."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class QuotaExceededError(RateLimitError):
|
|
51
|
+
"""429 with ``error: quota_reached``: the monthly quota is used up until the UTC month resets."""
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ServerError(CompsAPIError):
|
|
55
|
+
"""5xx: a temporary problem on the API side. Safe to retry after a second or two."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class APIConnectionError(CompsAPIError):
|
|
59
|
+
"""The request never got an HTTP answer (DNS, TLS, timeout, connection reset)."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def error_for_status(
|
|
63
|
+
status: int, body: Dict[str, Any], retry_after: Optional[float]
|
|
64
|
+
) -> CompsAPIError:
|
|
65
|
+
message = str(body.get("error") or body.get("message") or f"HTTP {status}")
|
|
66
|
+
if status == 400:
|
|
67
|
+
return BadRequestError(message, status, body)
|
|
68
|
+
if status == 401:
|
|
69
|
+
return AuthenticationError(message, status, body)
|
|
70
|
+
if status == 403:
|
|
71
|
+
return PermissionDeniedError(message, status, body)
|
|
72
|
+
if status == 404:
|
|
73
|
+
return NotFoundError(message, status, body)
|
|
74
|
+
if status == 429:
|
|
75
|
+
if "quota" in message.lower():
|
|
76
|
+
return QuotaExceededError(message, status, body, retry_after)
|
|
77
|
+
return RateLimitError(message, status, body, retry_after)
|
|
78
|
+
if status >= 500:
|
|
79
|
+
return ServerError(message, status, body, retry_after)
|
|
80
|
+
return CompsAPIError(message, status, body, retry_after)
|
compsapi/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
compsapi/py.typed
ADDED
|
File without changes
|
compsapi/types.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
"""Typed shapes of the CompsAPI responses (OpenAPI 1.11.0, https://api.compsapi.com/openapi.json).
|
|
2
|
+
|
|
3
|
+
Every TypedDict is ``total=False``: fields that only appear with an option (``best_offer``, ``native_price``,
|
|
4
|
+
``ai``, card options, marketplace sources) are simply absent otherwise. Responses are plain dicts, so new
|
|
5
|
+
fields the API adds later come through untouched.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Dict, List, Literal, Optional, TypedDict
|
|
11
|
+
|
|
12
|
+
Source = Literal[
|
|
13
|
+
"ebay",
|
|
14
|
+
"reverb",
|
|
15
|
+
"stockx",
|
|
16
|
+
"goat",
|
|
17
|
+
"grailed",
|
|
18
|
+
"poshmark",
|
|
19
|
+
"mercari",
|
|
20
|
+
"vinted",
|
|
21
|
+
"goldin",
|
|
22
|
+
"fanatics",
|
|
23
|
+
"myslabs",
|
|
24
|
+
"pristine",
|
|
25
|
+
"tcgplayer",
|
|
26
|
+
"psa",
|
|
27
|
+
"all",
|
|
28
|
+
]
|
|
29
|
+
Site = Literal["US", "UK", "DE", "FR", "IT", "ES", "CA", "AU"]
|
|
30
|
+
EbayCondition = Literal["new", "open_box", "refurbished", "used", "parts"]
|
|
31
|
+
BestOffer = Literal["1", "only", "verify"]
|
|
32
|
+
Match = Literal["strict", "check", "off"]
|
|
33
|
+
ActiveSort = Literal["best_match", "newly_listed", "ending_soonest", "price_asc", "price_desc"]
|
|
34
|
+
ActiveFormat = Literal["bin", "auction"]
|
|
35
|
+
Kids = Literal["auto", "1", "0", "only"]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Card(TypedDict, total=False):
|
|
39
|
+
graded: Optional[bool]
|
|
40
|
+
grader: Optional[str]
|
|
41
|
+
grade: Optional[str]
|
|
42
|
+
grade_label: Optional[str]
|
|
43
|
+
card_number: Optional[str]
|
|
44
|
+
year: Optional[int]
|
|
45
|
+
language: Optional[str]
|
|
46
|
+
first_edition: Optional[bool]
|
|
47
|
+
flags: List[str]
|
|
48
|
+
condition: Optional[str]
|
|
49
|
+
psa_spec_id: int
|
|
50
|
+
rarity: Optional[str]
|
|
51
|
+
set_code: Optional[str]
|
|
52
|
+
is_rookie: bool
|
|
53
|
+
is_autographed: bool
|
|
54
|
+
is_memorabilia: bool
|
|
55
|
+
serial_number: Optional[int]
|
|
56
|
+
serial_limit: Optional[int]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class Authenticity(TypedDict, total=False):
|
|
60
|
+
basis: Literal["marketplace_verified", "graded", "third_party_coa", "seller_declared"]
|
|
61
|
+
verified: bool
|
|
62
|
+
grader: Optional[str]
|
|
63
|
+
grade: Optional[str]
|
|
64
|
+
cert_number: Optional[str]
|
|
65
|
+
coa_note: str
|
|
66
|
+
cert_note: str
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Signals(TypedDict, total=False):
|
|
70
|
+
days_on_market: float
|
|
71
|
+
discount_pct: float
|
|
72
|
+
listed_date: str
|
|
73
|
+
seller: Dict[str, Any]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class AiLabel(TypedDict, total=False):
|
|
77
|
+
kind: Literal["item", "lot", "mystery", "parts", "accessory", "box_only", "replica", "digital", "other"]
|
|
78
|
+
junk: bool
|
|
79
|
+
confidence: float
|
|
80
|
+
category: str
|
|
81
|
+
model: str
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class SoldItem(TypedDict, total=False):
|
|
85
|
+
item_id: str
|
|
86
|
+
title: str
|
|
87
|
+
last_sold: str
|
|
88
|
+
price: Optional[float]
|
|
89
|
+
units_sold: int
|
|
90
|
+
total_sales: float
|
|
91
|
+
format: Literal["FIXED_PRICE", "AUCTION"]
|
|
92
|
+
bids: int
|
|
93
|
+
us_sale: bool
|
|
94
|
+
native_price: Optional[float]
|
|
95
|
+
native_currency: Optional[str]
|
|
96
|
+
native_reason: str
|
|
97
|
+
best_offer: Optional[bool]
|
|
98
|
+
best_offer_confidence: Literal["confirmed", "likely", "unlikely", "unknown"]
|
|
99
|
+
asking_price: Optional[float]
|
|
100
|
+
asking_gap_pct: Optional[float]
|
|
101
|
+
print_run: Optional[int]
|
|
102
|
+
condition: Optional[str]
|
|
103
|
+
shipping_cost: Optional[float]
|
|
104
|
+
free_shipping_pct: float
|
|
105
|
+
url: str
|
|
106
|
+
image: str
|
|
107
|
+
card: Card
|
|
108
|
+
source: str
|
|
109
|
+
authenticity: Authenticity
|
|
110
|
+
raw: Dict[str, Any]
|
|
111
|
+
flags: List[Any]
|
|
112
|
+
signals: Signals
|
|
113
|
+
market: Dict[str, Any]
|
|
114
|
+
ai: AiLabel
|
|
115
|
+
brand: Optional[str]
|
|
116
|
+
category: Optional[str]
|
|
117
|
+
size: Optional[str]
|
|
118
|
+
listing_id: Optional[str]
|
|
119
|
+
seller_country: Optional[str]
|
|
120
|
+
row_type: Literal["weekly_summary"]
|
|
121
|
+
price_is_estimate: bool
|
|
122
|
+
attributes: Dict[str, Any]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class Stats(TypedDict, total=False):
|
|
126
|
+
count: int
|
|
127
|
+
used_for_stats: int
|
|
128
|
+
median: float
|
|
129
|
+
mean: float
|
|
130
|
+
p25: float
|
|
131
|
+
p75: float
|
|
132
|
+
min: float
|
|
133
|
+
max: float
|
|
134
|
+
outliers_removed: int
|
|
135
|
+
junk_removed: int
|
|
136
|
+
newest_sale: str
|
|
137
|
+
oldest_sale: str
|
|
138
|
+
confidence: Dict[str, Any]
|
|
139
|
+
price_trend: Optional[Dict[str, Any]]
|
|
140
|
+
by_condition: Optional[Dict[str, Any]]
|
|
141
|
+
accessories_removed: int
|
|
142
|
+
days_to_sell: Optional[Dict[str, Any]]
|
|
143
|
+
sold_within_days: Optional[List[Dict[str, Any]]]
|
|
144
|
+
products: int
|
|
145
|
+
by_product: List[Dict[str, Any]]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class SoldResponse(TypedDict, total=False):
|
|
149
|
+
ok: bool
|
|
150
|
+
query: str
|
|
151
|
+
page: int
|
|
152
|
+
ms: int
|
|
153
|
+
count: int
|
|
154
|
+
no_results: bool
|
|
155
|
+
next_page: bool
|
|
156
|
+
days: int
|
|
157
|
+
size: int
|
|
158
|
+
cached: bool
|
|
159
|
+
cached_age_s: int
|
|
160
|
+
source: str
|
|
161
|
+
site: str
|
|
162
|
+
filters: Dict[str, Any]
|
|
163
|
+
count_before_filters: int
|
|
164
|
+
price_filter: Dict[str, Any]
|
|
165
|
+
title_filter: Dict[str, Any]
|
|
166
|
+
match_filter: Dict[str, Any]
|
|
167
|
+
note: str
|
|
168
|
+
stats: Stats
|
|
169
|
+
items: List[SoldItem]
|
|
170
|
+
window: Dict[str, Any]
|
|
171
|
+
meta: Optional[Dict[str, Any]]
|
|
172
|
+
ignored_params: List[str]
|
|
173
|
+
summaries_included: bool
|
|
174
|
+
upstream_pages_read: int
|
|
175
|
+
deepen: Dict[str, Any]
|
|
176
|
+
native_price_info: Dict[str, Any]
|
|
177
|
+
plan_limit: Dict[str, Any]
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class ActiveItem(TypedDict, total=False):
|
|
181
|
+
item_id: str
|
|
182
|
+
title: str
|
|
183
|
+
url: str
|
|
184
|
+
price: Optional[float]
|
|
185
|
+
price_max: Optional[float]
|
|
186
|
+
currency: str
|
|
187
|
+
shipping: Optional[float]
|
|
188
|
+
shipping_text: Optional[str]
|
|
189
|
+
format: Literal["BIN", "AUCTION"]
|
|
190
|
+
bids: Optional[int]
|
|
191
|
+
ends_at: Optional[str]
|
|
192
|
+
buy_it_now_available: bool
|
|
193
|
+
best_offer_enabled: bool
|
|
194
|
+
quantity_available: Optional[int]
|
|
195
|
+
condition: Optional[str]
|
|
196
|
+
seller: Optional[str]
|
|
197
|
+
seller_feedback: Optional[int]
|
|
198
|
+
seller_positive_pct: Optional[float]
|
|
199
|
+
location: Optional[str]
|
|
200
|
+
image: Optional[str]
|
|
201
|
+
source: str
|
|
202
|
+
authenticity: Authenticity
|
|
203
|
+
raw: Dict[str, Any]
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class ActiveResponse(TypedDict, total=False):
|
|
207
|
+
ok: bool
|
|
208
|
+
query: str
|
|
209
|
+
page: int
|
|
210
|
+
ms: int
|
|
211
|
+
sort: str
|
|
212
|
+
count: int
|
|
213
|
+
next_page: bool
|
|
214
|
+
source: str
|
|
215
|
+
total_active: int
|
|
216
|
+
total_active_is_minimum: bool
|
|
217
|
+
filtered_total: int
|
|
218
|
+
title_filter: Dict[str, Any]
|
|
219
|
+
match_filter: Dict[str, Any]
|
|
220
|
+
cached: bool
|
|
221
|
+
cached_age_s: int
|
|
222
|
+
items: List[ActiveItem]
|
|
223
|
+
live_status: Dict[str, str]
|
|
224
|
+
sources_failed: List[str]
|
|
225
|
+
per_page: int
|
|
226
|
+
next_cursor: Optional[str]
|
|
227
|
+
marketplace_total: int
|
|
228
|
+
price_points: List[Dict[str, Any]]
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class UsageResponse(TypedDict, total=False):
|
|
232
|
+
ok: bool
|
|
233
|
+
plan: str
|
|
234
|
+
monthly_used: int
|
|
235
|
+
monthly_quota: int
|
|
236
|
+
rpm_limit: int
|
|
237
|
+
day_utc: str
|
|
238
|
+
used: int
|
|
239
|
+
daily_cap: Optional[int]
|
|
240
|
+
expires: Optional[str]
|
|
241
|
+
trial_hours: Optional[int]
|
|
242
|
+
trial_started: Optional[str]
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class SourcesResponse(TypedDict, total=False):
|
|
246
|
+
ok: bool
|
|
247
|
+
default: str
|
|
248
|
+
sources: List[str]
|
|
249
|
+
all: str
|
|
250
|
+
all_merges: List[str]
|
|
251
|
+
not_in_all: Dict[str, str]
|
|
252
|
+
live_listings: List[str]
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
class LookupResult(TypedDict, total=False):
|
|
256
|
+
spec_id: int
|
|
257
|
+
subject: str
|
|
258
|
+
year: str
|
|
259
|
+
set: str
|
|
260
|
+
number: str
|
|
261
|
+
variety: Optional[str]
|
|
262
|
+
category: str
|
|
263
|
+
description: str
|
|
264
|
+
url: str
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
class LookupResponse(TypedDict, total=False):
|
|
268
|
+
ok: bool
|
|
269
|
+
query: str
|
|
270
|
+
count: int
|
|
271
|
+
source: Literal["psa"]
|
|
272
|
+
results: List[LookupResult]
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class PopulationResponse(TypedDict, total=False):
|
|
276
|
+
ok: bool
|
|
277
|
+
spec_id: str
|
|
278
|
+
source: Literal["psa"]
|
|
279
|
+
gem_rate: float
|
|
280
|
+
total_graded: int
|
|
281
|
+
grades: Dict[str, int]
|
|
282
|
+
resolved_from: Dict[str, Any]
|
|
283
|
+
no_results: bool
|
|
284
|
+
has_dual_graded: bool
|
|
285
|
+
psa_spec_url: str
|
|
286
|
+
# set=... answers (SetPopulationResponse)
|
|
287
|
+
set_id: int
|
|
288
|
+
total_items: int
|
|
289
|
+
page: int
|
|
290
|
+
page_size: int
|
|
291
|
+
pages: int
|
|
292
|
+
total_sales: Optional[float]
|
|
293
|
+
total_value: Optional[float]
|
|
294
|
+
cards: List[Dict[str, Any]]
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
class CertResponse(TypedDict, total=False):
|
|
298
|
+
ok: bool
|
|
299
|
+
cert: str
|
|
300
|
+
found: bool
|
|
301
|
+
source: Literal["psa"]
|
|
302
|
+
reason: str
|
|
303
|
+
spec_id: int
|
|
304
|
+
grade: str
|
|
305
|
+
grading_company: Optional[str]
|
|
306
|
+
card: Dict[str, Any]
|
|
307
|
+
population: Optional[Dict[str, Any]]
|
|
308
|
+
recent_sales: List[Dict[str, Any]]
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
__all__ = [
|
|
312
|
+
"Source",
|
|
313
|
+
"Site",
|
|
314
|
+
"EbayCondition",
|
|
315
|
+
"BestOffer",
|
|
316
|
+
"Match",
|
|
317
|
+
"ActiveSort",
|
|
318
|
+
"ActiveFormat",
|
|
319
|
+
"Kids",
|
|
320
|
+
"Card",
|
|
321
|
+
"Authenticity",
|
|
322
|
+
"Signals",
|
|
323
|
+
"AiLabel",
|
|
324
|
+
"SoldItem",
|
|
325
|
+
"Stats",
|
|
326
|
+
"SoldResponse",
|
|
327
|
+
"ActiveItem",
|
|
328
|
+
"ActiveResponse",
|
|
329
|
+
"UsageResponse",
|
|
330
|
+
"SourcesResponse",
|
|
331
|
+
"LookupResult",
|
|
332
|
+
"LookupResponse",
|
|
333
|
+
"PopulationResponse",
|
|
334
|
+
"CertResponse",
|
|
335
|
+
]
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: compsapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: eBay sold listings API client for Python: real sold prices, comps and live listings as JSON or pandas, with 3 years of history and 12 more marketplaces.
|
|
5
|
+
Author: CompsAPI
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://compsapi.com
|
|
8
|
+
Project-URL: Documentation, https://compsapi.com/docs
|
|
9
|
+
Project-URL: API reference (OpenAPI), https://api.compsapi.com/openapi.json
|
|
10
|
+
Project-URL: Pricing, https://compsapi.com/pricing
|
|
11
|
+
Project-URL: Source, https://github.com/getcompsapi/ebay-sold-listings-api
|
|
12
|
+
Project-URL: Issues, https://github.com/getcompsapi/ebay-sold-listings-api/issues
|
|
13
|
+
Keywords: ebay,ebay api,ebay sold listings,ebay sold listings api,ebay sold api,ebay completed listings,sold prices,price history,comps,findCompletedItems,trading cards,psa,pandas
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
20
|
+
Classifier: Topic :: Office/Business :: Financial
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: requests>=2.20
|
|
27
|
+
Provides-Extra: pandas
|
|
28
|
+
Requires-Dist: pandas>=1.3; extra == "pandas"
|
|
29
|
+
Provides-Extra: test
|
|
30
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
31
|
+
Requires-Dist: pandas>=1.3; extra == "test"
|
|
32
|
+
Dynamic: license-file
|
|
33
|
+
|
|
34
|
+
# compsapi: eBay sold listings API client for Python
|
|
35
|
+
|
|
36
|
+
eBay sold listings API client for Python: real sold prices, price stats and live listings as JSON or a pandas DataFrame, with up to 3 years of history, accepted Best Offer prices, and 12 more marketplaces (StockX, GOAT, TCGplayer, Reverb, Mercari, Poshmark and others) on the same key.
|
|
37
|
+
|
|
38
|
+
[Docs](https://compsapi.com/docs) · [OpenAPI](https://api.compsapi.com/openapi.json) · [Pricing](https://compsapi.com/pricing) · [Get a free key](https://compsapi.com)
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install compsapi # requests only
|
|
42
|
+
pip install "compsapi[pandas]" # adds DataFrame output
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The free plan is 100 requests a month with no card. Set your key once:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
export COMPSAPI_API_KEY=sk_live_...
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Quickstart
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from compsapi import CompsAPI
|
|
55
|
+
|
|
56
|
+
client = CompsAPI() # reads COMPSAPI_API_KEY, or CompsAPI("sk_live_...")
|
|
57
|
+
|
|
58
|
+
# Sold listings, newest sale first
|
|
59
|
+
res = client.sold("nintendo switch oled", days=30, condition="used", stats=True)
|
|
60
|
+
print(res["stats"]["median"], "median from", res["stats"]["used_for_stats"], "sales")
|
|
61
|
+
for item in res["items"][:5]:
|
|
62
|
+
print(item["last_sold"], item["price"], item["title"])
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Comps for a card in one call
|
|
66
|
+
|
|
67
|
+
`/v1/comps` returns price stats over every matching sale in the window plus the 10 newest sales, with junk listings (lots, mystery packs, replicas) left out by default.
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
res = client.comps("umbreon vmax 215/203", grader="PSA", grade=10)
|
|
71
|
+
s = res["stats"]
|
|
72
|
+
print(f"PSA 10 median ${s['median']:,.2f} (p25 {s['p25']}, p75 {s['p75']}, n={s['used_for_stats']})")
|
|
73
|
+
|
|
74
|
+
raw = client.comps("umbreon vmax 215/203", graded=False) # the raw card market
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Every sale across pages
|
|
78
|
+
|
|
79
|
+
`iter_sold` walks pages in order until `next_page` is false. Each page is one request, so set `max_pages`.
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
for item in client.iter_sold("omega speedmaster", days=365, max_pages=5):
|
|
83
|
+
print(item["item_id"], item["price"])
|
|
84
|
+
|
|
85
|
+
items = client.sold_all("lego 75192", days=90, max_pages=3)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Pages per search depend on the plan (free 10, Starter 25, Growth and up 200). For deep history a fixed window is faster than a long page walk:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from datetime import date
|
|
92
|
+
|
|
93
|
+
q3 = client.sold_all("rolex submariner 126610", start=date(2025, 7, 1), end=date(2025, 9, 30), max_pages=10)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## pandas
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
df = client.sold_df("canon eos r5", days=90, max_pages=2) # one row per sale
|
|
100
|
+
df.set_index("last_sold").resample("W")["price"].median() # weekly median
|
|
101
|
+
|
|
102
|
+
from compsapi import to_dataframe
|
|
103
|
+
df = to_dataframe(client.sold("umbreon vmax 215/203", grader="PSA", grade=9)) # nested card.* -> card_*
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
`last_sold` comes back as a UTC datetime column; nested objects are flattened (`card_grade`, `signals_days_on_market`).
|
|
107
|
+
|
|
108
|
+
## Accepted Best Offer prices
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
res = client.sold("omega speedmaster", days=30, best_offer=True) # adds best_offer to each row
|
|
112
|
+
offers = client.sold("omega speedmaster", days=30, best_offer="only") # accepted offers only
|
|
113
|
+
checked = client.sold("omega speedmaster", days=30, best_offer="verify")
|
|
114
|
+
for i in checked["items"]:
|
|
115
|
+
print(i["price"], i.get("best_offer_confidence"), i.get("asking_price"))
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
`price` is what the buyer paid, so an accepted offer shows the offer price, never the asking price.
|
|
119
|
+
|
|
120
|
+
## Live listings
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
live = client.active("kitchenaid mixer", sort="price_asc", condition="used", per_page=50)
|
|
124
|
+
print(live["total_active"], "listed now")
|
|
125
|
+
|
|
126
|
+
for listing in client.iter_active("air jordan 1 chicago", source="poshmark", max_pages=2):
|
|
127
|
+
print(listing["price"], listing["url"])
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Other marketplaces
|
|
131
|
+
|
|
132
|
+
Pass `source=` to read StockX, GOAT, TCGplayer, Reverb, Grailed, Poshmark, Mercari, Vinted, Goldin, Fanatics Collect, MySlabs, Pristine, PSA auction prices, or `all`:
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
client.sold("jordan 4 black cat", source="stockx", item_size="10", days=90)
|
|
136
|
+
client.comps("fender stratocaster american professional ii", source="reverb")
|
|
137
|
+
client.sources()["sources"]
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## PSA population and certs
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
spec = client.lookup("2018 panini prizm luka doncic 280")["results"][0]["spec_id"]
|
|
144
|
+
pop = client.population(spec=spec)
|
|
145
|
+
print(pop["total_graded"], pop["gem_rate"])
|
|
146
|
+
cert = client.cert("<PSA cert number>", recent=5) # the number on the slab label
|
|
147
|
+
print(cert["found"], cert.get("grade"))
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## Coming from findCompletedItems
|
|
151
|
+
|
|
152
|
+
eBay's Finding API (`findCompletedItems`) is gone. The same request with this client:
|
|
153
|
+
|
|
154
|
+
| findCompletedItems | compsapi |
|
|
155
|
+
|---|---|
|
|
156
|
+
| `keywords` | `q` |
|
|
157
|
+
| `itemFilter SoldItemsOnly=true` | always on: `/v1/sold` returns sales only |
|
|
158
|
+
| `itemFilter Condition` | `condition="new"` (also `open_box`, `refurbished`, `used`, `parts`, comma list) |
|
|
159
|
+
| `itemFilter EndTimeFrom` / `EndTimeTo` | `start` / `end` (YYYY-MM-DD) or `days` |
|
|
160
|
+
| `itemFilter MinPrice` / `MaxPrice` | `min_price` / `max_price` |
|
|
161
|
+
| `categoryId` | `category` |
|
|
162
|
+
| `GLOBAL-ID` (EBAY-GB, EBAY-DE ...) | `site="UK"`, `"DE"`, `"FR"`, `"IT"`, `"ES"`, `"CA"`, `"AU"` |
|
|
163
|
+
| `paginationInput.entriesPerPage` / `pageNumber` | `size` (10 to 240) / `page`, or `iter_sold()` |
|
|
164
|
+
| `sellingStatus.currentPrice` | `price` (USD, what the buyer paid) |
|
|
165
|
+
| `listingInfo.endTime` | `last_sold` |
|
|
166
|
+
| `sellingStatus.bidCount` | `bids` |
|
|
167
|
+
| `galleryURL` / `viewItemURL` | `image` / `url` |
|
|
168
|
+
|
|
169
|
+
## Errors and limits
|
|
170
|
+
|
|
171
|
+
```python
|
|
172
|
+
from compsapi import CompsAPIError, QuotaExceededError, RateLimitError
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
client.sold("charizard")
|
|
176
|
+
except QuotaExceededError:
|
|
177
|
+
... # monthly quota used; resets with the UTC month
|
|
178
|
+
except RateLimitError as e:
|
|
179
|
+
print("retry in", e.retry_after)
|
|
180
|
+
except CompsAPIError as e:
|
|
181
|
+
print(e.status, e.message)
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
| Class | When |
|
|
185
|
+
|---|---|
|
|
186
|
+
| `BadRequestError` | 400: missing or invalid parameter, page past the plan limit, search too broad |
|
|
187
|
+
| `AuthenticationError` | 401: missing or wrong key |
|
|
188
|
+
| `PermissionDeniedError` | 403: key expired |
|
|
189
|
+
| `RateLimitError` / `QuotaExceededError` | 429: per minute rate (retried for you, honouring `Retry-After`) / monthly quota |
|
|
190
|
+
| `ServerError` | 5xx (retried for you) |
|
|
191
|
+
|
|
192
|
+
Failed searches do not count against your quota. `client.usage()` is free and shows today's use and your caps; `client.last_rate_limit` holds the rate headers of the last response.
|
|
193
|
+
|
|
194
|
+
## Options
|
|
195
|
+
|
|
196
|
+
`CompsAPI(api_key=None, base_url="https://api.compsapi.com", timeout=90, max_retries=2, session=None, user_agent=None)`
|
|
197
|
+
|
|
198
|
+
Every endpoint parameter in the [reference](https://compsapi.com/docs) is a keyword argument. Lists are sent comma separated (`grade=[9, 10]`), booleans become the API's switches (`stats=True`), dates become `YYYY-MM-DD`. Responses are plain dicts with `TypedDict` hints (`compsapi.types`), so new fields come through untouched.
|
|
199
|
+
|
|
200
|
+
## Links
|
|
201
|
+
|
|
202
|
+
- API reference: https://compsapi.com/docs
|
|
203
|
+
- OpenAPI 1.11.0: https://api.compsapi.com/openapi.json
|
|
204
|
+
- Node client: `npm install compsapi`
|
|
205
|
+
- MCP server for AI agents: https://compsapi.com/docs#mcp
|
|
206
|
+
|
|
207
|
+
MIT licensed.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
compsapi/__init__.py,sha256=ZAklIIXHLCrcO1S9meS-ZvCwizYLHHRurUZcfSCp3oY,829
|
|
2
|
+
compsapi/_client.py,sha256=KsIFWhAPXehQKao5nwHZ3Y-evBsSvAU6l_aWjlBkwBg,19885
|
|
3
|
+
compsapi/_errors.py,sha256=tRWT4BHNSsAulmck5ufBA4C2RYf9-t6jwffNe3XnnzU,2591
|
|
4
|
+
compsapi/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
5
|
+
compsapi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
compsapi/types.py,sha256=Z8HjnGNLx_Wi8J9tUFXozxcXbxvNtfcxsouyketYB0Q,7920
|
|
7
|
+
compsapi-0.1.0.dist-info/licenses/LICENSE,sha256=0RNZ8QAZshpYco_zPe7NN35YeXNlxUZAKpn9QHOKPfY,1065
|
|
8
|
+
compsapi-0.1.0.dist-info/METADATA,sha256=-YMmT93HGVYGzmR34P2EOBfR7PQQeKBFXcBtTnecKw4,8405
|
|
9
|
+
compsapi-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
compsapi-0.1.0.dist-info/top_level.txt,sha256=X-dzQmsrHOV2oslfk3O0szFu-HZwjEfiXF77DHw9P6o,9
|
|
11
|
+
compsapi-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 CompsAPI
|
|
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
|
+
compsapi
|