1
votes

Apologies in advance - I am a complete beginner to using Google Apps Script.

I have a question on how to transfer data from a YouTube API call to a Google Sheet. I have set up the code below, which searches videos from a channel ID and loops (to get beyond the 50 results limit).

I want to pull back the four variables defined in the script into a Google Sheet - Published At, Title, ID and URL i.e. information on these four elements for all 7,000+ videos in the channel. All of this information appears to log successfully using the Logger.log line.

I now want to transfer the information that is logged to a Google Sheet. I have experimented with different ways of doing this but I have only managed to pull back the details of the last video successfully.

Can anyone advise on the code I would need to add to the final section after the 'var ActiveSheet' line to make this work successfully?

As I say, apologies if this is a stupid question.

function myFunction() {

var nextPageToken = '';

while (nextPageToken != null) {
  var sr = YouTube.Search.list("snippet", {
    channelId:'UC14UlmYlSNiQCBe9Eookf_A', 
    maxResults: 50,
    pageToken: nextPageToken
  });

    for (var j = 0; j < sr.items.length; j++) {
    var srItem = sr.items[j];
    var PublishedAt = srItem.snippet.publishedAt;
    var Title = srItem.snippet.title;
    var ID = srItem.id.videoId;
    var URL = srItem.snippet.thumbnails.high.url;
      Logger.log('[%s] Title: %s Id: %s Url: %s',
               srItem.snippet.publishedAt,
               srItem.snippet.title,
               srItem.id.videoId,
               srItem.snippet.thumbnails.high.url);
  }
  nextPageToken = sr.nextPageToken;
}

var ss = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = ss.getActiveSheet();

}

Any help would be massively appreciated.

Thanks,

KC

1

1 Answers

2
votes

You need to capture every row and save then in an array. Then you can insert the rows into the sheet. Following code does that.

function myFunction() {
  var nextPageToken = '';

  // to hold data rows
  var results = [];
  // add header row
  results.push(['Published At', 'Title', 'ID', 'URL']);

  while (nextPageToken != null) {
    var sr = YouTube.Search.list('snippet', {
      channelId: 'UC14UlmYlSNiQCBe9Eookf_A',
      maxResults: 50,
      pageToken: nextPageToken
    });

    for (var j = 0; j < sr.items.length; j++) {
      var srItem = sr.items[j];
      var PublishedAt = srItem.snippet.publishedAt;
      var Title = srItem.snippet.title;
      var ID = srItem.id.videoId;
      var URL = srItem.snippet.thumbnails.high.url;
      // add every row
      results.push([PublishedAt, Title, ID, URL]);
    }
    nextPageToken = sr.nextPageToken;
  }

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  // get range and set values
  // row to start, col to start, how many rows, how many cols
  sheet.getRange(1, 1, results.length, 4).setValues(results);
}