Build a Sample Application

  • This web application utilizes the YouTube Data API to fetch a user's uploaded videos and the YouTube Analytics API to retrieve viewing statistics for those videos.

  • The application leverages OAuth 2.0 for secure user authentication, granting it read-only access to the user's YouTube data and analytics.

  • The Google Visualization API is employed to dynamically generate charts that visually represent the retrieved YouTube analytics data, such as daily views.

  • The application uses JavaScript, including jQuery for DOM manipulation, and the Google APIs Client Library to streamline interactions with Google's services.

  • The application filters out videos with zero views, and shows a message if the user channel has no viewed videos or the channel ID cannot be found.

This page walks you through the steps of building an application that uses several different APIs to chart viewing statistics for a user's YouTube videos. The application performs the following tasks:

  • It uses the YouTube Data API to retrieve a list of the currently authenticated user's uploaded videos and then displays a list of video titles.
  • When the user clicks on a particular video, the application calls the YouTube Analytics API to retrieve analytics data for that video.
  • The application uses the Google Visualization API to chart the analytics data.

The following steps describe the process of building the application. In step 1, you create the application's HTML and CSS files. Steps 2 through 5 describe different parts of the JavaScript that the application uses. The complete sample code is also included at the end of the document.

  1. Step 1: Build your HTML page and CSS file
  2. Step 2: Enable OAuth 2.0 authentication
  3. Step 3: Retrieve data for the currently logged-in user
  4. Step 4: Request Analytics data for a video
  5. Step 5: Display Analytics data in a chart

Important: You need to register your application with Google to obtain an OAuth 2.0 client ID for your application.

Step 1: Build your HTML page and CSS file

In this step, you'll create an HTML page that loads the JavaScript libraries that the application will use. The HTML below shows the code for the page:

<!doctype html>
<html>
<head>
  <title>Google I/O YouTube Codelab</title>
  <link type="text/css" rel="stylesheet" href="index.css">
  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script type="text/javascript" src="//www.google.com/jsapi"></script>
  <script type="text/javascript" src="index.js"></script>
  <script type="text/javascript" src="https://apis.google.com/js/client.js?onload=onJSClientLoad"></script>
</head>
<body>
  <div id="login-container" class="pre-auth">This application requires access to your YouTube account.
    Please <a href="#" id="login-link">authorize</a> to continue.
  </div>
  <div class="post-auth">
    <div id="message"></div>
    <div id="chart"></div>
    <div>Choose a Video:</div>
    <ul id="video-list"></ul>
  </div>
</body>
</html>

As shown in the <head> tag of the sample page, the application uses the following libraries:

  • jQuery provides helper methods to simplify HTML document traversing, event handling, animating and Ajax interactions.
  • The Google API loader (www.google.com/jsapi) lets you easily import one or more Google APIs. This sample application uses the API loader to load the Google Visualization API, which is used to chart the retrieved Analytics data.
  • The index.js library contains functions specific to the sample application. This tutorial walks you through the steps to create those functions.
  • The Google APIs Client Library for JavaScript helps you to implement OAuth 2.0 authentication and to call the YouTube Analytics API.

The sample application also includes the index.css file. A sample CSS file, which you could save in the same directory as your HTML page, is shown below:


body {
  font-family: Helvetica, sans-serif;
}

.pre-auth {
  display: none;
}

.post-auth {
  display: none;
}

#chart {
  width: 500px;
  height: 300px;
  margin-bottom: 1em;
}

#video-list {
  padding-left: 1em;
  list-style-type: none;
}
#video-list > li {
  cursor: pointer;
}
#video-list > li:hover {
  color: blue;
}

Step 2: Enable OAuth 2.0 authentication

In this step, you'll start building the index.js file that's being called by your HTML page. With that in mind, create a file named index.js in the same directory as your HTML page and insert the following code in that file. Replace the string YOUR_CLIENT_ID with the client ID for your registered application.

(function() {

  // Retrieve your client ID from the Google Cloud console at
  // https://console.cloud.google.com/.
  var OAUTH2_CLIENT_ID = 'YOUR_CLIENT_ID';
  var OAUTH2_SCOPES = [
    'https://www.googleapis.com/auth/yt-analytics.readonly',
    'https://www.googleapis.com/auth/youtube.readonly'
  ];

  // Upon loading, the Google APIs JS client automatically invokes this callback.
  // See https://developers.google.com/api-client-library/javascript/features/authentication 
  window.onJSClientLoad = function() {
    gapi.auth.init(function() {
      window.setTimeout(checkAuth, 1);
    });
  };

  // Attempt the immediate OAuth 2.0 client flow as soon as the page loads.
  // If the currently logged-in Google Account has previously authorized
  // the client specified as the OAUTH2_CLIENT_ID, then the authorization
  // succeeds with no user intervention. Otherwise, it fails and the
  // user interface that prompts for authorization needs to display.
  function checkAuth() {
    gapi.auth.authorize({
      client_id: OAUTH2_CLIENT_ID,
      scope: OAUTH2_SCOPES,
      immediate: true
    }, handleAuthResult);
  }

  // Handle the result of a gapi.auth.authorize() call.
  function handleAuthResult(authResult) {
    if (authResult) {
      // Authorization was successful. Hide authorization prompts and show
      // content that should be visible after authorization succeeds.
      $('.pre-auth').hide();
      $('.post-auth').show();

      loadAPIClientInterfaces();
    } else {
      // Authorization was unsuccessful. Show content related to prompting for
      // authorization and hide content that should be visible if authorization
      // succeeds.
      $('.post-auth').hide();
      $('.pre-auth').show();

      // Make the #login-link clickable. Attempt a non-immediate OAuth 2.0
      // client flow. The current function is called when that flow completes.
      $('#login-link').click(function() {
        gapi.auth.authorize({
          client_id: OAUTH2_CLIENT_ID,
          scope: OAUTH2_SCOPES,
          immediate: false
        }, handleAuthResult);
      });
    }
  }

  // This helper method displays a message on the page.
  function displayMessage(message) {
    $('#message').text(message).show();
  }

  // This helper method hides a previously displayed message on the page.
  function hideMessage() {
    $('#message').hide();
  }
  /* In later steps, add additional functions above this line. */
})();

Step 3: Retrieve data for the currently logged-in user

In this step, you'll add a function to your index.js file that retrieves the currently logged-in user's uploaded videos feed using the YouTube Data API (v2.0). That feed will specify the user's YouTube channel ID, which you will need when calling the YouTube Analytics API. In addition, the sample app will list the user's uploaded videos so that the user can retrieve Analytics data for any individual video.

Make the following changes to your index.js file:

  1. Add a function that loads the client interface for the YouTube Analytics and Data APIs. This is a prerequisite to using the Google APIs JavaScript client.

    Once both API client interfaces are loaded, the function calls the getUserChannel function.

      // Load the client interfaces for the YouTube Analytics and Data APIs, which
      // are required to use the Google APIs JS client. More info is available at
      // https://developers.google.com/api-client-library/javascript/dev/dev_jscript#loading-the-client-library-and-the-api
      function loadAPIClientInterfaces() {
        gapi.client.load('youtube', 'v3', function() {
          gapi.client.load('youtubeAnalytics', 'v1', function() {
            // After both client interfaces load, use the Data API to request
            // information about the authenticated user's channel.
            getUserChannel();
          });
        });
      }
  2. Add the channelId variable as well as the getUserChannel function. The function calls the YouTube Data API (v3) and includes the mine parameter, which indicates that the request is for the currently authenticated user's channel information. The