Get Book Details from Amazon with Google Apps Script

Google Apps Script can connect to the Amazon Product Advertising API to get the product details, price and availability of any book (by ISBN) or any other item listed on the Amazon website (by ASIN). You would need to sign-up for a free AWS (Amazon Web Services) account and also key in your Amazon Associate tag, the AWS Access ID (or SubscriptionID) and the AWS Secret Access key.

The script is for Amazon US (region set to com) but it would work for other Amazon country website as well though your Associate Tag may be different for different Amazon Website. See the Amazon Price Tracker to see the code in action.

function AmazonAPI(isbn) {
  
  var region = "com",
      method = "GET",
      uri    = "/onca/xml",
      host   = "ecs.amazonaws." + region;

  var private_key   = "AWS Secret Access Id",
      public_key    = "AWS Access Key",
      associate_tag = "labnol-20";
  
  var params = {
    Service        : "AWSECommerceService",
    Version        : "2011-08-01",
    AssociateTag   : associate_tag,
    Operation      : "ItemLookup",
    SearchIndex    : "Books",
    ItemId         : isbn,
    Timestamp      : new Date().toISOString(),
    AWSAccessKeyId : public_key,
    IdType         : "ISBN",
    ResponseGroup  : "ItemAttributes"
  };
  
  var canonicalized_query = Object.keys(params).sort();
  
  canonicalized_query = canonicalized_query.map(function(key){
    return key +"="+encodeURIComponent(params[key]);
  });
  
  var string_to_sign = method + "\n" + host + "\n" + uri + "\n" + canonicalized_query.join("&");
  
  var signature = Utilities.base64Encode
                     (Utilities.computeHmacSha256Signature(string_to_sign, private_key));
  
  var request   = "http://" + host + uri + "?" + canonicalized_query.join("&") 
                     + "&Signature=" + encodeURIComponent(signature);
  
  var response  = UrlFetchApp.fetch(request);
  
  return XmlService.parse(response.getContentText());
  
}

function getBookInfo(){

  var isbn = "xyz"; // Put the 10 or 13 digital ISBN here
  
  var o = {};
  var response = AmazonAPI(isbn);
  var a = response.getDescendants();
  
  for(var i=0;i<a.length;i++) {

    if(a[i].getType() == XmlService.ContentTypes.ELEMENT){
      switch(a[i].asElement().getName()){
        case "Title" :
          o.title = a[i].asElement().getText();
          break;
        case "FormattedPrice" :
          o.price = a[i].asElement().getText();
          break;
      }
    }
  }

  Logger.log(o);
}