Add YouTube titles to Google sheets through Apps Script

I wanted to get a list of all the videos uploaded on YouTube by a specific user. A nice feature of Google Docs (Spreadsheet) is the abbility to add and run apps scripts to get data based from an external source like YouTube. So I changed a already existing script (http://ctrlq.org/code/19561-youtube-google-apps-script) and it works perfectly for me. Open a new Google Spreadsheet. The click “Tools > Script editor…” and copy past the code below. The you can run the script from within the “Script editor”. You probably need to authorise using YouTube within Google Spreadsheet.

function init() {
  retrieveUploads("allerhande",1);
}
function retrieveUploads(playlistID,start) {

var startpoint = start, options, titles = [], descriptions = [], videos = [], duration = [], uploaded = [], result, json, title="";
options = {
};

Logger.log('start');

do {
// Run in a loop since YouTube Data API only returns 50 videos in a batch
result = UrlFetchApp.fetch("http://gdata.youtube.com/feeds/api/users/" + playlistID + "/uploads?v=2&max-results=50&alt=json&start-index="+startpoint, options);
json = Utilities.jsonParse(result.getContentText());

// if there are no entries, stop do while loop
if (!json.feed.entry)
break;

// add certain data from entries to array
for (var i=0; i<json.feed.entry.length; i++) {
  titles.push(json.feed.entry[i].title.$t);
  descriptions.push(json.feed.entry[i].media$group.media$description.$t);
  duration.push(json.feed.entry[i].media$group.yt$duration.seconds);
  uploaded.push(json.feed.entry[i].media$group.yt$uploaded.$t);
  videos.push("http://youtu.be/"+json.feed.entry[i].media$group.yt$videoid.$t);
}

// increase the start-index by 50
startpoint += 50;
} while (startpoint < json.feed.openSearch$totalResults.$t);

// get active spreadsheet by name
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName(playlistID);

// add sheet if non exists with the given playlistID
if(sheet === null) sheet = ss.insertSheet(playlistID,2);

// add Youtube data to spreadsheet
for(var i=0;i<videos.length;i++) {
  sheet.getRange((i+start), 1, 1, 5).setValues([[titles[i],descriptions[i],duration[i],uploaded[i],videos[i]]]);
}
Logger.log('done');
}

2 thoughts on “Add YouTube titles to Google sheets through Apps Script

    • Don’t think this API endpoint still works. So you have to alter this script to make it work again. But then you should get the YouTube video’s of a Channel.

Leave a Reply

Your email address will not be published. Required fields are marked *