Look up a book by ISBN in Python

This tutorial builds a command-line script that takes an ISBN and prints the book's title, authors, ISBN-10 and ISBN-13, page count, cover image URL and description. It uses the requests library and two Big Book API calls, converts ISBN-10s to ISBN-13s on the way, and handles the errors you will meet in practice: no match, a used-up free quota and the rate limit.

What you need

Install requests and put the key in an environment variable. The script reads it from there, so the key never appears in your code. The terms require you to keep it confidential, which includes not committing it to a repository.

python3 -m pip install requests
export BIG_BOOK_API_KEY="your-api-key"

On Windows PowerShell, set the variable with $env:BIG_BOOK_API_KEY = "your-api-key".

How the lookup works

Big Book API finds books by ISBN through the isbn filter of /search-books, which accepts ISBN-13s only. The search result has the book's ID, title, cover and authors; the full record with identifiers, page count and description comes from GET /{id}. So the script:

  1. turns the input into an ISBN-13, converting an ISBN-10 if needed;
  2. calls /search-books?isbn=... and takes the ID from books[0][0]["id"];
  3. calls /{id} and prints the fields.

books is a list of lists; with group-results=true, each inner list holds the editions of one book. A search response has this shape (illustrative values, shortened):

{
    "available": 1,
    "number": 1,
    "offset": 0,
    "books": [
        [
            {
                "id": 16384516,
                "title": "Harry Potter and the Goblet of Fire",
                "image": "https://covers.openlibrary.org/b/id/12775900-M.jpg",
                "authors": [{"id": 14136020, "name": "J. K. Rowling"}],
                "rating": {"average": 0.912}
            }
        ]
    ]
}

The blocks in steps 1 to 6 make up the complete script. Put them in one file, isbn_lookup.py, in this order.

Step 1: imports and settings

"""Look up a book by ISBN with Big Book API.

Usage:
    export BIG_BOOK_API_KEY="your-key"
    python isbn_lookup.py 9780439139595
"""
import os
import sys
import time

import requests

API_BASE = "https://api.bigbookapi.com"


class QuotaUsedUp(Exception):
    """HTTP 402: the free plan's daily quota is used up."""

QuotaUsedUp is a named exception for HTTP 402, so the entry point can print a clear message instead of a stack trace.

Step 2: normalize the ISBN

People paste ISBNs with hyphens, spaces and in both formats. An ISBN-10 becomes an ISBN-13 by putting 978 in front of its first nine digits and computing a new check digit: multiply the 12 digits alternately by 1 and 3, add them up, and take (10 - sum % 10) % 10. The old ISBN-10 check digit is dropped, but it is still worth verifying first, because it catches typos.

def isbn13_check_digit(first12):
    """Check digit for the first 12 digits of an ISBN-13 (weights 1, 3, 1, 3, ...)."""
    total = sum(int(d) * (1 if i % 2 == 0 else 3) for i, d in enumerate(first12))
    return str((10 - total % 10) % 10)


def isbn10_to_isbn13(isbn10):
    """Convert an ISBN-10 such as 0439139597 to its ISBN-13, 9780439139595."""
    digits = isbn10.replace("-", "").replace(" ", "").upper()
    if len(digits) != 10 or not digits[:9].isdigit() or digits[9] not in "0123456789X":
        raise ValueError(f"not an ISBN-10: {isbn10}")
    # Catch typos with the ISBN-10 check digit: weights 10 down to 1, X counts as 10,
    # and the weighted sum must be divisible by 11.
    total = sum((10 - i) * (10 if c == "X" else int(c)) for i, c in enumerate(digits))
    if total % 11 != 0:
        raise ValueError(f"wrong ISBN-10 check digit: {isbn10}")
    # The ISBN-10 check digit is dropped; the ISBN-13 gets a new one.
    first12 = "978" + digits[:9]
    return first12 + isbn13_check_digit(first12)


def normalize_isbn(isbn):
    """Return the ISBN-13 for an ISBN-10 or ISBN-13, without hyphens or spaces."""
    digits = isbn.replace("-", "").replace(" ", "")
    if len(digits) == 10:
        return isbn10_to_isbn13(digits)
    if len(digits) == 13 and digits.isdigit():
        if digits[12] != isbn13_check_digit(digits[:12]):
            raise ValueError(f"wrong ISBN-13 check digit: {isbn}")
        return digits
    raise ValueError(f"not an ISBN-10 or ISBN-13: {isbn}")

A quick check in the Python shell:

>>> from isbn_lookup import isbn10_to_isbn13, normalize_isbn
>>> isbn10_to_isbn13("0439139597")
'9780439139595'
>>> normalize_isbn("978-0-439-13959-5")
'9780439139595'
>>> isbn10_to_isbn13("0439139598")
Traceback (most recent call last):
  ...
ValueError: wrong ISBN-10 check digit: 0439139598

Step 3: call the API, handle 402 and 429

All requests go through one function. The key travels in the x-api-key header, which the entry point sets once on a requests.Session; an api-key query parameter works too (authentication), but a header keeps the key out of URLs and server logs.

