1

Trying to shorten URLs through a Google apps script using Bit.ly api:

function shortenURL() {
  var longUrl = 'www.google.com';
  var shortURL;
  var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'payload' : JSON.stringify({
      "long_url": longUrl,
    }),
    'muteHttpExceptions': false,
    'headers': {'Authorization': 'Bearer ' + 'xxx (my authorization key)'};
  Logger.log(longUrl);
  shortURL = UrlFetchApp.fetch("https://api-ssl.bitly.com/v4/shorten", options).getContentText(); // Modified
  Logger.log(shortURL)
}

My URL looks fine but Bitly is rejection saying my URL is too long:

10:59:40 AM Notice  Execution started
10:59:40 AM Info    www.google.com
10:59:40 AM Error   
Exception: Request failed for https://api-ssl.bitly.com returned code 400. Truncated server response: {"message":"INVALID_ARG_LONG_URL","resource":"bitlinks","description":"The value provided is invalid.","errors":[{"field":"long_url","error_code":"... (use muteHttpExceptions option to examine full response)
shortenURL  @ BitlyTest.gs:14

Any suggestions appreciated.

user1355179
  • 89
  • 1
  • 8

1 Answers1

1

Modification points:

  • In your script, options is not enclosed by }. Please be careful about this.
  • I thought that var longUrl = 'www.google.com'; might be var longUrl = 'https://www.google.com';. I thought that this might be the reason for your current issue.

When these points are reflected in your script, it becomes as follows.

Modified script:

function shortenURL() {
  var longUrl = 'https://www.google.com';
  var shortURL;
  var options = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify({
      "long_url": longUrl,
    }),
    'muteHttpExceptions': false,
    'headers': { 'Authorization': 'Bearer ' + 'xxx (my authorization key)' }
  };
  Logger.log(longUrl);
  shortURL = UrlFetchApp.fetch("https://api-ssl.bitly.com/v4/shorten", options).getContentText(); // Modified
  Logger.log(shortURL)
}
  • When I tested this modified script using my access token, I confirmed that the correct response value could be obtained with no errors.
Tanaike
  • 181,128
  • 11
  • 97
  • 165