Skip to content

Instantly share code, notes, and snippets.

@phs
Last active December 19, 2015 12:09
Show Gist options
  • Save phs/5953060 to your computer and use it in GitHub Desktop.
Save phs/5953060 to your computer and use it in GitHub Desktop.
Mozscape API Demo from a Google Spreadsheet source
/**
* Returns an gmt epoch timestamp integer 4 hours into the future, to use as an API call expiration.
*/
function expiresTimestamp() {
var nowAsEpochGMTSeconds = Math.floor(new Date().getTime() / 1000.0);
var fourHoursFromNow = nowAsEpochGMTSeconds + 3600 * 4;
return fourHoursFromNow;
};
/**
* Formulate and return the API url (as a string) for fetching the given resource with the given credentials.
*
* Example: var url = apiUrl("/url-metrics/www.seomoz.org?Cols=68719476772", "member-xyz", "yabbadabbadoo");
*/
function apiUrl(resource, accessId, secretKey, expires) {
var toSign = accessId + "\n" + expires;
var binarySignature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_1, toSign, secretKey);
var base64signature = Utilities.base64Encode(binarySignature);
var urlEncodedSignature = encodeURIComponent(base64signature);
var url = "http://lsapi.seomoz.com/linkscape" + resource + "&AccessID=" + accessId + "&Expires=" + expires + "&Signature=" + urlEncodedSignature;
return url;
};
/**
* Fetch the given url from the API.
*/
function fetch(apiUrl) {
// Don't barf if the API url isn't calculated yet.
if (typeof(apiUrl) != "string" || apiUrl == "#N/A") return "";
var response = UrlFetchApp.fetch(apiUrl);
var contentText = response.getContentText();
// TODO: format?
return contentText;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment