JSmith
JSmith

Reputation: 4808

Using the UrlShortener API in a custom Spreadsheet function

I would like to use an API (url shortener) with a public google Add-on. For the moment my code returns:

Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.

Thanks a lot for your answers,

Upvotes: 1

Views: 1970

Answers (1)

Spencer Easton
Spencer Easton

Reputation: 5782

EDIT: The OP pointed out in the comments that this is a custom function. Custom function run with limited authorization. A complete list of what is available is at:
https://developers.google.com/apps-script/guides/sheets/functions#using_apps_script_services

Below uses the REST API to get the shortened url. This will work with custom functions. You will just need to enable the URL Shortener API and generate a Server API Key. Use the IPs at the following link for your server api key:
https://developers.google.com/apps-script/guides/jdbc#setup_for_google_cloud_sql

/**
 * Returns a shortened URL of the input.
 *
 * @param {string} longUrl The long URL to shorten.
 * @return The shortened url.
 * @customfunction
 */
function getShortUrl(longUrl) {

   var payLoad = {"longUrl": longUrl};
   var apiKey = PropertiesService.getScriptProperties().getProperty("ServerApiKey");
   var url  = "https://www.googleapis.com/urlshortener/v1/url?key="+ apiKey;
  var options = { method:"POST",
                 contentType:"application/json",
                 payload:JSON.stringify(payLoad),
                 muteHttpExceptions:true};

  var response = UrlFetchApp.fetch(url, options);
  if(response.getResponseCode() != 200){throw new Error("Unable to shorten url");}
  return JSON.parse(response).id;
}

Original Post


Here is a quick primer on using the UrlShortener advanced service. You will need to turn on the service and activate the Url Shortener api in the developers console. This will give you a quota of 1,000,000 requests per day for your add-on.

function myFunction() {
  var url = UrlShortener.newUrl();
  url.longUrl = "http://www.example.org";  
  var short = UrlShortener.Url.insert(url);
  Logger.log(short);

  //list all users shortened urls
  Logger.log(UrlShortener.Url.list());
}

Upvotes: 1

Related Questions