google-apps-scriptgoogle-sheetshttp-status-code-403url-shortener

Google Sheets Advanced Google Services URL Shortener 403 Error: Forbidden


I am trying to create a small application in in Google Sheets to sorten URLs on my personal google account. I am using the following code which I found here: Google Sheets Function to get a shortened URL (from Bit.ly or goo.gl etc.)

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu("Shorten")
    .addItem("Go !!","rangeShort")
    .addToUi()  
}

function rangeShort() {
  var range = SpreadsheetApp.getActiveRange(), data = range.getValues();
  var output = [];
  for(var i = 0, iLen = data.length; i < iLen; i++) {
    //var url = UrlShortener.Url.insert({longUrl: data[i][0]});
    var url = UrlShortener.Url.insert({longUrl: 'www.google.com'});
    output.push([url.id]);
  }
  range.offset(0,1).setValues(output);
}

I created a new Google Cloud Project and enabled the URL shortener API in the project and on the Google sheet. The problem is that when I try and run the code I get an err on the line: var url = UrlShortener.Url.insert({longUrl: 'www.google.com'});

error 403, message:forbidden

when i try an execute the rangeShort() function. I have no idea how to fix this. Any ideas would be most appreciated! Thanks!


Solution

  • As it turns out, like Ruben mentioned, Google has moved away from their URL shortener. So after much research ans testing here is the solution:

    Step 1

    Migrate Google Cloud Project over to Firebase or create a new Firebase Project. See steps here

    Step 2

    Create a dummy project in order to create a base URL for the shortening. See this youtube video

    Step 3

    Get the Web API Key from your new Firebase Project (not the app you just created)

    Step 4

    Check the left side menu on the screen and navigate to Grow->Dynamic Links. You should see the new application you created and a URL at the top of the application. This will become the base of the new shortened URLs.

    Step 5

    Create the code in Google Apps Script inside the code builder from within Google Sheets. Here is the code that worked for me (I passed the url into this function) (This code is based on the answer found here):

    function api_call(url){
      var req='https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[YOUR PROJECT WEB API KEY FROM STEP 3]';
      var formData = {
        "longDynamicLink": "[YOUR APPLICATION URL BASE FROM STEP 4]?link=" + url,
        "suffix" : {
          "option" : "UNGUESSABLE" 
        }
      };
      var options = {
        'method': 'post',
        'contentType': 'application/json',
        'payload': JSON.stringify(formData)
    
      };
    
      var response = UrlFetchApp.fetch(req, options);
      var res=JSON.parse(response);
    
      return res.shortLink;
    }
    

    Additional Information

    1. Documentation on Creating Dynamic Links in Firebase
    2. Documentation on using UrlFetchApp() in Google Apps Script