Search Books with Goodreads API and Google Apps Script

S
Published in: Amazon - Google Apps Script - Google Sheets

The Goodreads API helps you query the entire database of books on the Goodreads website. You can find the ratings of books, fetch book reviews, search books by author or even publish your own reviews. This example shows how to connect to the GoodReads website through Google Apps Script, find books by title, parse the XML results as JSON and write the results in a Google Spreadsheet.

You can also extend the code to insert the thumbnail of the book image in a spreadsheet cell using the IMAGE function.

To get started, go to the Goodreads.com account and create a key. All Rest API methods will require you to register for a developer key.

Goodreads API

Goodreads will return the response in XML format (see below) and we can use the XML service of Google Apps Script to easily parse this XML response.

GoodReads XML

Here’s the complete example. Remember to replace the API key with your own.

function GoodReads() {
  var search = "Taj Mahal";
  var books = searchBooks_(search);

  // Write Data to Google Spreadsheet.
  var sheet = SpreadsheetApp.getActiveSheet();
  books.forEach(function(book) {
    sheet.appendRow([book.title, book.author, book.rating, book.url]);
  });
}

function searchBooks_(query) {

  var baseUrl = "https://www.goodreads.com/book/show/",
      apiUrl = "https://www.goodreads.com/search/index.xml",
      apiKey = "ctrlq.org",
      searchResults = [],
      payload = {
        q: query,
        key: apiKey
      },
      params = {
        method: "GET",
        payload: payload,
        muteHttpExceptions: true
      };

  var response = UrlFetchApp.fetch(apiUrl, params);

  // API Connection Successful
  if (response.getResponseCode() === 200) {

    // Parse XML Response
    var xml = XmlService.parse(response.getContentText());
    var results = xml.getRootElement().getChildren('search')[0];

    // Save the result in JSON format
    results.getChild('results').getChildren().forEach(function(result) {
      result.getChildren('best_book').forEach(function(book) {
        searchResults.push({
          title: book.getChild('title').getText(),
          author: book.getChild('author').getChild('name').getText(),
          thumbnail: book.getChild('image_url').getText(),
          rating: result.getChild("average_rating").getText(),
          url: baseUrl + result.getChild("id").getText()
        });
      });
    });

  }

  return searchResults;

}
Published in: Amazon - Google Apps Script - Google Sheets

Looking for something? Find here!

Meet the Author

Web Geek, Tech Columnist
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in GSuite and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. Read more on Lifehacker and YourStory

Get in touch