Using the UrlShortener API in a custom Spreadsheet function

假装没事ソ 提交于 2019-12-08 03:12:13

问题


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.

  • Is this possible?
  • If yes, Do I need an authentification Token?
    • If yes, what key type should I choose?
    • How can I implement the authorisation for this kind of use?
    • Do I need to pay for it?
  • If no, How could other add-ons use external APIs

Thanks a lot for your answers,


回答1:


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());
}


来源:https://stackoverflow.com/questions/30429435/using-the-urlshortener-api-in-a-custom-spreadsheet-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!