Python: usare le API di Google Books per cercare libri

Python: usare le API di Google Books per cercare libri

In questo articolo vedremo come effettuare la ricerca di libri su Google Books con Python.

Per utilizzare le API di Google è necessario installare il modulo requests. La richiesta che effettueremo alle API richiede due parametri:

  1. q: il termine di ricerca
  2. maxResults: il numero massimo di risultati da restituire.

Possiamo definire una funzione che, presi questi due parametri come argomenti, effettui una richiesta GET alle API di Google e ne restituisca il risultato in JSON o una lista vuota in caso di errore.

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 []

Esempio d'uso:

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


if __name__ == '__main__':
    main()
Torna su