def api_get(session, path, params=None, attempts=3):
    """GET a Big Book API path and return the JSON. Waits and retries on HTTP 429."""
    for attempt in range(1, attempts + 1):
        response = session.get(API_BASE + path, params=params, timeout=10)
        if response.status_code != 429 or attempt == attempts:
            break
        # Over your plan's per-second rate limit: wait 1 s, then 2 s, and retry.
        time.sleep(attempt)
    if response.status_code == 429:
        raise RuntimeError(f"still rate limited (HTTP 429) after {attempts} attempts")
    if response.status_code == 402:
        raise QuotaUsedUp("the free daily quota is used up; it resets at midnight UTC")
    response.raise_for_status()
    return response.json()

The status codes that need their own handling (quotas and rate limits):

Every response also carries the headers X-API-Quota-Request, X-API-Quota-Used and X-API-Quota-Left. To watch your quota, add a line such as print("quota left:", response.headers.get("X-API-Quota-Left"), file=sys.stderr) before the return.

Step 4: find the book ID

def find_book_id(session, isbn13):
    """Return the Big Book ID for an ISBN-13, or None if there is no match."""
    data = api_get(session, "/search-books", {"isbn": isbn13, "number": 1})
    books = data.get("books") or []
    # "books" is a list of lists: one inner list per book (per group of editions with group-results=true).
    return books[0][0]["id"] if books and books[0] else None

If the ISBN is not in the catalogue, the search still answers 200, with an empty books list, and the function returns None rather than failing on an index. number=1 asks for one result; an ISBN filter matches a single book anyway.

Step 5: print the record

def print_book(book, isbn13):
    identifiers = book.get("identifiers") or {}
    authors = ", ".join(author["name"] for author in book.get("authors") or [])
    pages = book.get("number_of_pages")  # a float such as 734.0
    print("Title:   ", book.get("title") or "-")
    print("Authors: ", authors or "-")
    print("ISBN-10: ", identifiers.get("isbn_10") or "-")
    # Fall back to the ISBN-13 we searched for if the record has none.
    print("ISBN-13: ", identifiers.get("isbn_13") or isbn13)
    print("Pages:   ", int(pages) if pages else "-")
    print("Cover:   ", book.get("image") or "-")
    print()
    print(book.get("description") or "No description.")

The record from /{id} has id, title, image, identifiers (open_library_id, isbn_10, isbn_13), authors, publish_date, number_of_pages, description and rating. Numbers such as the page count and publish year arrive as floats (734.0), hence the int(). Not every book has every field, so the function uses .get() throughout. The rating is an average between 0 and 1; multiply it by 5 for a star rating.

Step 6: the command-line entry point

def main():
    if len(sys.argv) != 2:
        sys.exit("usage: python isbn_lookup.py ISBN")
    api_key = os.environ.get("BIG_BOOK_API_KEY")
    if not api_key:
        sys.exit("Set the BIG_BOOK_API_KEY environment variable first.")
    try:
        isbn13 = normalize_isbn(sys.argv[1])
    except ValueError as err:
        sys.exit(str(err))

    session = requests.Session()
    session.headers["x-api-key"] = api_key

    try:
        book_id = find_book_id(session, isbn13)
        if book_id is None:
            sys.exit(f"No book found for ISBN {isbn13}.")
        print_book(api_get(session, f"/{book_id}"), isbn13)
    except QuotaUsedUp as err:
        sys.exit(f"HTTP 402: {err}.")
    except (requests.RequestException, RuntimeError) as err:
        sys.exit(f"Request failed: {err}")


if __name__ == "__main__":
    main()

The session sets the key header once and reuses the connection for both requests. Every failure ends with a one-line message and a non-zero exit code, which makes the script easy to call from shell scripts.

Run it

python3 isbn_lookup.py 0439139597
python3 isbn_lookup.py 978-0-439-13959-5

Both commands look up the same book. The script prints the title, authors, both ISBNs, the page count and the cover URL, then the description. For an ISBN that is not in the catalogue it prints No book found for ISBN ....

Where to go from here

One limit to plan for: the terms do not allow storing the data the API returns, and caching it for up to an hour needs written permission. The Big Book ID is the exception: you may store it next to the ISBN in your own records and look the book up when you need it, rather than filling a database with titles and descriptions from the API.

Frequently asked questions

Can I look up a book by ISBN-10?

Yes, after converting it. The isbn filter of /search-books takes ISBN-13s, so put 978 in front of the first nine digits of the ISBN-10 and compute a new check digit, as the isbn10_to_isbn13 function above does.

Why is books a list of lists?

That is the response format; with group-results=true, each inner list groups the editions of one book. For an ISBN lookup, books[0][0] is the match.

Why does an ISBN lookup take two requests?

The search returns the ID, title, cover, authors and rating. ISBNs, page count, publish date and description are in the full record from GET /{id}. If the search result has everything you need, skip the second call.

What happens when the free quota is used up?

The API answers with HTTP 402 until the quota resets at midnight UTC. Going over the per-second rate limit returns HTTP 429 instead; wait a moment and retry.

Can I save the results in my database?

Only the Big Book IDs of books and authors. The terms do not allow storing the other data, such as titles, covers and descriptions; caching it for up to an hour is possible with written permission.

Get a free API key and run the script: 50 requests a day.

Get a free API key Read the docs