google-apps-scriptgoogle-sheetshttp-status-code-403urlfetchbit.ly

Posting to Bitly api with Google App Script returns 403


Hey Stackoverflow fellows!

I have been trying to writing an automation for my google sheets using an api from bit.ly to shorten my tons of link. Right now, I am at the fundamental stage and trying to log what the api return to me. Could you guys help an see what is wrong with the code? I am expecting the 200 returning back to me but it keep returning 403 forbidden to me.

var form = 
     {"long_url": "https://dev.bitly.com", "domain": "bit.ly", "group_guid": "MY GROUP ID" };  
var option =  {'header':'Authorization: Bearer{MY TOKEN}',
       'method' : 'post',
       'contentType': 'application/json', 
       'payload' : JSON.stringify(form)
       };
 var response = UrlFetchApp.fetch('https://api-ssl.bitly.com/v4/shorten', option);
Logger.log (response);
}

P.S. I tried to further expand the code by using adding title (succeeded) and customized link (short half // after bit.ly/ ). The second part keep return me 404. Or should I use Post/custom_bitlinks instead?

Here is my current code:

function bitlyori (i, title){
var form = {
    "group_guid": "MINE",  
    "domain": "bit.ly",  
    "long_url": i,
    "title" : title
    }; 
const MY_TOKEN = "MINE";
const option = {
  headers: { Authorization: `Bearer ${MY_TOKEN}` },
  method: 'post',
  contentType: 'application/json',
  payload: JSON.stringify(form),
  };
var result = UrlFetchApp.fetch('https://api-ssl.bitly.com/v4/bitlinks', option);
return (JSON.parse(result.getContentText()));
}

function bitly(url,title,custom) {
var temp = bitlyori(url, title);
var form_2 = { 
  "custom_bitlinks": [temp] ,
    };
const MY_TOKEN = "MINE";
const option_2 = {
  headers: { Authorization: `Bearer ${MY_TOKEN}` },
  method: 'patch',
  payload: form_2}; 
var temp_link = 'https://api-ssl.bitly.com/v4/bitlinks/'+ JSON.stringify(temp)["id"];
var result_2 = UrlFetchApp.fetch(temp_link, option_2);
return (JSON.parse(result_2.getContentText()));
}

Solution

  • Headers should be a object with key "headers" inside options:

    const MY_TOKEN = "dfjkgsa";
    const option = {
      headers: { Authorization: `Bearer ${MY_TOKEN}` },
      method: 'post',
      contentType: 'application/json',
      payload: JSON.stringify(form),
    };
    

    See: