Get the Amazon Sales Rank by ASIN in Google Spreadsheet
Given the Amazon ASIN number, the getAmazonSalesRank() method with return the overall Sales Rank of the item using the Amazon Product Advertising API. You’ll need to enter your own Amazon AWS keys and associate ID before making the API calls.
This can also be converted into a custom function for Google Spreadsheets where you can enter the product ASINs in one column the latest sales rank is displayed in another column. It is however recommended that you either use the Cache Service or store the results in Property Service to avoid making too many calls to the Amazon API.
function getAmazonSalesRank(asin) {
try {
var method = 'GET',
uri = '/onca/xml',
host = 'ecs.amazonaws.com',
public_key = 'YOUR_PUBLIC_KEY',
private_key = 'YOUR_PRIVATE_KEY',
associate_tag = 'YOUR_AMAZON_ASSOCIATE_ID';
var params = {
Service: 'AWSECommerceService',
Version: '2011-08-01',
AssociateTag: associate_tag,
Operation: 'ItemLookup',
ItemId: asin,
Timestamp: new Date().toISOString(),
AWSAccessKeyId: public_key,
ResponseGroup: 'SalesRank',
};
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 =
'https://' + host + uri + '?' + canonicalized_query.join('&') + '&Signature=' + encodeURIComponent(signature);
var response = UrlFetchApp.fetch(request, { muteHttpExceptions: true }).getContentText();
var elems = XmlService.parse(response).getDescendants();
for (var i = 0; i < elems.length; i++) {
if (elems[i].getType() === XmlService.ContentTypes.ELEMENT)
if (elems[i].asElement().getName() === 'SalesRank') return elems[i].asElement().getText();
}
} catch (f) {}
return '';
}
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory