discogs-sdk 0.4.0__tar.gz → 0.6.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.
Files changed (75) hide show
  1. discogs_sdk-0.6.0/PKG-INFO +646 -0
  2. discogs_sdk-0.6.0/README.md +616 -0
  3. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/pyproject.toml +14 -4
  4. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/pyproject.toml.orig +27 -17
  5. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/__init__.py +5 -0
  6. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/_client.py +209 -40
  7. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/_lazy.py +34 -2
  8. discogs_sdk-0.6.0/src/discogs_sdk/_async/_oauth.py +131 -0
  9. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/_paginator.py +80 -22
  10. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/_resource.py +3 -1
  11. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/artists.py +3 -2
  12. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/collection.py +37 -15
  13. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/exports.py +13 -2
  14. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/labels.py +3 -2
  15. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/lists.py +3 -2
  16. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/marketplace.py +14 -10
  17. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/masters.py +3 -2
  18. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/releases.py +29 -11
  19. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/uploads.py +10 -1
  20. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/users.py +8 -7
  21. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/wantlist.py +8 -6
  22. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_base_client.py +266 -73
  23. discogs_sdk-0.6.0/src/discogs_sdk/_cache.py +316 -0
  24. discogs_sdk-0.6.0/src/discogs_sdk/_events.py +71 -0
  25. discogs_sdk-0.6.0/src/discogs_sdk/_exceptions.py +145 -0
  26. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/_client.py +195 -44
  27. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/_lazy.py +35 -2
  28. discogs_sdk-0.6.0/src/discogs_sdk/_sync/_oauth.py +130 -0
  29. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/_paginator.py +76 -20
  30. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/_resource.py +3 -1
  31. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/artists.py +3 -2
  32. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/collection.py +21 -15
  33. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/exports.py +11 -2
  34. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/labels.py +3 -2
  35. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/lists.py +3 -2
  36. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/marketplace.py +12 -10
  37. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/masters.py +3 -2
  38. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/releases.py +28 -13
  39. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/uploads.py +10 -1
  40. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/users.py +8 -7
  41. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/wantlist.py +8 -6
  42. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/_common.py +98 -21
  43. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/_lazy_fields.py +43 -30
  44. discogs_sdk-0.6.0/src/discogs_sdk/models/_timestamp.py +65 -0
  45. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/collection.py +8 -1
  46. discogs_sdk-0.6.0/src/discogs_sdk/models/export.py +24 -0
  47. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/list_.py +18 -4
  48. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/marketplace.py +21 -5
  49. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/release.py +9 -2
  50. discogs_sdk-0.6.0/src/discogs_sdk/models/upload.py +26 -0
  51. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/user.py +9 -1
  52. discogs_sdk-0.4.0/PKG-INFO +0 -371
  53. discogs_sdk-0.4.0/README.md +0 -342
  54. discogs_sdk-0.4.0/src/discogs_sdk/_async/_oauth.py +0 -91
  55. discogs_sdk-0.4.0/src/discogs_sdk/_cache.py +0 -142
  56. discogs_sdk-0.4.0/src/discogs_sdk/_exceptions.py +0 -60
  57. discogs_sdk-0.4.0/src/discogs_sdk/_sync/_oauth.py +0 -92
  58. discogs_sdk-0.4.0/src/discogs_sdk/models/export.py +0 -15
  59. discogs_sdk-0.4.0/src/discogs_sdk/models/upload.py +0 -16
  60. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/LICENSE.txt +0 -0
  61. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/__init__.py +0 -0
  62. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/__init__.py +0 -0
  63. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_async/resources/search.py +0 -0
  64. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_oauth_types.py +0 -0
  65. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/__init__.py +0 -0
  66. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/__init__.py +0 -0
  67. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/_sync/resources/search.py +0 -0
  68. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/__init__.py +0 -0
  69. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/artist.py +0 -0
  70. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/label.py +0 -0
  71. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/master.py +0 -0
  72. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/search.py +0 -0
  73. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/models/wantlist.py +0 -0
  74. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/oauth.py +0 -0
  75. {discogs_sdk-0.4.0 → discogs_sdk-0.6.0}/src/discogs_sdk/py.typed +0 -0
