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
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']
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.
Thumbnails captured like this: