Build a Book Search App with The Books API (Step-by-Step)

A hands-on tutorial: search books by title and author, look up editions by ISBN, show covers, enrich a list with batch lookups, and handle errors and rate limits, with JavaScript and Python examples.

By The Books API TeamPublished 8 min read

A search box, a list of results with covers, and a detail page for each book: it is one of the most common features in reading apps, bookshop systems, classroom libraries and internal tools. It is also deceptively hard to build from scratch, because you need a large, clean catalogue behind it.

In this tutorial we'll build that feature on top of The Books API. You'll learn how to authenticate, search by keyword, title and author, fetch a full edition by ISBN, display cover images, enrich a list of ISBNs in one request, and deal with errors and rate limits. Examples are in JavaScript (browser and Node.js) and Python.

What we're building

By the end you'll have:

  1. A search form that queries books by free text, or by title and author.
  2. A results list showing cover, title, authors, publisher and year.
  3. A detail view loaded by ISBN.
  4. A small script that enriches a CSV of ISBNs.

Step 1: Get an API key

Every request to the /v1 endpoints (except public cover images) needs an API key. Start a free trial to get one, then keep it out of your source code. In the examples we read it from an environment variable:

export BOOKS_API_KEY="your-key-here"

Send the key in the X-API-Key header:

curl "https://api.thebooksapi.com/v1/books/9780306406157" \
  -H "X-API-Key: $BOOKS_API_KEY"

Security tip: an API key is a secret. Don't embed it in a public web page or a mobile app bundle. Call the API from your server (or a serverless function) and let your front end talk to your server.

Step 2: Understand the endpoints

These are the endpoints you'll use most for a search app:

MethodPathPurpose
GET/v1/searchSearch editions by q, title, author, with filters
GET/v1/books/{isbn}Full edition record by ISBN-10 or ISBN-13
POST/v1/books/batchUp to 100 ISBNs in one request
GET/v1/authors/{id}Author details
GET/v1/authors/{id}/worksWorks by an author
GET/v1/covers/...Public cover images (no key needed)

The base URL is https://api.thebooksapi.com.

Step 3: Search for books

The search endpoint accepts at least one of these parameters:

ParameterMeaning
qFree-text query (title, author, ISBN…)
titleTitle only
authorAuthor only
langLanguage filter, e.g. en, es
publisherPublisher filter
has_covertrue to only return results with a cover
limitResults per page (default 20, capped by your plan)
offsetSkip this many results for pagination

Each text parameter is limited to 200 characters. A typical request:

curl "https://api.thebooksapi.com/v1/search?title=dune&author=herbert&lang=en&limit=10" \
  -H "X-API-Key: $BOOKS_API_KEY"

The response contains a results array and pagination fields:

{
  "results": [
    {
      "id": "…",
      "isbn13": "…",
      "title": "Dune",
      "subtitle": null,
      "authors": ["Frank Herbert"],
      "publisher": "…",
      "publication_year": 1965,
      "language": "en",
      "cover_url": "https://api.thebooksapi.com/v1/covers/…-M.jpg",
      "attribution": "…",
      "position": 1
    }
  ],
  "total": 42,
  "total_is_approximate": true,
  "page": 1,
  "limit": 10,
  "offset": 0,
  "query": "dune herbert"
}

(Values marked "…" vary; always read the real response rather than hard-coding fields.)

A minimal server-side search in Node.js

// server/search.js — Node 18+ (global fetch)
const API = "https://api.thebooksapi.com/v1";

export async function searchBooks({ q, title, author, lang, limit = 20, offset = 0 }) {
  const params = new URLSearchParams();
  if (q) params.set("q", q);
  if (title) params.set("title", title);
  if (author) params.set("author", author);
  if (lang) params.set("lang", lang);
  params.set("limit", String(limit));
  params.set("offset", String(offset));

  const res = await fetch(`${API}/search?${params}`, {
    headers: { "X-API-Key": process.env.BOOKS_API_KEY },
  });
  if (!res.ok) {
    const body = await res.json().catch(() => ({}));
    throw new Error(`Search failed (${res.status}): ${body.error ?? res.statusText}`);
  }
  return res.json();
}

Expose it through your own route (for example /api/search) and call that from the browser.

Rendering results

function renderResults(container, data) {
  container.replaceChildren(
    ...data.results.map((book) => {
      const li = document.createElement("li");
      li.className = "book";
      const img = document.createElement("img");
      img.src = book.cover_url ?? "/placeholder-cover.svg";
      img.alt = "";
      img.loading = "lazy";
      const title = document.createElement("a");
      title.href = `/books/${book.isbn13}`;
      title.textContent = book.title;
      const meta = document.createElement("p");
      meta.textContent = [book.authors?.join(", "), book.publisher, book.publication_year]
        .filter(Boolean).join(" · ");
      li.append(img, title, meta);
      return li;
    }),
  );
}

We build DOM nodes with textContent instead of concatenating HTML strings. Book titles can contain characters such as < and &, and this keeps you safe from injection.

Pagination

Use limit and offset. For page n (1-based) with 20 results per page, offset = (n - 1) * 20. The response's total tells you roughly how many results there are; when total_is_approximate is true, show "about 42 results" rather than an exact number, and stop when a page comes back with fewer results than limit. Offsets are capped (currently at 1,000), so encourage users to refine their search instead of paging forever.