@@ -0,0 +1,646 @@
1
+ Metadata-Version: 2.4
2
+ Name: discogs-sdk
3
+ Version: 0.6.0
4
+ Summary: Modern Python client for the Discogs API
5
+ Keywords: api,discogs,music,python,sdk
6
+ Author: Jean-Marc Fontaine
7
+ Author-email: Jean-Marc Fontaine <jm@jmfontaine.net>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE.txt
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Programming Language :: Python :: 3.15
19
+ Classifier: Typing :: Typed
20
+ Requires-Dist: httpx2>=2.12
21
+ Requires-Dist: pydantic>=2.12
22
+ Requires-Dist: pydantic>=2.14 ; python_full_version == '3.15.*'
23
+ Requires-Dist: typing-extensions>=4
24
+ Requires-Dist: tzdata>=2024.1
25
+ Requires-Python: >=3.10
26
+ Project-URL: Homepage, https://github.com/jmfontaine/discogs-sdk
27
+ Project-URL: Issues, https://github.com/jmfontaine/discogs-sdk/issues
28
+ Project-URL: Repository, https://github.com/jmfontaine/discogs-sdk
29
+ Description-Content-Type: text/markdown
30
+
31
+ # discogs-sdk
32
+
33
+ <p align="center">
34
+ <a href="https://pypi.org/project/discogs-sdk/"><img src="https://img.shields.io/pypi/v/discogs-sdk.svg" alt="PyPI version"></a>
35
+ <a href="https://pypi.org/project/discogs-sdk/"><img src="https://img.shields.io/pypi/pyversions/discogs-sdk.svg" alt="Python versions"></a>
36
+ <a href="https://github.com/jmfontaine/discogs-sdk/actions"><img src="https://github.com/jmfontaine/discogs-sdk/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
37
+ <a href="https://pypi.org/project/discogs-sdk/"><img src="https://img.shields.io/pypi/dm/discogs-sdk.svg" alt="PyPI downloads"></a>
38
+ <a href="https://github.com/jmfontaine/discogs-sdk/blob/main/LICENSE.txt"><img src="https://img.shields.io/pypi/l/discogs-sdk.svg" alt="License"></a>
39
+ </p>
40
+
41
+ discogs-sdk is a modern Python client for the [Discogs API](https://www.discogs.com/developers) covering every documented v2 endpoint, with a fluent chainable syntax and built-in response caching.
42
+
43
+ ```python
44
+ from discogs_sdk import Discogs
45
+
46
+ with Discogs() as client:
47
+ release = client.releases.get(352665)
48
+ print(f"{release.title} ({release.year})")
49
+
50
+ for result in client.search(query="Nine Inch Nails", type="artist"):
51
+ print(result.title)
52
+ ```
53
+
54
+ ## Installation
55
+
56
+ ```bash
57
+ pip install discogs-sdk
58
+ # or
59
+ uv add discogs-sdk
60
+ ```
61
+
62
+ Requires Python 3.10+.
63
+
64
+ ## Features
65
+
66
+ - **Complete Endpoint Coverage** — Every route in the Discogs API v2 documentation
67
+ - **Fluent API** — Chain sub-resources naturally: `client.releases.get(id).rating.get()`
68
+ - **Lazy Loading** — No HTTP calls until you actually need the data
69
+ - **Effortless Pagination** — Browse results without managing pages or offsets
70
+ - **Rate Limit Aware** — Bounded retries with `Retry-After` support, the live budget on `client.ratelimit`, and a structured event per request
71
+ - **Built-in Caching** — Optional TTL-based caching reduces API calls
72
+ - **Flexible Auth** — Supports personal tokens, consumer key/secret, or full OAuth 1.0a
73
+ - **Type Safe** — Get autocomplete and IDE support
74
+ - **Async & Sync** — Full support for both synchronous and asynchronous workflows
75
+
76
+ ### How it compares
77
+
78
+ The established alternative is [python3-discogs-client](https://github.com/joalla/discogs_client). Both load data
79
+ lazily, paginate automatically, support OAuth 1.0a and back off on HTTP 429, so the differences that matter are:
80
+
81
+ | | discogs-sdk | python3-discogs-client |
82
+ |---|---|---|
83
+ | Documented v2 API coverage | Complete | Partial † |
84
+ | Sync and async | Both | Sync only |
85
+ | Responses | Typed Pydantic models | Untyped attributes |
86
+ | Response cache | In-memory or SQLite | None |
87
+
88
+ † No inventory export or upload, release ratings or have/want stats, collection fields, folder creation,
89
+ contributions or submissions.
90
+
91
+ ## Quick start
92
+
93
+ ### Authentication
94
+
95
+ Set your personal access token from [your Discogs developer settings](https://www.discogs.com/settings/developers) as an environment variable:
96
+
97
+ ```bash
98
+ export DISCOGS_TOKEN="your-token-here"
99
+ ```
100
+
101
+ ```python
102
+ from discogs_sdk import Discogs
103
+
104
+ client = Discogs() # reads DISCOGS_TOKEN from environment
105
+ ```
106
+
107
+ You can also pass credentials explicitly:
108
+
109
+ ```python
110
+ client = Discogs(token="your-token-here")
111
+ ```
112
+
113
+ The SDK supports three auth modes: personal token, consumer key/secret, and OAuth 1.0a. Exactly one mode is selected
114
+ when the client is constructed, and only that mode's credentials are used. The precedence is:
115
+
116
+ 1. An explicit `token` selects personal-token auth and overrides every environment credential.
117
+ 2. Explicit OAuth access-token credentials select OAuth; any missing half may come from the matching `DISCOGS_*`
118
+ variable, but an unrelated environment token never takes over.
119
+ 3. Explicit `consumer_key`/`consumer_secret` select consumer auth, without borrowing environment access tokens.
120
+ 4. With no auth arguments, the environment resolves the mode: `DISCOGS_TOKEN`, then a complete OAuth set, then
121
+ `DISCOGS_CONSUMER_KEY`/`DISCOGS_CONSUMER_SECRET`, then unauthenticated.
122
+
123
+ An explicitly selected but incomplete credential set raises `ValueError` rather than quietly falling back to a
124
+ different account or mode. See [`examples/authentication.py`](examples/authentication.py) for the full OAuth flow.
125
+
126
+ > [!TIP]
127
+ > Use a `.env` file with [python-dotenv](https://pypi.org/project/python-dotenv/) or
128
+ > [direnv](https://direnv.net/) to avoid exporting tokens manually in every shell.
129
+
130
+ > [!NOTE]
131
+ > Discogs allows 60 requests/minute authenticated and 25/minute unauthenticated, measured as a moving average over
132
+ > the last 60 seconds. The SDK does not pace your requests: it retries a rate-limited **read** a bounded number of
133
+ > times (`max_retries`, default 3), honouring `Retry-After` (seconds or an HTTP-date) up to 60 seconds. A longer
134
+ > `Retry-After` is not slept through: the error is raised immediately, `RateLimitError.retry_after` carries the raw
135
+ > value, and you decide whether to wait. Sustained traffic above the limit still needs pacing on your side, and you can
136
+ > still receive `RateLimitError` once the retries are exhausted.
137
+
138
+ > [!WARNING]
139
+ > Mutations are not replayed. A `POST`, `PUT` or `DELETE` is retried only when the failure proves the request never
140
+ > reached the server, such as a refused connection. After a read timeout, a dropped connection or a 5xx the change may
141
+ > already have been committed, so the SDK raises instead of sending it again — the remote outcome is genuinely unknown
142
+ > and only you can decide how to reconcile it.
143
+
144
+ Every transport failure surfaces as `DiscogsConnectionError`, chained to the underlying `httpx2` error
145
+ (`exc.__cause__`). Reads retry the transient ones: network errors, timeouts, and a keep-alive connection the server
146
+ closed (`RemoteProtocolError`). Failures that would repeat identically — `LocalProtocolError`, `UnsupportedProtocol`,
147
+ `ProxyError`, `DecodingError`, `TooManyRedirects` — are raised at once for every method.
148
+
149
+ ### Fetching resources
150
+
151
+ ```python
152
+ # Releases, artists, masters, labels
153
+ release = client.releases.get(352665)
154
+ print(release.title) # lazy — HTTP fires here → "The Downward Spiral"
155
+
156
+ artist = client.artists.get(3857)
157
+ print(artist.name) # "Nine Inch Nails"
158
+
159
+ master = client.masters.get(3719)
160
+ label = client.labels.get(647)
161
+ ```
162
+
163
+ These lazy resources are read-only views: assigning to one of their attributes raises `AttributeError`, since the
164
+ value would never reach Discogs. Where the API accepts writes, they go through a resource method such as
165
+ `release.rating.update()` or `user.wantlist.update()`.
166
+
167
+ Each identifier you pass (username, order id, release id and so on) is sent as a
168
+ single, percent-encoded path segment, so a `/`, `?` or `#` in it cannot reach a
169
+ different endpoint. `"."` and `".."` raise `ValueError` before any request is made.
170
+
171
+ ### Search
172
+
173
+ ```python
174
+ for result in client.search(query="Pretty Hate Machine", type="release", year="1989"):
175
+ print(f"[{result.type}] {result.title}")
176
+ # [release] Nine Inch Nails - Pretty Hate Machine
177
+ ```
178
+
179
+ ### Sub-resources
180
+
181
+ ```python
182
+ # Community rating
183
+ rating = client.releases.get(352665).rating.get()
184
+ print(f"Average: {rating.rating.average}") # Average: 4.49
185
+
186
+ # Artist releases with sorting
187
+ for rel in client.artists.get(3857).releases.list(sort="year", sort_order="desc"):
188
+ print(f"{rel.title} ({rel.year})")
189
+
190
+ # Master versions with filters
191
+ for v in client.masters.get(3719).versions.list(format="Vinyl", country="US"):
192
+ print(f"{v.title} [{v.format}]")
193
+ ```
194
+
195
+ ### Async usage
196
+
197
+ ```python
198
+ import asyncio
199
+ from discogs_sdk import AsyncDiscogs
200
+
201
+
202
+ async def main():
203
+ async with AsyncDiscogs() as client: # reads DISCOGS_TOKEN from environment
204
+ # Must await lazy resources in async mode
205
+ release = await client.releases.get(352665)
206
+ print(release.title)
207
+
208
+ # Async iteration for paginated results
209
+ async for result in client.search(query="Nine Inch Nails"):
210
+ print(result.title)
211
+
212
+
213
+ asyncio.run(main())
214
+ ```
215
+
216
+ ### Collection
217
+
218
+ ```python
219
+ user = client.users.get("your_username")
220
+
221
+ # Folders
222
+ folders = user.collection.folders.list()
223
+ user.collection.folders.create(name="Industrial")
224
+
225
+ # Browse folder contents
226
+ for item in user.collection.folders.get(0).releases.list(sort="added"):
227
+ print(item.basic_information.title)
228
+
229
+ # Add a release. The response identifies the copy you just created, which is
230
+ # how you tell it apart from copies of the same release you already own.
231
+ created = user.collection.folders.get(1).releases.create(release_id=352665)
232
+
233
+ # Deep chaining: folder -> release -> instance -> fields
234
+ instances = user.collection.folders.get(1).releases.get(352665).instances
235
+ instances.get(created.instance_id).fields.update(field_id=1, value="Signed copy")
236
+
237
+ # Collection value
238
+ value = user.collection.value.get()
239
+ print(f"Median: {value.median}, Maximum: {value.maximum}")
240
+
241
+ # Wantlist — the add takes only the release id; Discogs drops notes and ratings
242
+ # sent to it, so they go in the update call
243
+ user.wantlist.create(release_id=352665)
244
+ user.wantlist.update(352665, notes="Original pressing", rating=4)
245
+ for want in user.wantlist.list():
246
+ print(want.basic_information.title)
247
+ ```
248
+
249
+ ### Marketplace
250
+
251
+ ```python
252
+ # Listings
253
+ listing = client.marketplace.listings.get(123456789)
254
+ new = client.marketplace.listings.create(
255
+ release_id=352665,
256
+ condition="Very Good Plus (VG+)",
257
+ price=25.00,
258
+ )
259
+ client.marketplace.listings.update(new.id, price=22.50)
260
+ client.marketplace.listings.delete(new.id)
261
+
262
+ # Orders
263
+ for order in client.marketplace.orders.list(status="Payment Received"):
264
+ print(f"Order {order.id}: {order.status}")
265
+
266
+ # Fee lookup
267
+ fee = client.marketplace.fee.get(price=25.00, currency="USD")
268
+ ```
269
+
270
+ ### Error handling
271
+
272
+ ```python
273
+ from discogs_sdk import NotFoundError, RateLimitError, AuthenticationError
274
+
275
+ try:
276
+ release = client.releases.get(999999999)
277
+ _ = release.title
278
+ except NotFoundError:
279
+ print("Not found")
280
+ except RateLimitError as exc:
281
+ print(f"Rate limited, retry after {exc.retry_after}s")
282
+ if exc.ratelimit: # the 429's own X-Discogs-Ratelimit* headers, when present
283
+ print(f"{exc.ratelimit.used}/{exc.ratelimit.limit} used this window")
284
+ except AuthenticationError:
285
+ print("Bad credentials")
286
+ ```
287
+
288
+ The full exception hierarchy:
289
+
290
+ ```
291
+ DiscogsError
292
+ ├── DiscogsConnectionError
293
+ ├── CacheMissError
294
+ └── DiscogsAPIError
295
+ ├── AuthenticationError (401)
296
+ ├── ForbiddenError (403)
297
+ ├── NotFoundError (404)
298
+ ├── ValidationError (422)
299
+ └── RateLimitError (429)
300
+ ```
301
+
302
+ The OAuth helpers in `discogs_sdk.oauth` (`get_request_token`, `get_access_token`
303
+ and their `async_` variants) raise from the same hierarchy: an error status maps as
304
+ above (401 → `AuthenticationError`, 400 → `DiscogsAPIError`, …), a transport failure
305
+ raises `DiscogsConnectionError`, and a successful response missing either
306
+ `oauth_token` or `oauth_token_secret` raises `DiscogsAPIError` naming any
307
+ `oauth_problem`. They never retry: the access-token exchange is sent at most once.
308
+
309
+ `str(exc)` on a `DiscogsAPIError` is a short summary, `"<status>: <message>"`. The
310
+ message is the body's `message` when that is a non-empty string, otherwise the body
311
+ itself, cut to 500 characters so a gateway error page does not flood logs. The full
312
+ payload stays in `exc.response_body`.
313
+
314
+ Every SDK exception survives `pickle`, `copy.copy` and `copy.deepcopy` with its
315
+ attributes (`status_code`, `response_body`, `retry_after`, `ratelimit`, `method`,
316
+ `url`) and any notes, so an error raised in a `ProcessPoolExecutor` or
317
+ `multiprocessing` worker reaches the parent as the same class. As with any pickled
318
+ exception, `__cause__`, `__context__` and the traceback are not carried over.
319
+
320
+ A paginated iterator (`.list()`, `search()`) that raises keeps its place. Whether the
321
+ request for a page fails, the page's envelope has the wrong shape, or one of its items
322
+ fails validation (Pydantic's `ValidationError`), `page`, the totals and the URLs stay as
323
+ they were before that page, and the next `next()` or `anext()` requests the same page
324
+ again. Items already yielded are not repeated, and none are skipped.
325
+
326
+ A wrong shape raises `DiscogsError` naming the endpoint, the key and the JSON type
327
+ received, for example `GET /users/trent_reznor/submissions: "submissions" is null,
328
+ expected an object`. That covers a body that is not an object, a `pagination` or a
329
+ non-empty `pagination.urls` that is not an object, and an items key that is not an
330
+ array (or, for nested items, not an object on the way). An absent items key is an
331
+ empty page.
332
+
333
+ #### Exceptions outside `DiscogsError`
334
+
335
+ Apart from the `ValueError`s that reject invalid arguments, such as incomplete
336
+ credentials, the SDK lets three exceptions through on purpose, and
337
+ `except DiscogsError` catches none of them:
338
+
339
+ - `json.JSONDecodeError` (a `ValueError`) when a 2xx response that the SDK reads as
340
+ JSON has a body that is not JSON; a body that is not even UTF-8 raises
341
+ `UnicodeDecodeError`, also a `ValueError`. Error statuses are mapped before the
342
+ endpoint parses the body, and a success is not an API error, so the SDK raises the
343
+ parse failure instead of a fallback value.
344
+ - `pydantic.ValidationError` (a `ValueError`) when a 2xx JSON body does not fit the
345
+ model, such as a release whose `id` is not a number. The response was a success,
346
+ so this is a parsing failure rather than an API error. Only a list page's envelope
347
+ is checked by the SDK itself, as described above; its items go to Pydantic like
348
+ any other model.
349
+ - `FileNotFoundError` (an `OSError`) from `client.uploads.create()`, `change()` or
350
+ `delete()` when `file` names a path that does not exist. The file is read before
351
+ any request is sent, so there is no response to map.
352
+
353
+ Transport failures are not among them: they surface as `DiscogsConnectionError`, as
354
+ described under [Authentication](#authentication).
355
+
356
+ Two unrelated classes are named `ValidationError`. `discogs_sdk.ValidationError` is
357
+ the HTTP 422 `DiscogsAPIError` above and is not a `ValueError`;
358
+ `pydantic.ValidationError` is the model parsing failure. Imported under the same
359
+ name, one silently shadows the other, so alias them:
360
+
361
+ ```python
362
+ from discogs_sdk import ValidationError as ApiValidationError
363
+ from pydantic import ValidationError as ModelValidationError
364
+ ```
365
+
366
+ ## Examples
367
+
368
+ The [`examples/`](examples/) directory has runnable scripts for every feature:
369
+
370
+ - [`quickstart.py`](examples/quickstart.py) — first requests, lazy loading, search
371
+ - [`authentication.py`](examples/authentication.py) — all auth modes including OAuth 1.0a
372
+ - [`database.py`](examples/database.py) — releases, artists, masters, labels, search
373
+ - [`marketplace.py`](examples/marketplace.py) — listings, orders, fees, inventory
374
+ - [`collection.py`](examples/collection.py) — folders, instances, fields, wantlist
375
+ - [`async_usage.py`](examples/async_usage.py) — async client with await and async for
376
+ - [`advanced.py`](examples/advanced.py) — error handling, caching, custom HTTP clients, exports
377
+
378
+ ## Configuration
379
+
380
+ | Parameter | Default | Description |
381
+ |---|---|---|
382
+ | `access_token_secret` | `None` | OAuth access token secret |
383
+ | `access_token` | `None` | OAuth access token |
384
+ | `base_url` | `https://api.discogs.com` | API base URL; pagination `next` links are rebased onto it, and a link to any origin other than it or `https://api.discogs.com` raises `DiscogsError` |
385
+ | `cache_dir` | `None` | Directory for SQLite cache; in-memory when omitted. Used only with `cache=True` |
386
+ | `cache_ttl` | `3600.0` | Cache time-to-live in seconds. Used only with `cache=True` |
387
+ | `cache` | `False` | `True` builds the built-in backend from `cache_dir` and `cache_ttl`; or pass a custom `ResponseCache` instance, which carries its own TTL and storage and is never closed by the client |
388
+ | `consumer_key` | `None` | OAuth consumer key |
389
+ | `consumer_secret` | `None` | OAuth consumer secret |
390
+ | `http_client` | `None` | Custom `httpx2.Client` or `httpx2.AsyncClient` |
391
+ | `max_retries` | `3` | Max retries, `>= 0` (`0` disables retries, a negative value raises `ValueError`); reads retry on 429/5xx, network errors, timeouts and dropped connections, mutations only on pre-send failures. A `Retry-After` above 60s raises immediately instead |
392
+ | `media_type` | `"discogs"` | Format of text fields: `"discogs"` (Discogs markup), `"html"` or `"plaintext"`; sent in the `Accept` header, and cached responses are kept apart per value |
393
+ | `on_request` | `None` | Callback receiving a `RequestEvent` per request |
394
+ | `timeout` | `30.0` | Request timeout in seconds for the HTTP client the SDK creates; an injected `http_client` keeps its own (see [Custom HTTP clients](#custom-http-clients)) |
395
+ | `token` | `None` | Personal access token |
396
+ | `user_agent` | `discogs-sdk/<version> +https://github.com/jmfontaine/discogs-sdk` | `User-Agent` header; a non-empty value replaces the default entirely |
397
+
398
+ With `cache=False`, the default, `cache_dir` and `cache_ttl` are ignored and no cache or directory is created; a
399
+ `ResponseCache` instance ignores them too. `cache_ttl=0` is accepted and expires every entry at once, so each read
400
+ refetches: it is not a way to say "no limit".
401
+
402
+ See [Authentication](#authentication) for how a credential mode is selected.
403
+
404
+ ### Caching
405
+
406
+ Only successful `GET`/`HEAD` responses are cached, and a `GET` body that is not valid JSON (a gateway's HTML page, an
407
+ empty body) never is, so a bad response fails once instead of on every read; inventory export downloads, which are CSV,
408
+ are cached as they are. A body that is valid JSON but the wrong shape for its model is still cached until it expires.
409
+ Entries are keyed by method, fully resolved URL, the effective `Accept` representation, and a non-reversible digest of
410
+ the selected mode's credentials, so two clients sharing one cache — or one SQLite directory — never serve each other's
411
+ private responses, and unauthenticated traffic gets its own namespace. No token or secret is stored in a key.
412
+
413
+ Job status reads, `client.exports.get(id)` and `client.uploads.get(id)`, are never cached: each one reaches the API and
414
+ stores nothing, so a polling loop sees the job finish. A resolved proxy keeps its data, though, so poll with a new
415
+ `get()` call each time. Inside `cache_only()` these reads raise `CacheMissError`. `exports.list()`, `uploads.list()`
416
+ and `exports.download()` are cached as usual.
417
+
418
+ A successful write (`POST`, `PUT` or `DELETE` with a 2xx answer) clears the whole response cache, so no entry cached
419
+ before the write is served after it: not the written URL, not a list page, not a related folder or count. The rule
420
+ holds inside `no_cache()` too, and a cache shared between clients is cleared for all of them; entries are refetched on
421
+ demand, which costs requests. A failed write leaves the cache alone, and a cache that fails to clear is logged without
422
+ failing the write. Proxies and pages already resolved keep their in-memory data, so fetch a new proxy or iterate again
423
+ to see the change. Discogs itself may take a while to show a write, and a refetch made in that window caches what it
424
+ returned.
425
+
426
+ A cache built from `cache=True` belongs to the client, and `client.close()` closes it. A `ResponseCache` instance you
427
+ pass in stays yours, like an injected `http_client`: `client.close()` never closes it, so one cache can outlive any of
428
+ the clients sharing it. Call its `close()` yourself once every client using it is done.
429
+
430
+ The SQLite cache never fails a request. If its database is locked by another process, read-only, full or corrupt,
431
+ it logs a warning on the `discogs_sdk` logger and carries on: a lookup counts as a miss and a store is skipped, so the
432
+ response still reaches you. Using the cache after it has been closed raises `RuntimeError`. The database runs in WAL
433
+ mode, so `cache.db-wal` and `cache.db-shm` may appear next to `cache.db`.
434
+
435
+ The SQLite database holds the full bodies of your private responses (identity, orders with buyer addresses,
436
+ collection), so put `cache_dir` somewhere only you can read, such as `~/.cache/my-app`, never a shared path like
437
+ `/tmp`. A directory the cache creates is private (`0o700`) and `cache.db` is `0o600`; on POSIX, an existing `cache.db`
438
+ that is a symlink or belongs to another user raises `PermissionError`. Entries keep only the `Content-Type`, `ETag` and
439
+ `Last-Modified` response headers.
440
+
441
+ `client.no_cache()` bypasses the cache for the current execution context. Scopes nest, the previous state is
442
+ restored even when the block raises, and each context carries its own scope, so leaving it in one thread or task
443
+ never affects another (a pool worker, or a task created before the block, does not see it; see
444
+ [Concurrency](#concurrency)):
445
+
446
+ ```python
447
+ with client.no_cache():
448
+ fresh = client.releases.get(352665).title # always hits the API
449
+ ```
450
+
451
+ `client.cache_only()` is the mirror image: inside the scope a request the cache cannot serve — a miss, an expired
452
+ entry, a non-`GET`, a job status read, a disabled cache, an injected `http_client` without SDK credentials or an
453
+ enclosing `no_cache()` — raises `CacheMissError` before any network I/O. It nests and restores exactly like
454
+ `no_cache()`, so you can try everything for free first:
455
+
456
+ ```python
457
+ from discogs_sdk import CacheMissError
458
+
459
+ with client.cache_only():
460
+ try:
461
+ title = client.releases.get(352665).title # never hits the API
462
+ except CacheMissError as exc:
463
+ print(f"Not cached: {exc.method} {exc.url}")
464
+ ```
465
+
466
+ ### Observability
467
+
468
+ Every live response carries Discogs' `X-Discogs-Ratelimit`, `X-Discogs-Ratelimit-Used` and
469
+ `X-Discogs-Ratelimit-Remaining` headers. `client.ratelimit` holds them as a `RateLimit(limit, used, remaining)`
470
+ parsed from the most recent **network** response: a cache hit never touches it, and a response without the headers
471
+ leaves the last known value in place. It is `None` until the first live response.
472
+
473
+ `on_request` receives one `RequestEvent` per logical request, invoked synchronously — after a cache hit, or after the
474
+ final network response and before any error is raised, so the event exists even when the call raises. Intermediate
475
+ retried attempts do not emit; the final event carries `attempts`. A call that ends in `DiscogsConnectionError` emits
476
+ nothing, since there is no response. Exceptions raised by the callback propagate unchanged; keep it cheap and never
477
+ block in it, because the async client calls it from the event loop.
478
+
479
+ | Field | Meaning |
480
+ |---|---|
481
+ | `method` | Upper-case HTTP method |
482
+ | `url` | Fully resolved URL, query string included |
483
+ | `status_code` | Status of the response that ended the call |
484
+ | `source` | `"network"` or `"cache"` |
485
+ | `elapsed_ms` | Final network attempt, or the cache lookup |
486
+ | `attempts` | Network attempts (`1` = no retry); `0` on a cache hit |
487
+ | `stored` | Whether this call wrote the response to the cache |
488
+ | `ratelimit` | `RateLimit` from the response; always `None` on a cache hit |
489
+
490
+ A minimal pacing loop:
491
+
492
+ ```python
493
+ import time
494
+
495
+ client = Discogs(
496
+ token="...", on_request=lambda e: print(e.source, e.status_code, e.elapsed_ms)
497
+ )
498
+ title = client.releases.get(352665).title # lazy — the GET fires here
499
+ if client.ratelimit and client.ratelimit.remaining < 10:
500
+ time.sleep(60)
501
+ ```
502
+
503
+ ### Concurrency
504
+
505
+ One client may be shared by several threads (`Discogs`) or tasks (`AsyncDiscogs`). A few things are tied to a
506
+ context or an object rather than to the client.
507
+
508
+ `no_cache()` and `cache_only()` apply to the current execution context only. A task copies its context when it is
509
+ created, so a task created before the block does not see the scope. A pool worker runs in its own context, so
510
+ `with client.no_cache(): pool.map(...)` still serves the workers from the cache; on a free-threaded 3.14+ build, where
511
+ a new thread starts with a copy of its creator's context, a worker spawned inside the block keeps the scope for its
512
+ lifetime instead. Either way, enter the scope inside the worker, or run the work in a copy of the context taken inside
513
+ the scope. Take a new copy for each call: one `Context` cannot run in two threads at once, and sharing it raises
514
+ `RuntimeError`.
515
+
516
+ ```python
517
+ import contextvars
518
+ from concurrent.futures import ThreadPoolExecutor
519
+
520
+
521
+ def title(release_id):
522
+ return client.releases.get(release_id).title
523
+
524
+
525
+ with ThreadPoolExecutor() as pool:
526
+ with client.no_cache():
527
+ # copy_context() runs here, inside the scope
528
+ future = pool.submit(contextvars.copy_context().run, title, 352665)
529
+ print(future.result()) # The Downward Spiral, fetched from the API
530
+ ```
531
+
532
+ A page returned by `.list()` or `search()` is a single-pass iterator for one consumer. Several threads or tasks
533
+ iterating the same page race on its position and can fetch a page twice and yield its items twice, and a page that
534
+ is exhausted yields nothing on a second pass. Call `.list()` or `search()` again for each consumer and each pass.
535
+
536
+ `on_request` runs on the thread or task that made the request, once that request completes, so events arrive in
537
+ completion order rather than start order, and with several threads the callback can run in several of them at once.
538
+ `client.ratelimit` is the value from whichever live response completed last, not necessarily the one with the lowest
539
+ `remaining`: under concurrency it is a hint for pacing, not a global count.
540
+
541
+ The cache that `cache=True` builds locks internally. A custom `ResponseCache` shared across threads needs its own
542
+ locking, because the client calls its methods without synchronisation.
543
+
544
+ ### Custom HTTP clients
545
+
546
+ An injected `http_client` must be an `httpx2` client — the SDK is built on [httpx2](https://github.com/pydantic/httpx2),
547
+ Pydantic's maintained continuation of httpx. It owns its transport configuration and its lifecycle: `client.close()`
548
+ never closes it. SDK credentials, User-Agent and media type are still applied per request, so they describe the request
549
+ without mutating your client's defaults, and its own `httpx2.Auth` cannot replace credentials you gave the SDK.
550
+
551
+ An injected client's timeout is part of that transport configuration. The `timeout` argument only configures a client
552
+ the SDK creates, so `Discogs(http_client=httpx2.Client(timeout=99.0), timeout=1.0)` sends every request with the
553
+ injected client's 99-second timeout, even though `client.timeout` reports `1.0`. To control the timeout of an injected
554
+ client, set it on that client.
555
+
556
+ When the SDK has no credentials of its own, your client's authentication is preserved and its responses are never
557
+ cached, even with `cache=True`, because the SDK cannot tell whose account they belong to. Inside `cache_only()` every
558
+ request from such a client therefore raises `CacheMissError`.
559
+
560
+ ## Field naming
561
+
562
+ Model fields use clean Python names. Where the Discogs API uses inconsistent or cryptic keys, the SDK provides a readable alias while still accepting the raw API name during deserialization:
563
+
564
+ | API field | Python attribute | Models |
565
+ |---|---|---|
566
+ | `anv` | `name_variation` | `ArtistCredit` |
567
+ | `catno` | `catalog_number` | `LabelCredit`, `Company`, `LabelRelease`, `MasterVersion`, `SearchResult` |
568
+ | `created_ts` | `created_at` | `Export`, `Upload`, `List_` |
569
+ | `curr_abbr` | `currency_code` | `OriginalPrice`, `User` |
570
+ | `curr_id` | `currency_id` | `OriginalPrice` |
571
+ | `extraartists` | `extra_artists` | `Release`, `Track` |
572
+ | `finished_ts` | `finished_at` | `Export`, `Upload` |
573
+ | `from` | `from_user` | `OrderMessage` |
574
+ | `list_id` | `id` | `List_` |
575
+ | `listing_id` | `id` | `Listing` |
576
+ | `modified_ts` | `modified_at` | `List_` |
577
+ | `namevariations` | `name_variations` | `Artist` |
578
+ | `qty` | `quantity` | `Format` |
579
+ | `sublabels` | `sub_labels` | `Label` |
580
+ | `uri150` | `uri_150` | `Image` |
581
+
582
+ The Python name is the typed attribute. API names still resolve as attributes at runtime, but only dynamically: a type
583
+ checker treats them like any misspelled attribute, so read them through `getattr` where one is in play:
584
+
585
+ ```python
586
+ release = client.releases.get(352665) # The Downward Spiral
587
+ print(release.extra_artists) # Python name, typed
588
+ print(getattr(release, "extraartists")) # API name, runtime only — same value
589
+ ```
590
+
591
+ An API name that is a Python keyword, such as `from`, is reachable only through `getattr(message, "from")`.
592
+
593
+ An API name resolves to the same normalized value as the Python name, so `getattr(export, "created_ts")` is a
594
+ `datetime` too. To read what Discogs sent, use [`raw`](#original-api-values).
595
+
596
+ ## Timestamps
597
+
598
+ Discogs sends timestamps as strings in several shapes:
599
+
600
+ | Shape | Example | Where |
601
+ |---|---|---|
602
+ | ISO 8601 with an offset | `2005-01-03T23:17:26-08:00` | most fields |
603
+ | A space instead of `T` | `2011-08-30 14:21:45-07:00` | `User.registered` |
604
+ | No offset | `2026-10-11T07:07:34` | `Export` and `Upload` (`created_at`, `finished_at`) |
605
+
606
+ The SDK parses every one of them into a timezone-aware `datetime`, so you can compare and sort values from any
607
+ endpoint. This covers `Release` (`date_added`, `date_changed`), `CollectionItem.date_added`, `ListSummary`
608
+ (`date_added`, `date_changed`), `List_` (`created_at`, `modified_at`), `User.registered`, `Listing.posted`, `Order`
609
+ (`created`, `last_activity`), `OrderMessage.timestamp`, `Export` and `Upload` (`created_at`, `finished_at`).
610
+
611
+ - An offset that Discogs sends stays as sent.
612
+ - A value without an offset is read as `America/Los_Angeles` time and gets the fixed offset in force then (`-08:00` or
613
+ `-07:00`), the same kind of `tzinfo` as a value that arrives with one. Discogs does not document its zone; this is an
614
+ assumption. An export requested at 14:07:34 UTC reported `07:07:34`, and the offsets Discogs does send switch between
615
+ `-08:00` and `-07:00` with daylight saving. In the hour repeated when daylight saving ends, the SDK picks the first
616
+ occurrence.
617
+ - An empty string becomes `None`.
618
+ - A value the SDK cannot parse becomes `None`, and the SDK logs a warning on the `discogs_sdk` logger. The model still
619
+ loads, and `raw` keeps the string.
620
+
621
+ `model_dump(mode="json")` writes ISO 8601 with an explicit offset, and `model_validate` reads it back unchanged.
622
+
623
+ ## Original API values
624
+
625
+ Every model keeps the mapping it was validated from in `raw`. Use it to read a value as Discogs sent it, before
626
+ renaming or parsing:
627
+
628
+ ```python
629
+ release = client.releases.get(352665) # The Downward Spiral
630
+ print(release.date_added) # datetime(2005, 1, 3, 23, 17, 26, tzinfo=...)
631
+ print(release.raw["date_added"]) # '2005-01-03T23:17:26-08:00'
632
+ print(release.extra_artists[0].raw) # a nested model holds its own part of the payload
633
+ ```
634
+
635
+ `raw` is the decoded response itself, not a copy; its type is a read-only `Mapping`, but code holding the same dict can
636
+ still change it, and later reads see the change. Holding a model keeps the whole payload in memory. `model_dump()` and
637
+ `==` ignore `raw`. A model you build with keyword arguments or with `model_validate(model.model_dump())` reports that
638
+ input instead of an API response.
639
+
640
+ ## Contributing
641
+
642
+ Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
643
+
644
+ ## License
645
+
646
+ discogs-sdk is licensed under the [Apache License 2.0](LICENSE.txt).