Python: search for books on Google Books

Python: search for books on Google Books

In this tutorial we will see how to search for books on Google Books with Python.

In this tutorial we will see how to search for books on Google Books with Python.

To use the Google API you need to install the requests module. The request we will make to the API requires two parameters:

  1. q: the search term
  2. maxResults: the maximum number of results to return.

We can define a function that, taking these two parameters as arguments, makes a GET request to the Google API and returns the result in JSON or an empty list in case of error.

import requests


def search_for_books(search_term, max_results = 3):
    if not search_term:
        return []
    if not isinstance(max_results, int):
        max_results = 3
    API_ENDPOINT = 'https://www.googleapis.com/books/v1/volumes'
    params = {'q': search_term, 'maxResults': max_results}
    try:
        res = requests.get(API_ENDPOINT, params=params)
        return res.json()
    except requests.exceptions.RequestException:
        return []

Usage example:

def main():
    print(search_for_books('on the road'))


if __name__ == '__main__':
    main()