If you search while the user types, wait until they pause:

let timer;
input.addEventListener("input", () => {
  clearTimeout(timer);
  timer = setTimeout(async () => {
    const q = input.value.trim();
    if (q.length < 2) return;
    const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`);
    renderResults(list, await res.json());
  }, 300);
});

A 250–400 ms delay keeps the interface responsive while saving a lot of requests.

Step 4: Show a book's detail page

When the user clicks a result, fetch the full edition by ISBN. Both ISBN-10 and ISBN-13 are accepted, with or without hyphens; an invalid ISBN returns 400.

# Python 3 with the requests library
import os
import requests

API = "https://api.thebooksapi.com/v1"
session = requests.Session()
session.headers["X-API-Key"] = os.environ["BOOKS_API_KEY"]

def get_book(isbn: str) -> dict | None:
    res = session.get(f"{API}/books/{isbn}", timeout=10)
    if res.status_code == 404:
        return None
    res.raise_for_status()
    return res.json()

book = get_book("978-0-306-40615-7")
if book:
    print(book["title"])
    print(", ".join(c["name"] for c in book.get("contributors", [])))
    print(book.get("cover_urls", {}).get("large"))

The edition record can include, depending on what the sources provide: isbn13, isbn10, title, subtitle, language, publication_year, pages, format, series, publisher, contributors, description, cover_urls (small, medium and large), a work_id that groups editions of the same work, and license_notice when a licence notice applies to the record.

Fields are omitted when no source has a value, so write defensive code: book.get("pages") in Python or book.pages ?? null in JavaScript.

Step 5: Display covers properly

Cover URLs point to https://api.thebooksapi.com/v1/covers/… and are public: no API key is needed, so you can place them directly in an <img> tag. Pick the size that matches your layout:

  • small for dense lists,
  • medium for result cards,
  • large for a detail page.

Always set a placeholder for books without a cover, use loading="lazy" in long lists, and give the image fixed dimensions (or an aspect-ratio) so your layout does not jump. Cover requests have their own per-IP rate limit, so avoid preloading hundreds of images at once. For background on rights and attribution, read our data licences page.

Step 6: Enrich a list of ISBNs with batch lookups

If you have a spreadsheet of ISBNs, don't loop over GET /v1/books/{isbn} one by one. Send up to 100 at a time:

import csv

def batch_lookup(isbns: list[str]) -> dict:
    res = session.post(f"{API}/books/batch", json={"isbns": isbns}, timeout=30)
    res.raise_for_status()
    return res.json()["results"]

with open("inventory.csv", newline="") as f:
    isbns = [row["isbn"] for row in csv.DictReader(f)]

enriched = {}
for i in range(0, len(isbns), 100):
    enriched.update(batch_lookup(isbns[i:i + 100]))

for isbn, record in enriched.items():
    if "error" in record:
        print(isbn, "->", record["error"])   # e.g. "Invalid ISBN" or "Not found"
    else:
        print(isbn, "->", record["title"])

The results object is keyed by the ISBN you sent. Each value is either an edition record or an object with an error message, so one bad row never fails the whole batch.

Step 7: Handle errors and rate limits

StatusMeaningWhat to do
400Invalid input (bad ISBN, missing parameter, limit out of range)Fix the request; show a validation message
401 / 403Missing, invalid or inactive keyCheck the key and your plan
404No edition with that ISBNShow "not found"; offer a title search
429Rate limit or quota reachedWait and retry; respect Retry-After if present
5xxTemporary server problemRetry with exponential backoff

A small retry helper:

async function fetchWithRetry(url, options, attempts = 3) {
  for (let i = 0; i < attempts; i++) {
    const res = await fetch(url, options);
    if (res.status !== 429 && res.status < 500) return res;
    const retryAfter = Number(res.headers.get("Retry-After"));
    const delay = retryAfter > 0 ? retryAfter * 1000 : 2 ** i * 500;
    await new Promise((r) => setTimeout(r, delay));
  }
  return fetch(url, options);
}

Cache aggressively, too. Book metadata changes slowly; caching a lookup for hours or days on your server cuts latency and usage.

Step 8: Show the licence notice

Some data licences require a credit. Search hits and edition records carry an optional license_notice string when one applies; display it near the data (a small line under the book details is enough) and keep it with the record if you pass the data on. The terms that apply are on our data licences page.

Production checklist

  • API key stored on the server, never in client code.
  • Debounced search input and server-side caching.
  • Placeholder covers and lazy loading.
  • ISBN normalisation and validation before lookups (see What Is an ISBN?).
  • Graceful handling of 404, 429 and 5xx responses.
  • Attribution displayed where required.

Final thoughts

With two endpoints, search and lookup by ISBN, you can build a complete book search experience in an afternoon. Batch lookups make data enrichment straightforward, and public cover URLs keep your front end simple. When you're ready, start a free trial, grab a key, and try the examples above with your own titles.

Those two calls are written up in the API documentation, and the plan limits are on the pricing page.

Tagsapitutorialjavascriptpythonsearchisbn lookupcovers

Back to blog