bookinfo 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ .mypy_cache/
10
+ .coverage
11
+ .env
12
+ .idea/
13
+ .vscode/
bookinfo-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tn3w
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,136 @@
1
+ Metadata-Version: 2.5
2
+ Name: bookinfo
3
+ Version: 0.1.0
4
+ Summary: Python client for the free shlf.bid book API: books, authors, series, ISBNs and covers
5
+ Project-URL: Homepage, https://github.com/tn3w/bookinfo
6
+ Project-URL: Source, https://github.com/tn3w/bookinfo
7
+ Project-URL: Issues, https://github.com/tn3w/bookinfo/issues
8
+ Project-URL: API, https://shlf.bid/openapi.json
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: api-client,books,isbn,openlibrary,shlf
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Topic :: Software Development :: Libraries
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.9
25
+ Requires-Dist: httpx>=0.27
26
+ Requires-Dist: typing-extensions>=4.4; python_version < '3.11'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # bookinfo
30
+
31
+ [![CI](https://github.com/tn3w/bookinfo/actions/workflows/ci.yml/badge.svg)](https://github.com/tn3w/bookinfo/actions/workflows/ci.yml)
32
+ [![PyPI](https://img.shields.io/pypi/v/bookinfo)](https://pypi.org/project/bookinfo/)
33
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
34
+
35
+ Python client for the free [shlf.bid](https://shlf.bid) book API: millions of books and
36
+ authors with series, ISBNs, editions, descriptions, tags, covers and similar books from
37
+ Open Library, Wikidata and national libraries. No API key, no sign-up.
38
+
39
+ ## Install
40
+
41
+ ```sh
42
+ pip install bookinfo
43
+ ```
44
+
45
+ Requires Python 3.9+. The only dependency is [httpx](https://www.python-httpx.org)
46
+ (plus `typing_extensions` on Python older than 3.11).
47
+
48
+ ## Usage
49
+
50
+ ```python
51
+ import bookinfo
52
+
53
+ print(bookinfo.isbn("978-0-7475-3269-9").book.title)
54
+ print(bookinfo.search("dune", tag="fantasy").results[0].title)
55
+ ```
56
+
57
+ Every endpoint is available as a module-level function that shares one connection pool.
58
+ Create your own `BookInfo` for custom timeouts, retries or a different base URL:
59
+
60
+ ```python
61
+ from bookinfo import BookInfo
62
+
63
+ with BookInfo(timeout=30) as books:
64
+ hits = books.search("foundation", year_to=1960, limit=5)
65
+ print([book.title for book in hits.results])
66
+
67
+ book = books.work(82563)
68
+ print(book.title, book.series.name, book.tags)
69
+
70
+ print(books.recommend([82563, 27482]).results)
71
+ ```
72
+
73
+ Every method returns a frozen dataclass from `bookinfo.models` (`SearchPage`, `Work`,
74
+ `Author`, `Series`, ...) with attribute access and full type hints.
75
+
76
+ Options are typed keyword arguments that differ per endpoint (`SearchOptions`,
77
+ `CatalogueOptions`, ...): `language`, `author`, `tag`, `year_from`, `year_to`, `cover`,
78
+ `sort`, `page` and `limit`.
79
+
80
+ | Method | Endpoint |
81
+ | --- | --- |
82
+ | `search(q, **options)` | `/search` |
83
+ | `suggest(q)` | `/suggest` |
84
+ | `work(work_id)` / `works(work_ids)` | `/works/{id}` / `/works?ids=` |
85
+ | `isbn(isbn)` / `isbns(isbns)` | `/isbn/{isbn}` / `/isbn?isbns=` |
86
+ | `check_isbn(isbn)` | `/isbn/{isbn}/check` |
87
+ | `search_series(q)` / `series(series_id)` | `/series` / `/series/{id}` |
88
+ | `search_authors(q)` / `author(author_id)` | `/authors` / `/authors/{id}` |
89
+ | `author_works(author_id, sort="year")` | `/authors/{id}/works` |
90
+ | `similar(work_id)` / `recommend(work_ids)` | `/similar/{id}` / `/recommend` |
91
+ | `random(**options)` | `/random` |
92
+ | `catalogue(language, /, **options)` | `/catalogue/{language}` |
93
+ | `tags()` / `languages()` | `/tags` / `/languages` |
94
+ | `cover_url(work_id, language, width)` | `/b/{id}/{language}/{width}.avif` |
95
+ | `photo_url(author_id, width)` | `/a/{id}/{width}.avif` |
96
+
97
+ ### Paging
98
+
99
+ `paginate` walks every page of a list endpoint and yields the results one by one:
100
+
101
+ ```python
102
+ for book in books.paginate(books.author_works, 23919, sort="year"):
103
+ print(book.year, book.title)
104
+ ```
105
+
106
+ ### Errors and rate limits
107
+
108
+ Failed requests raise `BookInfoError` with `status`, `code` (`invalid_parameter`,
109
+ `not_found`, `rate_limited`, `unavailable`, and `network_error` or `invalid_response` when
110
+ no usable answer arrived; `status` is 0 without a response) and `message`. Rate limited (429) and
111
+ temporarily unavailable (502, 503, 504) answers are retried, honouring `Retry-After`; tune it with
112
+ `BookInfo(retries=2, timeout=10)`. Moved work ids are followed automatically.
113
+
114
+ ## Example
115
+
116
+ [examples/flask_app](examples/flask_app) is a small book browser built with Flask: search
117
+ with filters, book pages with series navigation, editions and similar books, authors,
118
+ series, ISBN lookup and a random book.
119
+
120
+ ```sh
121
+ uv run --with flask flask --app examples/flask_app/app run
122
+ ```
123
+
124
+ ## Development
125
+
126
+ ```sh
127
+ uv run pytest
128
+ ```
129
+
130
+ Releases are published to PyPI from GitHub Actions through
131
+ [trusted publishing](https://docs.pypi.org/trusted-publishers/): create a GitHub release
132
+ and the `publish.yml` workflow does the rest.
133
+
134
+ ## License
135
+
136
+ [MIT](LICENSE)
@@ -0,0 +1,108 @@
1
+ # bookinfo
2
+
3
+ [![CI](https://github.com/tn3w/bookinfo/actions/workflows/ci.yml/badge.svg)](https://github.com/tn3w/bookinfo/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/bookinfo)](https://pypi.org/project/bookinfo/)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+
7
+ Python client for the free [shlf.bid](https://shlf.bid) book API: millions of books and
8
+ authors with series, ISBNs, editions, descriptions, tags, covers and similar books from
9
+ Open Library, Wikidata and national libraries. No API key, no sign-up.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ pip install bookinfo
15
+ ```
16
+
17
+ Requires Python 3.9+. The only dependency is [httpx](https://www.python-httpx.org)
18
+ (plus `typing_extensions` on Python older than 3.11).
19
+
20
+ ## Usage
21
+
22
+ ```python
23
+ import bookinfo
24
+
25
+ print(bookinfo.isbn("978-0-7475-3269-9").book.title)
26
+ print(bookinfo.search("dune", tag="fantasy").results[0].title)
27
+ ```
28
+
29
+ Every endpoint is available as a module-level function that shares one connection pool.
30
+ Create your own `BookInfo` for custom timeouts, retries or a different base URL:
31
+
32
+ ```python
33
+ from bookinfo import BookInfo
34
+
35
+ with BookInfo(timeout=30) as books:
36
+ hits = books.search("foundation", year_to=1960, limit=5)
37
+ print([book.title for book in hits.results])
38
+
39
+ book = books.work(82563)
40
+ print(book.title, book.series.name, book.tags)
41
+
42
+ print(books.recommend([82563, 27482]).results)
43
+ ```
44
+
45
+ Every method returns a frozen dataclass from `bookinfo.models` (`SearchPage`, `Work`,
46
+ `Author`, `Series`, ...) with attribute access and full type hints.
47
+
48
+ Options are typed keyword arguments that differ per endpoint (`SearchOptions`,
49
+ `CatalogueOptions`, ...): `language`, `author`, `tag`, `year_from`, `year_to`, `cover`,
50
+ `sort`, `page` and `limit`.
51
+
52
+ | Method | Endpoint |
53
+ | --- | --- |
54
+ | `search(q, **options)` | `/search` |
55
+ | `suggest(q)` | `/suggest` |
56
+ | `work(work_id)` / `works(work_ids)` | `/works/{id}` / `/works?ids=` |
57
+ | `isbn(isbn)` / `isbns(isbns)` | `/isbn/{isbn}` / `/isbn?isbns=` |
58
+ | `check_isbn(isbn)` | `/isbn/{isbn}/check` |
59
+ | `search_series(q)` / `series(series_id)` | `/series` / `/series/{id}` |
60
+ | `search_authors(q)` / `author(author_id)` | `/authors` / `/authors/{id}` |
61
+ | `author_works(author_id, sort="year")` | `/authors/{id}/works` |
62
+ | `similar(work_id)` / `recommend(work_ids)` | `/similar/{id}` / `/recommend` |
63
+ | `random(**options)` | `/random` |
64
+ | `catalogue(language, /, **options)` | `/catalogue/{language}` |
65
+ | `tags()` / `languages()` | `/tags` / `/languages` |
66
+ | `cover_url(work_id, language, width)` | `/b/{id}/{language}/{width}.avif` |
67
+ | `photo_url(author_id, width)` | `/a/{id}/{width}.avif` |
68
+
69
+ ### Paging
70
+
71
+ `paginate` walks every page of a list endpoint and yields the results one by one:
72
+
73
+ ```python
74
+ for book in books.paginate(books.author_works, 23919, sort="year"):
75
+ print(book.year, book.title)
76
+ ```
77
+
78
+ ### Errors and rate limits
79
+
80
+ Failed requests raise `BookInfoError` with `status`, `code` (`invalid_parameter`,
81
+ `not_found`, `rate_limited`, `unavailable`, and `network_error` or `invalid_response` when
82
+ no usable answer arrived; `status` is 0 without a response) and `message`. Rate limited (429) and
83
+ temporarily unavailable (502, 503, 504) answers are retried, honouring `Retry-After`; tune it with
84
+ `BookInfo(retries=2, timeout=10)`. Moved work ids are followed automatically.
85
+
86
+ ## Example
87
+
88
+ [examples/flask_app](examples/flask_app) is a small book browser built with Flask: search
89
+ with filters, book pages with series navigation, editions and similar books, authors,
90
+ series, ISBN lookup and a random book.
91
+
92
+ ```sh
93
+ uv run --with flask flask --app examples/flask_app/app run
94
+ ```
95
+
96
+ ## Development
97
+
98
+ ```sh
99
+ uv run pytest
100
+ ```
101
+
102
+ Releases are published to PyPI from GitHub Actions through
103
+ [trusted publishing](https://docs.pypi.org/trusted-publishers/): create a GitHub release
104
+ and the `publish.yml` workflow does the rest.
105
+
106
+ ## License
107
+
108
+ [MIT](LICENSE)
@@ -0,0 +1,49 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "bookinfo"
7
+ version = "0.1.0"
8
+ description = "Python client for the free shlf.bid book API: books, authors, series, ISBNs and covers"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ dependencies = [
14
+ "httpx>=0.27",
15
+ "typing_extensions>=4.4; python_version < '3.11'",
16
+ ]
17
+ keywords = ["books", "isbn", "openlibrary", "api-client", "shlf"]
18
+ classifiers = [
19
+ "Development Status :: 4 - Beta",
20
+ "Intended Audience :: Developers",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Programming Language :: Python :: 3.14",
29
+ "Topic :: Software Development :: Libraries",
30
+ "Typing :: Typed",
31
+ ]
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/tn3w/bookinfo"
35
+ Source = "https://github.com/tn3w/bookinfo"
36
+ Issues = "https://github.com/tn3w/bookinfo/issues"
37
+ API = "https://shlf.bid/openapi.json"
38
+
39
+ [dependency-groups]
40
+ dev = ["pytest>=8", "ruff"]
41
+
42
+ [tool.hatch.build.targets.sdist]
43
+ include = ["src", "tests", "README.md", "LICENSE"]
44
+
45
+ [tool.ruff]
46
+ line-length = 90
47
+
48
+ [tool.ruff.lint]
49
+ select = ["E", "F", "I", "UP", "B"]
@@ -0,0 +1,265 @@
1
+ import sys
2
+ from collections.abc import Callable, Iterable, Iterator
3
+ from time import sleep
4
+ from typing import Any, Literal, Optional, TypedDict, TypeVar
5
+ from urllib.parse import quote
6
+
7
+ import httpx
8
+
9
+ from bookinfo.models import (
10
+ Author,
11
+ AuthorHits,
12
+ AuthorWorksPage,
13
+ CataloguePage,
14
+ IsbnCheck,
15
+ IsbnMatch,
16
+ IsbnMatches,
17
+ Languages,
18
+ Page,
19
+ Recommendations,
20
+ SearchPage,
21
+ Series,
22
+ SeriesHits,
23
+ Similar,
24
+ Suggestions,
25
+ Tags,
26
+ Work,
27
+ Works,
28
+ WorkSummary,
29
+ build,
30
+ )
31
+
32
+ if sys.version_info >= (3, 11):
33
+ from typing import Self, Unpack
34
+ else:
35
+ from typing_extensions import Self, Unpack
36
+
37
+ BASE_URL = "https://shlf.bid"
38
+ RETRY_STATUSES = {429, 502, 503, 504}
39
+ MAX_PAGE = 50
40
+ MAX_RETRY_DELAY = 30
41
+
42
+ T = TypeVar("T")
43
+
44
+
45
+ class InLanguage(TypedDict, total=False):
46
+ language: str
47
+
48
+
49
+ class Limit(TypedDict, total=False):
50
+ limit: int
51
+
52
+
53
+ class Paging(Limit):
54
+ page: int
55
+
56
+
57
+ class Filters(TypedDict, total=False):
58
+ author: int
59
+ tag: str
60
+ year_from: int
61
+ year_to: int
62
+ cover: bool
63
+
64
+
65
+ class SearchOptions(InLanguage, Filters, Paging):
66
+ pass
67
+
68
+
69
+ class RandomOptions(InLanguage, Filters):
70
+ pass
71
+
72
+
73
+ class CatalogueOptions(Filters, Paging):
74
+ pass
75
+
76
+
77
+ class SimilarOptions(InLanguage, Limit):
78
+ pass
79
+
80
+
81
+ class AuthorWorksOptions(InLanguage, Paging):
82
+ sort: Literal["popular", "year", "newest", "title"]
83
+
84
+
85
+ class BookInfoError(Exception):
86
+ def __init__(self, status: int, code: str, message: str):
87
+ super().__init__(f"{code}: {message}")
88
+ self.status = status
89
+ self.code = code
90
+ self.message = message
91
+
92
+
93
+ def join(values: Iterable[Any]) -> str:
94
+ return ",".join(map(str, values))
95
+
96
+
97
+ def to_error(response: httpx.Response) -> BookInfoError:
98
+ try:
99
+ error = response.json()["error"]
100
+ return BookInfoError(response.status_code, error["code"], error["message"])
101
+ except (ValueError, KeyError, TypeError):
102
+ return BookInfoError(response.status_code, "http_error", response.reason_phrase)
103
+
104
+
105
+ def retry_delay(response: httpx.Response, attempt: int) -> float:
106
+ try:
107
+ delay = float(response.headers["Retry-After"])
108
+ except (KeyError, ValueError):
109
+ delay = 2**attempt
110
+ return min(delay, MAX_RETRY_DELAY)
111
+
112
+
113
+ class BookInfo:
114
+ def __init__(
115
+ self,
116
+ base_url: str = BASE_URL,
117
+ *,
118
+ timeout: float = 10,
119
+ retries: int = 2,
120
+ transport: Optional[httpx.BaseTransport] = None,
121
+ ):
122
+ self.base_url = base_url.rstrip("/")
123
+ self.retries = retries
124
+ self.http = httpx.Client(
125
+ base_url=f"{self.base_url}/api/v1",
126
+ timeout=timeout,
127
+ follow_redirects=True,
128
+ transport=transport,
129
+ )
130
+
131
+ def __enter__(self) -> Self:
132
+ return self
133
+
134
+ def __exit__(self, *exception: object) -> None:
135
+ self.close()
136
+
137
+ def close(self) -> None:
138
+ self.http.close()
139
+
140
+ def send(self, path: str, params: dict[str, Any]) -> httpx.Response:
141
+ try:
142
+ return self.http.get(path, params=params)
143
+ except httpx.RequestError as error:
144
+ raise BookInfoError(0, "network_error", str(error) or repr(error)) from error
145
+
146
+ def get(self, model: type[T], path: str, **params: Any) -> T:
147
+ response = self.send(path, params)
148
+ for attempt in range(self.retries):
149
+ if response.status_code not in RETRY_STATUSES:
150
+ break
151
+ sleep(retry_delay(response, attempt))
152
+ response = self.send(path, params)
153
+ if response.is_error:
154
+ raise to_error(response)
155
+ try:
156
+ return build(model, response.json())
157
+ except ValueError as error:
158
+ raise BookInfoError(
159
+ response.status_code, "invalid_response", str(error)
160
+ ) from error
161
+
162
+ def search(self, q: str, **options: Unpack[SearchOptions]) -> SearchPage:
163
+ return self.get(SearchPage, "/search", q=q, **options)
164
+
165
+ def suggest(self, q: str) -> Suggestions:
166
+ return self.get(Suggestions, "/suggest", q=q)
167
+
168
+ def work(self, work_id: int, **options: Unpack[InLanguage]) -> Work:
169
+ return self.get(Work, f"/works/{work_id}", **options)
170
+
171
+ def works(self, work_ids: Iterable[int], **options: Unpack[InLanguage]) -> Works:
172
+ return self.get(Works, "/works", ids=join(work_ids), **options)
173
+
174
+ def isbn(self, isbn: str) -> IsbnMatch:
175
+ return self.get(IsbnMatch, f"/isbn/{quote(isbn, safe='')}")
176
+
177
+ def isbns(self, isbns: Iterable[str]) -> IsbnMatches:
178
+ return self.get(IsbnMatches, "/isbn", isbns=join(isbns))
179
+
180
+ def check_isbn(self, isbn: str) -> IsbnCheck:
181
+ return self.get(IsbnCheck, f"/isbn/{quote(isbn, safe='')}/check")
182
+
183
+ def search_series(self, q: str, **options: Unpack[Limit]) -> SeriesHits:
184
+ return self.get(SeriesHits, "/series", q=q, **options)
185
+
186
+ def series(self, series_id: int, **options: Unpack[InLanguage]) -> Series:
187
+ return self.get(Series, f"/series/{series_id}", **options)
188
+
189
+ def search_authors(self, q: str, **options: Unpack[Limit]) -> AuthorHits:
190
+ return self.get(AuthorHits, "/authors", q=q, **options)
191
+
192
+ def author(self, author_id: int, **options: Unpack[InLanguage]) -> Author:
193
+ return self.get(Author, f"/authors/{author_id}", **options)
194
+
195
+ def author_works(
196
+ self, author_id: int, **options: Unpack[AuthorWorksOptions]
197
+ ) -> AuthorWorksPage:
198
+ return self.get(AuthorWorksPage, f"/authors/{author_id}/works", **options)
199
+
200
+ def similar(self, work_id: int, **options: Unpack[SimilarOptions]) -> Similar:
201
+ return self.get(Similar, f"/similar/{work_id}", **options)
202
+
203
+ def recommend(
204
+ self, work_ids: Iterable[int], **options: Unpack[SimilarOptions]
205
+ ) -> Recommendations:
206
+ return self.get(Recommendations, "/recommend", ids=join(work_ids), **options)
207
+
208
+ def random(self, **options: Unpack[RandomOptions]) -> WorkSummary:
209
+ return self.get(WorkSummary, "/random", **options)
210
+
211
+ def catalogue(
212
+ self, language: str, **options: Unpack[CatalogueOptions]
213
+ ) -> CataloguePage:
214
+ return self.get(
215
+ CataloguePage, f"/catalogue/{quote(language, safe='')}", **options
216
+ )
217
+
218
+ def tags(self, **options: Unpack[InLanguage]) -> Tags:
219
+ return self.get(Tags, "/tags", **options)
220
+
221
+ def languages(self) -> Languages:
222
+ return self.get(Languages, "/languages")
223
+
224
+ def paginate(
225
+ self, method: Callable[..., Page], *args: Any, **options: Any
226
+ ) -> Iterator[WorkSummary]:
227
+ page = options.pop("page", 1)
228
+ while True:
229
+ data = method(*args, page=page, **options)
230
+ yield from data.results
231
+ if not data.more or page == MAX_PAGE:
232
+ return
233
+ page += 1
234
+
235
+ def cover_url(
236
+ self, work_id: int, language: str, width: Literal[160, 320, 640] = 320
237
+ ) -> str:
238
+ return f"{self.base_url}/b/{work_id}/{language}/{width}.avif"
239
+
240
+ def photo_url(self, author_id: int, width: Literal[96, 192] = 192) -> str:
241
+ return f"{self.base_url}/a/{author_id}/{width}.avif"
242
+
243
+
244
+ default_client = BookInfo()
245
+ search = default_client.search
246
+ suggest = default_client.suggest
247
+ work = default_client.work
248
+ works = default_client.works
249
+ isbn = default_client.isbn
250
+ isbns = default_client.isbns
251
+ check_isbn = default_client.check_isbn
252
+ search_series = default_client.search_series
253
+ series = default_client.series
254
+ search_authors = default_client.search_authors
255
+ author = default_client.author
256
+ author_works = default_client.author_works
257
+ similar = default_client.similar
258
+ recommend = default_client.recommend
259
+ random = default_client.random
260
+ catalogue = default_client.catalogue
261
+ tags = default_client.tags
262
+ languages = default_client.languages
263
+ paginate = default_client.paginate
264
+ cover_url = default_client.cover_url
265
+ photo_url = default_client.photo_url
@@ -0,0 +1,307 @@
1
+ from dataclasses import dataclass, fields, is_dataclass
2
+ from typing import Any, Literal, Optional, TypeVar, Union, get_args, get_origin
3
+
4
+ T = TypeVar("T")
5
+ model = dataclass(frozen=True)
6
+
7
+
8
+ @model
9
+ class AuthorReference:
10
+ id: int
11
+ name: str
12
+
13
+
14
+ @model
15
+ class WorkSummary:
16
+ id: int
17
+ language: str
18
+ title: str
19
+ authors: list[AuthorReference]
20
+ url: str
21
+ subtitle: Optional[str]
22
+ year: Optional[int]
23
+ cover: Optional[str]
24
+ covers: Optional[dict[str, str]]
25
+
26
+
27
+ @model
28
+ class Tag:
29
+ slug: str
30
+ label: str
31
+
32
+
33
+ @model
34
+ class TagCount(Tag):
35
+ category: str
36
+ works: int
37
+
38
+
39
+ @model
40
+ class WorkSeries:
41
+ id: int
42
+ name: str
43
+ position: Optional[int]
44
+ previous: Optional[int]
45
+ next: Optional[int]
46
+
47
+
48
+ @model
49
+ class Stats:
50
+ readers: Optional[int]
51
+ ratings: Optional[int]
52
+ rating: Optional[float]
53
+ editions: Optional[int]
54
+
55
+
56
+ @model
57
+ class Edition:
58
+ isbn: Optional[str]
59
+ year: Optional[int]
60
+ publisher: Optional[str]
61
+ format: Optional[int]
62
+ cover: Optional[int]
63
+ language: Optional[str]
64
+ price: Optional[str]
65
+
66
+
67
+ @model
68
+ class LanguageTitle:
69
+ language: str
70
+ title: str
71
+ url: str
72
+
73
+
74
+ @model
75
+ class Text:
76
+ language: str
77
+ text: str
78
+
79
+
80
+ @model
81
+ class Contributor:
82
+ role: str
83
+ name: str
84
+
85
+
86
+ @model
87
+ class Link:
88
+ label: str
89
+ url: str
90
+
91
+
92
+ @model
93
+ class Award:
94
+ name: str
95
+ result: str
96
+ year: Optional[int]
97
+
98
+
99
+ @model
100
+ class Work(WorkSummary):
101
+ languages: list[LanguageTitle]
102
+ translated: Optional[bool]
103
+ description: Optional[Text]
104
+ descriptions: Optional[list[Text]]
105
+ titles: Optional[list[Text]]
106
+ original_title: Optional[str]
107
+ original_language: Optional[str]
108
+ first_published: Optional[Union[int, str]]
109
+ tags: Optional[list[Tag]]
110
+ series: Optional[WorkSeries]
111
+ stats: Optional[Stats]
112
+ translators: Optional[list[str]]
113
+ contributors: Optional[list[Contributor]]
114
+ identifiers: Optional[list[str]]
115
+ editions: Optional[list[Edition]]
116
+ settings: Optional[list[str]]
117
+ characters: Optional[list[str]]
118
+ awards: Optional[list[Award]]
119
+ links: Optional[list[Link]]
120
+
121
+
122
+ @model
123
+ class Page:
124
+ page: int
125
+ limit: int
126
+ more: bool
127
+ results: list[WorkSummary]
128
+
129
+
130
+ @model
131
+ class SearchPage(Page):
132
+ query: Optional[str]
133
+
134
+
135
+ @model
136
+ class CataloguePage(Page):
137
+ language: str
138
+ total: int
139
+
140
+
141
+ @model
142
+ class AuthorWorksPage(Page):
143
+ author: int
144
+ sort: str
145
+ total: int
146
+
147
+
148
+ @model
149
+ class Suggestion:
150
+ kind: Literal["author", "work"]
151
+ id: int
152
+ label: str
153
+ detail: str
154
+ language: Optional[str]
155
+
156
+
157
+ @model
158
+ class Suggestions:
159
+ query: Optional[str]
160
+ suggestions: list[Suggestion]
161
+
162
+
163
+ @model
164
+ class Works:
165
+ results: list[WorkSummary]
166
+ missing: Optional[list[int]]
167
+
168
+
169
+ @model
170
+ class Similar:
171
+ work: int
172
+ results: list[WorkSummary]
173
+
174
+
175
+ @model
176
+ class Recommendations:
177
+ seeds: list[int]
178
+ results: list[WorkSummary]
179
+
180
+
181
+ @model
182
+ class IsbnMatch:
183
+ isbn: str
184
+ isbn10: Optional[str]
185
+ work: int
186
+ language: str
187
+ book: WorkSummary
188
+
189
+
190
+ @model
191
+ class IsbnMatches:
192
+ results: list[IsbnMatch]
193
+ missing: Optional[list[str]]
194
+ invalid: Optional[list[str]]
195
+
196
+
197
+ @model
198
+ class IsbnCheck:
199
+ input: Optional[str]
200
+ valid: bool
201
+ isbn13: Optional[str]
202
+ isbn10: Optional[str]
203
+
204
+
205
+ @model
206
+ class SeriesHit:
207
+ id: int
208
+ name: str
209
+ language: str
210
+ volumes: int
211
+ url: str
212
+
213
+
214
+ @model
215
+ class SeriesHits:
216
+ query: Optional[str]
217
+ results: list[SeriesHit]
218
+
219
+
220
+ @model
221
+ class SeriesVolume(WorkSummary):
222
+ work: int
223
+ position: int
224
+
225
+
226
+ @model
227
+ class Series:
228
+ id: int
229
+ name: str
230
+ language: str
231
+ url: str
232
+ works: list[SeriesVolume]
233
+
234
+
235
+ @model
236
+ class AuthorHit:
237
+ id: int
238
+ name: str
239
+ works: int
240
+ url: str
241
+ born: Optional[int]
242
+ photo: Optional[str]
243
+
244
+
245
+ @model
246
+ class AuthorHits:
247
+ query: Optional[str]
248
+ results: list[AuthorHit]
249
+
250
+
251
+ @model
252
+ class Author:
253
+ id: int
254
+ name: str
255
+ url: str
256
+ works: list[int]
257
+ born: Optional[int]
258
+ died: Optional[int]
259
+ birth_date: Optional[str]
260
+ death_date: Optional[str]
261
+ birthplace: Optional[str]
262
+ deathplace: Optional[str]
263
+ names: Optional[list[str]]
264
+ bio: Optional[str]
265
+ bios: Optional[list[Text]]
266
+ identifiers: Optional[list[str]]
267
+ photo: Optional[str]
268
+ photos: Optional[dict[str, str]]
269
+ nationality: Optional[list[str]]
270
+ occupations: Optional[list[str]]
271
+ education: Optional[list[str]]
272
+ influences: Optional[list[str]]
273
+ movements: Optional[list[str]]
274
+ awards: Optional[list[Award]]
275
+ links: Optional[list[Link]]
276
+
277
+
278
+ @model
279
+ class Tags:
280
+ language: str
281
+ tags: list[TagCount]
282
+
283
+
284
+ @model
285
+ class Language:
286
+ code: str
287
+ name: str
288
+ works: int
289
+ url: str
290
+
291
+
292
+ @model
293
+ class Languages:
294
+ languages: list[Language]
295
+
296
+
297
+ def build(hint: Any, value: Any) -> Any:
298
+ if value is None:
299
+ return None
300
+ if isinstance(hint, type) and is_dataclass(hint):
301
+ return hint(**{f.name: build(f.type, value.get(f.name)) for f in fields(hint)})
302
+ arguments = [argument for argument in get_args(hint) if argument is not type(None)]
303
+ if get_origin(hint) is Union and len(arguments) == 1:
304
+ return build(arguments[0], value)
305
+ if get_origin(hint) is list:
306
+ return [build(arguments[0], item) for item in value]
307
+ return value
File without changes
@@ -0,0 +1,250 @@
1
+ import os
2
+
3
+ import httpx
4
+ import pytest
5
+
6
+ import bookinfo
7
+ from bookinfo import BookInfo, BookInfoError
8
+
9
+
10
+ def make_client(handler, **options):
11
+ return BookInfo(transport=httpx.MockTransport(handler), **options)
12
+
13
+
14
+ def error_response(status, code, headers=None):
15
+ body = {"error": {"code": code, "message": "nope"}}
16
+ return httpx.Response(status, json=body, headers=headers)
17
+
18
+
19
+ @pytest.fixture(autouse=True)
20
+ def delays(monkeypatch):
21
+ recorded = []
22
+ monkeypatch.setattr(bookinfo, "sleep", recorded.append)
23
+ return recorded
24
+
25
+
26
+ @pytest.mark.parametrize(
27
+ ("call", "path", "params"),
28
+ [
29
+ (
30
+ lambda client: client.search("dune", tag="fantasy", cover=True, year_to=1960),
31
+ "/api/v1/search",
32
+ {"q": "dune", "tag": "fantasy", "cover": "true", "year_to": "1960"},
33
+ ),
34
+ (lambda client: client.works([1, 2, 3]), "/api/v1/works", {"ids": "1,2,3"}),
35
+ (
36
+ lambda client: client.recommend((4, 5), limit=3),
37
+ "/api/v1/recommend",
38
+ {"ids": "4,5", "limit": "3"},
39
+ ),
40
+ (
41
+ lambda client: client.author_works(7, sort="year"),
42
+ "/api/v1/authors/7/works",
43
+ {"sort": "year"},
44
+ ),
45
+ (
46
+ lambda client: client.catalogue("de", tag="fantasy"),
47
+ "/api/v1/catalogue/de",
48
+ {"tag": "fantasy"},
49
+ ),
50
+ (
51
+ lambda client: client.isbn("0-306/40615 2"),
52
+ "/api/v1/isbn/0-306%2F40615%202",
53
+ {},
54
+ ),
55
+ ],
56
+ )
57
+ def test_calls_build_the_documented_request(call, path, params):
58
+ requests = []
59
+
60
+ def handler(request):
61
+ requests.append(request)
62
+ return httpx.Response(200, json={})
63
+
64
+ call(make_client(handler))
65
+
66
+ assert requests[0].url.raw_path.decode().split("?")[0] == path
67
+ assert dict(requests[0].url.params) == params
68
+
69
+
70
+ @pytest.mark.parametrize(
71
+ ("response", "status", "code"),
72
+ [
73
+ (error_response(404, "not_found"), 404, "not_found"),
74
+ (httpx.Response(502, text="<html>bad gateway</html>"), 502, "http_error"),
75
+ (httpx.Response(400, json={"error": "boom"}), 400, "http_error"),
76
+ (httpx.Response(400, json={"error": {"message": "x"}}), 400, "http_error"),
77
+ ],
78
+ )
79
+ def test_failed_requests_raise_book_info_error(response, status, code):
80
+ client = make_client(lambda request: response)
81
+
82
+ with pytest.raises(BookInfoError) as raised:
83
+ client.work(1)
84
+
85
+ assert (raised.value.status, raised.value.code) == (status, code)
86
+
87
+
88
+ def test_network_failures_raise_book_info_error():
89
+ def handler(request):
90
+ raise httpx.ConnectError("connection refused")
91
+
92
+ with pytest.raises(BookInfoError) as raised:
93
+ make_client(handler).languages()
94
+
95
+ assert (raised.value.status, raised.value.code) == (0, "network_error")
96
+ assert "connection refused" in raised.value.message
97
+
98
+
99
+ def test_successful_but_malformed_answers_raise_book_info_error():
100
+ client = make_client(lambda request: httpx.Response(200, text="<html>captcha"))
101
+
102
+ with pytest.raises(BookInfoError) as raised:
103
+ client.languages()
104
+
105
+ assert (raised.value.status, raised.value.code) == (200, "invalid_response")
106
+
107
+
108
+ def test_moved_work_ids_are_followed():
109
+ def handler(request):
110
+ if request.url.path == "/api/v1/works/1":
111
+ return httpx.Response(301, headers={"Location": "/api/v1/works/9"})
112
+ return httpx.Response(200, json=work_json(9))
113
+
114
+ assert make_client(handler).work(1).id == 9
115
+
116
+
117
+ def test_rate_limit_is_retried_after_the_requested_delay(delays):
118
+ responses = [
119
+ error_response(429, "rate_limited", {"Retry-After": "3"}),
120
+ httpx.Response(200, json={"languages": []}),
121
+ ]
122
+ client = make_client(lambda request: responses.pop(0))
123
+
124
+ assert client.languages().languages == []
125
+ assert delays == [3]
126
+
127
+
128
+ def test_retries_back_off_then_give_up(delays):
129
+ calls = []
130
+
131
+ def handler(request):
132
+ calls.append(request)
133
+ return error_response(503, "unavailable")
134
+
135
+ client = make_client(handler, retries=2)
136
+
137
+ with pytest.raises(BookInfoError, match="unavailable"):
138
+ client.tags()
139
+
140
+ assert len(calls) == 3
141
+ assert delays == [1, 2]
142
+
143
+
144
+ def test_client_errors_are_not_retried(delays):
145
+ calls = []
146
+
147
+ def handler(request):
148
+ calls.append(request)
149
+ return error_response(400, "invalid_parameter")
150
+
151
+ with pytest.raises(BookInfoError):
152
+ make_client(handler).search("x", limit=99)
153
+
154
+ assert len(calls) == 1
155
+ assert delays == []
156
+
157
+
158
+ def test_paginate_yields_results_until_no_more_pages():
159
+ def handler(request):
160
+ page = int(request.url.params["page"])
161
+ results = [work_json(page)]
162
+ return httpx.Response(200, json=page_json(results, more=page < 3))
163
+
164
+ client = make_client(handler)
165
+
166
+ assert [work.id for work in client.paginate(client.search, "dune")] == [1, 2, 3]
167
+
168
+
169
+ def work_json(work_id):
170
+ return {"id": work_id, "language": "en", "title": "Dune", "url": "u", "authors": []}
171
+
172
+
173
+ def page_json(results, more=False):
174
+ return {"query": "dune", "page": 1, "limit": 20, "more": more, "results": results}
175
+
176
+
177
+ def test_omitted_fields_are_none_at_every_level():
178
+ body = {
179
+ **work_json(5),
180
+ "languages": [],
181
+ "series": {"id": 5, "name": "Dune", "next": 6},
182
+ "editions": [{"isbn": "9780441172719"}],
183
+ "description": {"language": "en", "text": "Spice."},
184
+ }
185
+ work = make_client(lambda request: httpx.Response(200, json=body)).work(5)
186
+
187
+ assert work.year is None and work.cover is None and work.awards is None
188
+ assert work.series.previous is None and work.series.next == 6
189
+ assert work.editions[0].isbn == "9780441172719"
190
+ assert work.editions[0].price is None
191
+ assert work.description.text == "Spice."
192
+ assert work.first_published is None
193
+
194
+
195
+ def test_unknown_response_fields_are_ignored():
196
+ body = page_json([{**work_json(1), "surprise": True}])
197
+
198
+ page = make_client(lambda request: httpx.Response(200, json=body)).search("dune")
199
+
200
+ assert page.results[0].id == 1
201
+
202
+
203
+ def test_paginate_stops_at_the_last_page_the_api_allows():
204
+ pages = []
205
+
206
+ def handler(request):
207
+ pages.append(int(request.url.params["page"]))
208
+ return httpx.Response(200, json=page_json([work_json(1)], more=True))
209
+
210
+ client = make_client(handler)
211
+
212
+ assert len(list(client.paginate(client.search, "dune"))) == bookinfo.MAX_PAGE
213
+ assert pages[-1] == bookinfo.MAX_PAGE
214
+
215
+
216
+ def test_every_method_has_a_module_level_function():
217
+ methods = {
218
+ name
219
+ for name, value in vars(BookInfo).items()
220
+ if callable(value)
221
+ and name not in {"get", "send", "close"}
222
+ and not name.startswith("_")
223
+ }
224
+
225
+ assert all(callable(getattr(bookinfo, name)) for name in methods)
226
+
227
+
228
+ def test_module_functions_share_the_default_client(monkeypatch):
229
+ paths = []
230
+
231
+ def handler(request):
232
+ paths.append(request.url.path)
233
+ return httpx.Response(200, json={"input": "x", "valid": True})
234
+
235
+ monkeypatch.setattr(bookinfo.default_client, "http", make_client(handler).http)
236
+
237
+ assert bookinfo.check_isbn("0-306-40615-2").valid
238
+ assert paths == ["/api/v1/isbn/0-306-40615-2/check"]
239
+
240
+
241
+ @pytest.mark.skipif(not os.environ.get("BOOKINFO_LIVE"), reason="set BOOKINFO_LIVE=1")
242
+ def test_live_api_matches_the_models():
243
+ with BookInfo() as books:
244
+ match = books.isbn("978-0-7475-3269-9")
245
+ work = books.work(match.work)
246
+ series = books.series(work.series.id)
247
+
248
+ assert work.title == match.book.title
249
+ assert work.authors[0].name == "J. K. Rowling"
250
+ assert [volume.position for volume in series.works][:2] == [1, 2]