Skip to content

Instantly share code, notes, and snippets.

@JnyJny
Created July 15, 2021 22:10
Show Gist options
  • Save JnyJny/07385862912e06a5a5133fac4ad4eb82 to your computer and use it in GitHub Desktop.
Save JnyJny/07385862912e06a5a5133fac4ad4eb82 to your computer and use it in GitHub Desktop.
Playing with Google Books API
#!/usr/bin/env python3
""" a quick and dirty books query thing
"""
from pprint import pprint
import requests
BASE_URL = "https://www.googleapis.com/books/v1"
VOLUMES_URL = "/".join([BASE_URL, "volumes"])
def book_ids_by_title(title: str) -> list[str]:
"""Given a book title, return a list of matching Google Books API identifiers.
:param title: str
:return: List of strings
Raises ValueError on HTTP errors.
"""
response = requests.get(VOLUMES_URL, params=[("q", title)])
if not response:
raise ValueError(f"bad response {response.text}")
payload = response.json()
book_ids = []
for item in payload["items"]:
if item["volumeInfo"]["printType"] == "BOOK":
book_ids.append(item["id"])
return book_ids
def book_by_id(book_id: str) -> dict:
"""Given a book_id, return a dictionary of information about the book.
:param book_id: str
:return: dictionary
Raises ValueError on HTTP errors.
"""
response = requests.get(f"{VOLUMES_URL}/{book_id}")
if not response:
raise ValueError(f"bad response {response.text}")
book_info = response.json()
return book_info
if __name__ == "__main__":
title = "Ender's Game"
unwanted_categories = ["film", "literary", "graphic"]
book_ids = book_ids_by_title(title)
books = []
skipped = [] # book info missing a categories key
for book_id in book_ids:
book = book_by_id(book_id)
try:
categories = " ".join(book["volumeInfo"]["categories"]).lower()
except KeyError:
# book['volumeInfo'] doesn't have a categories key so skip this book
skipped.append(book)
continue
for unwanted_category in unwanted_categories:
if unwanted_category in categories:
break
else:
# this else goes with the for statement
# it only executes if the loop finishes without a break
books.append(book)
for book in books:
print("-" * 80)
pprint(book)
for book in skipped:
print("*" * 80)
pprint(book)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment