Pages

Tuesday, 3 March 2020

Search for artist in iTunes API

The following Google Apps Script takes the name of an artist from a Google Sheet, passes it to the iTunes API and returns a list of albums, song titles, artwork, etc all formatted into a Google Sheet table.
Screenshot of artist details in Google Sheet table
Screenshot of artist details in Google Sheet table

calliTunes.gs
This function uses the iTunes API to search for results on the given artist's name. We use the 'UrlFetchApp' to then call the API and 'getContentText' to store the returned data. 'JSON.parse' is used to convert the returned text data into a JavaScript object that we can then extract data from.

displayArtistData.gs
This function filters through the data returned from the iTunes API. It loops through the array of data pushing the items we want into an empty array.
var results = tracks['results'];
var dataItem = results[i];
var artistName = dataItem['artistName'];
var trackName = dataItem['trackName'];
After some sorting we add an index number to the array by using the 'forEach' method to call a function once for each array item, in order. We call the 'unshift' method here so we add the index number to the beginning of each array. This simply allows us to create a sequential list in the Google Sheet rather than using the row number.
[[1.0, Bee Gees, ...]
[2.0, Bee Gees, ...]
[3.0, Bee Gees, ...]]
Before pasting the results into the Google Sheet the function clears any previous content and then applies some formatting afterwards. So the function can be run repeatedly by the user.
ss.getRange(8, 1, 500, 6).clearContent();
ss.getRange(8,1,500,6).setVerticalAlignment('middle');
ss.getRange(8,5,500,1).setHorizontalAlignment('center');
ss.getRange(8,2,sortedOutputNewLength,3).setWrap(true);
sortByAlbum.gs
This is a small function called to organise the album names alphabetically. It also handles undefined names which may be returned from the API and cause the script to stop running, by giving them the name Not known instead.

Search for artist in iTunes API

No comments:

Post a comment