How to use url url shorter api using UrlFetchApp.fetch?

I spent a lot of time reading Google manuals and other resources and didn’t figure out what I was doing wrong trying to get a short url using this script:

function test_short_link() {
  var apiKey, post_url, options, result;
  post_url = "https://www.googleapis.com/urlshortener/v1/url";
  apiKey = 'xxx';//here is real apiKey
  post_url += '?key=' + apiKey;
  var options =
     { 'method':'post',
       'headers' : {'Content-Type' : 'application/json'},
       "resource": {"longUrl": "https://google.com/"},
       'muteHttpExceptions': true
     }
   result = UrlFetchApp.fetch(post_url, options);
   Logger.log(result);
}

I made various modifications, but it returns:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required",
    "locationType": "parameter",
    "location": "resource.longUrl"
   }
  ],
  "code": 400,
  "message": "Required"
 }
}

It drives me crazy!
Please help! What is wrong with this code?

+4
source share
2 answers

You will need to change this code as it hardcodes longUrl and does not check for errors. Some of the important parts are that the API parameters are sent in the payload of the UrlFetchApp options object and that you need to pass the tokens of the current OAuth user in the header.

function ShortenUrl(){
var url = "https://www.googleapis.com/urlshortener/v1/url"

var payload = {"longUrl":"www.google.com"};

var parameters = { method : 'post',
                    headers : {'Authorization': 'Bearer '+ScriptApp.getOAuthToken()},
                    payload:JSON.stringify(payload),
                    contentType:'application/json',                    
                    muteHttpExceptions:true};

  var response = UrlFetchApp.fetch(url, parameters);
  Logger.log(response);

}
+2

Google, .

script (. ).

:

function shortenUrl(longUrl) {
  var toShorten = UrlShortener.newUrl().setLongUrl(longUrl);
  var shortened = UrlShortener.Url.insert(toShorten);
  return shortened.id;
}

, :

function test(){
  var shortUrl = shortenUrl("http://stackoverflow.com/questions/tagged/google-apps-script");
  Logger.log(shortUrl);
}

enter image description here

enter image description here

0

All Articles