1

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']
ARNON
  • 1,097
  • 1
  • 15
  • 33
  • Please supply the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) (MRE). We should be able to copy and paste a contiguous block of your code, execute that file, and reproduce your problem along with tracing output for the problem points. This lets us test our suggestions against your test data and desired output. Show where the intermediate results differ from what you expected. Off-site links and images of text are not acceptable; we need your question to be self-contained, in keeping with the purpose of this site. – Prune May 25 '21 at 18:53

1 Answers1

1

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'])
Jonathan Leon
  • 5,440
  • 2
  • 6
  • 14