There are 3 YouTube related advanced services in Google Apps Script. In this post I’ll show you how to get simple stats about the youtube videos in your channel. The API documentation can be a little intimidating and it’s hard to find how to do even a simple thing like this if you;re not familiar with it.

I’ll assume you know how to enable advanced services in your project and console, so enable the YouTube Data API and we’re good to go.

Getting the channel ID.

Let’s assume you have only one channel for this excercise. The first thing you need to do is get your channel ID (you can find it in the youtube UI if you know where to look, but here’s how to get it from the API).

var channelId = YouTube.Channels.list('id', {mine: true}).items[0].id;

Getting the Video IDs

Now we can get all the videos in that channel, and extract out their ids.

// get video ids
  var videoIds = getVideoIds (channelId);

// get videos IDS for a given channel
  function getVideoIds (channelId) {
    
    var allIds =[], pageToken;
    do {
      
      // get all the videos for this channel
      var videos = YouTube.Search.list('id', {
        channelId:channelId,
        maxResults: 50,
        pageToken: pageToken
      });
      
      // set up for the next one
      pageToken = videos.nextPageToken;
      
      // append these ids
      Array.prototype.push.apply ( allIds , videos.items.map (function (d) {
        return d.id.videoId;
      }));
      
    } while (pageToken && videos.items.length);
    return allIds;
    
	}

Getting the Video details

Now we want to get statistics and data for each of those videos

// get the details
  var videoDetails = getVideoDetails (videoIds);

  // get videos details for a list of ids
  function getVideoDetails (videoIds) {
    
    var allDetail =[], pageToken;
    do {
      
      // get details for each video
      var details = YouTube.Videos.list('id,snippet,statistics',{
      // The 'id' property's value is a comma-separated string of video IDs.
        id: videoIds.join(','),
        maxResults: 50,
        pageToken: pageToken
      });
      
      // set up for the next one
      pageToken = details.nextPageToken;
      
      // append these ids
      Array.prototype.push.apply ( allDetail , details.items);
      
    } while (pageToken && details.items.length);
    return allDetail;
    
	}

And that’s all there is to it.

For more like this see Google Apps Scripts Snippets
For help and more information join our forum,follow the blog or follow me on Twitter .