Search code examples
google-apps-scriptgoogle-sheetsspotify

Spotify API authorisation via Google Apps Script


I am using the following code to make requests to the Spotify API via Google Apps Script:

function search() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var artist = sheet.getRange(1,1).getValue();
  artist = encodeURIComponent(artist.trim());
  var result = searchSpotify(artist);
  Logger.log(result);
}

function searchSpotify(artist) {
  //searches spotify and returns artist ID
  var response = UrlFetchApp.fetch("https://api.spotify.com/v1/search?q=" + artist + "&type=artist&limit=1", 
  { method: "GET",
    headers:{
      "contentType": "application/json",
      'Authorization': "Bearer BQBnpSUdaEweirImw23yh2DH8OGhTwh5a_VnY_fgb2BPML0KvFvYd04CaEdUhQN9N4ZUXMIVfJ1MjFe1_j0Gl0UoHDhcoC_dklluZyOkq8Bo6i2_wfxSbGzP3k5EUjUKuULAnmTwCdkdZQnl-SNU0Co"
            },
  });
  json = response.getContentText();
  var data = JSON.parse(json);
  var uri = data.artists.items[0].uri.slice(15);
  var getArtists = getRelatedArtists(uri);
  Logger.log(getArtists);
  return getArtists;
}

function getRelatedArtists(uri) {
  //searches related artists with the returned ID
  var response = UrlFetchApp.fetch("https://api.spotify.com/v1/artists/" + uri + "/related-artists", 
  { method: "GET",
    headers:{
      "contentType": "application/json",
      'Authorization': "Bearer BQBnpSUdaEweirImw23yh2DH8OGhTwh5a_VnY_fgb2BPML0KvFvYd04CaEdUhQN9N4ZUXMIVfJ1MjFe1_j0Gl0UoHDhcoC_dklluZyOkq8Bo6i2_wfxSbGzP3k5EUjUKuULAnmTwCdkdZQnl-SNU0Co"
            },
  });
  json = response.getContentText();
  var data = JSON.parse(json);
  var listArtists = [];
  for(var i = 0, len = data.artists.length; i < len; i++){
    listArtists.push(data.artists[i].name);
                 }
  return listArtists;
}

This works fine using the temporary Authorisation token from the Spotify website but this token refreshes every hour and so is obviously useless.

I am trying to use my own Authorisation token and ID which I have setup on Spotify however I'm struggling to make this work. As I understand it I may need to add an extra step at the beginning to start the authorisation process but I've tried all methods suggested but keep receiving server errors.


Solution

  • From the document, it seems that "Client Credentials Flow" uses the basic authorization.

    In order to use this, at first, you are required to retrieve "client_id" and "client_secret".

    Sample script:

    var clientId = "### client id ###"; // Please set here.
    var clientSecret = "### client secret ###"; // Please set here.
    
    var url = "https://accounts.spotify.com/api/token";
    var params = {
      method: "post",
      headers: {"Authorization" : "Basic " + Utilities.base64Encode(clientId + ":" + clientSecret)},
      payload: {grant_type: "client_credentials"},
    };
    var res = UrlFetchApp.fetch(url, params);
    Logger.log(res.getContentText())
    
    • From curl sample, grant_type is required to send as form.

    Result:

    The document says that the response is as follows.

    {
       "access_token": "NgCXRKc...MzYjw",
       "token_type": "bearer",
       "expires_in": 3600,
    }
    

    Note:

    • This is a simple sample script. So please modify this for your situation.
    • I prepared this sample script by the sample curl in the document.

    Reference:

    Edit:

    As your next issue, you want to retrieve the access token from the returned value. If my understanding is correct, how about this modification? Please modify my script as follows.

    From:

    Logger.log(res.getContentText())
    

    To:

    var obj = JSON.parse(res.getContentText());
    Logger.log(obj.access_token)
    
    • When the value is returned from API, it returns as a string. So it is required to parse it as an object using JSON.parse().