How to return a search result with multiple books using the Google Books API?

1.1k views Asked by At

I'm consuming a Google Books API and I'm trying to return a search result with multiple books. Here's what I'm doing:

def lookup(search):
    """Look up search for books."""
    # Contact API
    try:
        url = f'https://www.googleapis.com/books/v1/volumes?q={search}&key=myAPIKey'
        response = requests.get(url)
        response.raise_for_status()
    except requests.RequestException:
        return None

    # Parse response
    try:
        search = response.json()
        return {
            "totalItems": int(search["totalItems"]),
            "title": search["items"][0]['volumeInfo']['title'],
            "authors": search["items"][0]['volumeInfo']['authors'],
        }
    except (KeyError, TypeError, ValueError):
        return None

Real example

Of course, this only returns one result. However, if I try to call it this way:

"title": search["items"]['volumeInfo']['title']

It doesn't return anything.

Example of JSON to be consumed.

How do I receive all results?


Another 'problem' that I've been facing is how to get a thumbnail of that same JSON, because apparently it doesn't work:

"thumbnail": search["items"][1]['volumeInfo']['imageLinks']['thumbnail']
1

There are 1 answers

0
Jonathan Leon On BEST ANSWER

You need to iterate through the response get the values. You can change your try: to the following and this will give lists of titles and authors. If you want something different you can adapt it.

try:
    search = response.json()
    titles = []
    authors = []
    for itm in search['items']:
        titles.append(itm['volumeInfo']['title'])
        authors.append(itm['volumeInfo']['authors'])

    return {
        "totalItems": int(search["totalItems"]),
        "title": titles,
        "authors": authors,
    }

Thumbnails captured like this:

thumbnails = []
for itm in search['items']:
    thumbnails.append(itm['volumeInfo']['imageLinks']['thumbnail'])