Published using Google Docs
Public YouTube API Codelab: Web Application Example (Japan)
Updated automatically every 5 minutes

YouTube API Codelab:

Web Application Example

Important Links

Test Account

Code Archive

YouTube v3 API Syntax

Link to the Slide Deck

Lesson 1: Base HTML

Lesson 2: Authentication with OAuth 2

Lesson 3: Requesting the YouTube User Id and List of Uploads

Lesson 4: Requesting YouTube Analytics Data for a Given Video

Lesson 5: Displaying Analytics Data in a Chart

Lesson 6: Adding CSS

Areas for Exploration

Important Links

Test Account

This code is only interesting if you run it while authenticated as a YouTube user that has videos that have received views within the past month. Feel free to use your own YouTube account, but if you’d rather use a test account, try the following: goog.io.ytapi@gmail.com, password 1234test. That account contains videos that received views from 2012-06-13 to 2012-09-18.

Code Archive

An archive of the code broken down into separate lessons can be found at:

http://io12-youtube-codelab.appspot.com/static/webapp-lessons.zip

YouTube v3 API Syntax

See discovery document at https://www.googleapis.com/discovery/v1/apis/youtube/v3/rpc and user documentation https://developers.google.com/youtube/v3/

Link to the Slide Deck

http://goo.gl/ulQ6A

Lesson 1: Base HTML

http://io12-youtube-codelab.appspot.com/static/lesson1/index.html

We need a basic HTML structure in place before we can use JavaScript to talk to the YouTube APIs.

The HTML provided here loads in the required JavaScript libraries. It provides a basic user interface which will be enhanced with additional JavaScript and CSS in future lessons.

Lesson 2: Authentication with OAuth 2

http://io12-youtube-codelab.appspot.com/static/lesson2/index.html

The Google APIs Client Library for JavaScript handles all aspects of OAuth 2 for us. We can use it to initiate the client flow and keeping track of the access tokens after a successful auth. This lesson demonstrates how to use the library to specify the desired scopes, attempt an “immediate” OAuth 2 request when the page first loads, and then if that doesn’t succeed, kick off the non-immediate OAuth 2 client flow when a login link is clicked.

The OAUTH2_CLIENT_ID constant provided in the index.js file is valid if your web application is being served off of http://localhost, i.e. from a local web server. If you are serving your web app off of a production web server, or if you just want to get experience with the process of registering for your own OAuth 2 client id, you can kick off the process by creating a new application in the Google API Console. The whole process is explained in the JavaScript client library documentation.

You might be curious about the (function() {})(); wrapper around the JavaScript code. This is a common convention to ensure that variables and functions declared within that wrapper are in an anonymous local scope, rather than polluting the global (i.e. window) scope. When we need to add something to the window scope within our code, like a callback function that needs to be globally accessible, we can do that with explicit assignments to properties of window.

Lesson 3: Requesting the YouTube User Id and List of Uploads

http://io12-youtube-codelab.appspot.com/static/lesson3/index.html

Now that we have a valid OAuth 2 access token, we can use it to talk to the YouTube Data API and retrieve two pieces of information.

We need to tell the Google APIs JavaScript client library that we plan on making a request to the YouTube Data API (and later the Analytics API) by calling gapi.client.load() with the required parameters youtube and v3. Once that’s loaded, we’ll load the youtubeAnayltics version v1. Once both those client interfaces are available, we’re ready to talk to the YouTube API.

First, we retrieve the YouTube channel id and user id associated with the current authenticated user. The user id is needed later on when making requests to the YouTube Analytics API.

Next, we retrieve a list of YouTube video ids for all the uploads in the current authenticated user’s account, making use of the channel id we previously obtaining. We pass in this list of video ids into the YouTube API call to retrieve metadata about each video. Once we have that metadata, we can construct a list of those videos’ titles and add that list to the existing HTML on the page. Videos that have never received any views (because they are not active or because they were simply never watched) are excluded from the list. Eventually, clicking on any item in the list will retrieve analytics data for that video and display a chart, but for the time being, clicking on any item will just display the corresponding video id.

Lesson 4: Requesting YouTube Analytics Data for a Given Video

http://io12-youtube-codelab.appspot.com/static/lesson4/index.html

Instead of simply displaying the video id when clicking on a video list item as we previously did, we now want to make a call to the YouTube Analytics API to retrieve analytics data for that video when it is clicked.

There are a number of different types of reports that can be retrieved via the YouTube Analytics API. For the purposes of this example, we’ll be retrieving a report of the view counts aggregated by day and filtered by a single video id, over the course of the past month. If you decide to change the parameters passed in to the YouTube Analytics API call, make careful note of the combinations of supported parameters, since many types of metrics/dimensions combinations are invalid.

For the time being, we’ll simply display the raw response from the Analytics API on the web page.

The YouTube Analytics API expects dates to be passed in as YYYY-MM-DD strings. Two helper functions, formatDateString() and padToTwoCharacters(), make the conversion from a JavaScript Date to that format easier.

If you don’t have any videos in your own YouTube account, you can authenticate with the credentials goog.io.ytapi@gmail.com/1234test. Please note that because immediate OAuth 2 is used, if you’ve previously authenticated as a different account then when you visit the same page the existing account will automatically be used. Since there’s currently no “Logout” link in the web application, the easiest way to switch authenticated accounts is to open an “Incognito” window in Google Chrome, or use a different web browser.

Lesson 5: Displaying Analytics Data in a Chart

http://io12-youtube-codelab.appspot.com/static/lesson5/index.html

Now that we have a means of fetching YouTube analytics data for a given video, the natural course of action is to visualize that data in a meaningful way. The Google Chart Tools API provides a way to create charts dynamically using JavaScript.  We’ll be creating a line chart in this example, but other chart types are available as well.

The specifics of using the Google Chart Tools API is a bit out of scope for this codelab, but the thrust of it is that we first determine the column titles from the analytics response, and then pass those along with the rows of data to the google.visualization.arrayToDataTable() method, which format the data in a way that can then be visualized. Fortunately, the data that’s returned in the analytics API response is in a very similar format to what the google.visualization.arrayToDataTable() method expects; the only massaging involves using the jQuery.map() method to create an array of column titles.

Lesson 6: Adding CSS

We’re now done with all the coding, and the last step is adding CSS definitions to improve the appearance of the user interface.

http://io12-youtube-codelab.appspot.com/static/lesson6/index.html

Areas for Exploration

Now that you’ve worked through the lessons in the example, think about ways you can modify the existing code to provide a different experience. For instance, you can change the user interface (via HTML or CSS). Or you could change the YouTube Analytics report definition to something different, and/or creating a different chart is another way the example can be enhanced.