YouTube

YouTube Data API: JavaScript Code Samples

experimental feature
The YouTube Data API (v3) is an experimental API version, which means it is still in development. We'll be adding many more features to the API while it is still an experimental version. Until the experimental label is removed, however, the Deprecation Policy for YouTube APIs won't apply to this version as discussed in the API Terms of Service.

The following code samples use the Google APIs Client Library for JavaScript to demonstrate YouTube Data API functionality:

  1. Authorizing requests
  2. My uploaded videos
  3. Update a playlist
  4. Search by keyword

Authorizing requests

The auth.js script demonstrates how to use the Google APIs Client Library for JavaScript to provide API access and authorize user requests. All of the subsequent samples on this page use this script to authorize their requests.

For requests that do not require authentication, you could also use the key query parameter to specify an API key rather than using OAuth 2.0.

Note: You need to update the client ID in the auth.js file. You can obtain your own client ID by registering your application in the Google APIs Console.

// The client id is obtained from the Google APIs Console at https://code.google.com/apis/console
// If you run access this code from a server other than http://localhost, you need to register
// your own client id.
var OAUTH2_CLIENT_ID = '__YOUR_CLIENT_ID__';
var OAUTH2_SCOPES = [
  'https://www.googleapis.com/auth/youtube'
];

// This callback is invoked by the Google APIs JS client automatically when it is loaded.
googleApiClientReady = function() {
  gapi.auth.init(function() {
    window.setTimeout(checkAuth, 1);
  });
}

// Attempt the immediate OAuth 2 client flow as soon as the page is loaded.
// If the currently logged in Google Account has previously authorized OAUTH2_CLIENT_ID, then
// it will succeed with no user intervention. Otherwise, it will fail and the user interface
// to prompt for authorization needs to be displayed.
function checkAuth() {
  gapi.auth.authorize({
    client_id: OAUTH2_CLIENT_ID,
    scope: OAUTH2_SCOPES,
    immediate: true
  }, handleAuthResult);
}

// Handles the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
  if (authResult) {
    // Auth was successful; hide the things related to prompting for auth and show the things
    // that should be visible after auth succeeds.
    $('.pre-auth').hide();
    loadAPIClientInterfaces();
  } else {
    // Make the #login-link clickable, and attempt a non-immediate OAuth 2 client flow.
    // The current function will be called when that flow is complete.
    $('#login-link').click(function() {
      gapi.auth.authorize({
        client_id: OAUTH2_CLIENT_ID,
        scope: OAUTH2_SCOPES,
        immediate: false
        }, handleAuthResult);
    });
  }
}

// Loads the client interface for the YouTube Analytics and Data APIs.
// This is required before using the Google APIs JS client; more info is available at
// http://code.google.com/p/google-api-javascript-client/wiki/GettingStarted#Loading_the_Client
function loadAPIClientInterfaces() {
  gapi.client.load('youtube', 'v3', function() {
    handleAPILoaded();
  });
}

My uploaded videos

The code samples below are for an application that lists videos uploaded to the authorized user's channel. The code assumes that the JavaScript and CSS files are in the same directory as the HTML page.

  • JavaScript (my_uploads.js)

    The JavaScript code below performs the following functions:

    1. It retrieves the playlist ID for videos uploaded to the user's channel using the API's channels.list method.
    2. It passes that ID to the playlistItems.list method to retrieve the videos in that list.
    3. It displays the list of videos.
    4. It constructs next and previous page buttons and sets their visibility based on the information in the API response.

    As noted in the Authorizing requests section, you need to update the client ID in the auth.js file to run this code.

    // Some variables to remember state.
    var playlistId, nextPageToken, prevPageToken;
    
    // Once the api loads call a function to get the uploads playlist id.
    function handleAPILoaded() {
      requestUserUploadsPlaylistId();
    }
    
    //Retrieve the uploads playlist id.
    function requestUserUploadsPlaylistId() {
      // https://developers.google.com/youtube/v3/docs/channels/list
      var request = gapi.client.youtube.channels.list({
        // mine: '' indicates that we want to retrieve the channel for the authenticated user.
        mine: '',
        part: 'contentDetails'
      });
      request.execute(function(response) {
        playlistId = response.result.items[0].contentDetails.uploads;
        requestVideoPlaylist(playlistId);
      });
    }
    
    // Retrieve a playist of videos.
    function requestVideoPlaylist(playlistId, pageToken) {
      $('#video-container').html('');
      var requestOptions = {
        playlistId: playlistId,
        part: 'snippet',
        maxResults: 9
      };
      if (pageToken) {
        requestOptions.pageToken = pageToken;
      }
      var request = gapi.client.youtube.playlistItems.list(requestOptions);
      request.execute(function(response) {
        // Only show the page buttons if there's a next or previous page.
        nextPageToken = response.result.nextPageToken;
        var nextVis = nextPageToken ? 'visible' : 'hidden';
        $('#next-button').css('visibility', nextVis);
        prevPageToken = response.result.prevPageToken
        var prevVis = prevPageToken ? 'visible' : 'hidden';
        $('#prev-button').css('visibility', prevVis);
    
        var playlistItems = response.result.items;
        if (playlistItems) {
          // For each result lets show a thumbnail.
          jQuery.each(playlistItems, function(index, item) {
            createDisplayThumbnail(item.snippet);
          });
        } else {
          $('#video-container').html('Sorry you have no uploaded videos');
        }
      });
    }
    
    
    // Create a thumbnail for a video snippet.
    function createDisplayThumbnail(videoSnippet) {
      var titleEl = $('<h3>');
      titleEl.addClass('video-title');
      $(titleEl).html(videoSnippet.title);
      var thumbnailUrl = videoSnippet.thumbnails.medium.url;
    
      var div = $('<div>');
      div.addClass('video-content');
      div.css('backgroundImage', 'url("' + thumbnailUrl + '")');
      div.append(titleEl);
      $('#video-container').append(div);
    }
    
    // Retrieve the next page of videos.
    function nextPage() {
      requestVideoPlaylist(playlistId, nextPageToken);
    }
    
    // Retrieve the previous page of videos.
    function previousPage() {
      requestVideoPlaylist(playlistId, prevPageToken);
    }
    
  • HTML (my_uploads.html)

    The HTML page below uses JQuery, the auth.js and my_uploads.js JavaScript files shown above, and a CSS file to display the list of uploaded videos.

    <!doctype html>
    <html>
      <head>
        <title>My Uploads</title>
        <link rel="stylesheet" href="my_uploads.css" />
      </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 id="video-container">
        </div>
        <div class="button-container">
          <button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button>
          <button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button>
        </div>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="auth.js"></script>
        <script src="my_uploads.js"></script>
        <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
      </body>
    </html>
    
  • CSS (my_uploads.css)

    This sample app also uses the following CSS:

    .paging-button {
      visibility: hidden;
    }
    
    .video-content {
      width: 200px;
      height: 200px;
      background-position: center;
      background-repeat: no-repeat;
      float: left;
      position: relative;
      margin: 5px;
    }
    
    .video-title {
      width: 100%;
      text-align: center;
      background-color: rgba(0, 0, 0, .5);
      color: white;
      top: 50%;
      left: 50%;
      position: absolute;
      -moz-transform: translate(-50%, -50%);
      -webkit-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
    }
    
    .video-content:nth-child(3n+1) {
      clear: both;
    }
    
    .button-container {
      clear: both;
    }
    

Update a playlist

The code samples below are for an application that enables a user to create a private playlist and add videos to it. (You could, of course, modify the code so that it creates a publicly visible playlist or so that it checks a form value to determine whether the playlist is public or private.)

  • JavaScript (playlist_updates.js)

    The JavaScript code below performs the following functions:

    1. It enables the user to create a private playlist and then displays information about the newly created playlist.
    2. It enables the user to add a video to the playlist and displays the API response from that operation. Note that the JavaScript code supports the ability to specify the position where the video should start and stop playing, but the HTML below does not provide a way to specify those values.

    Again, you need to update the client ID in the auth.js file to run this code.

    // Some variables to remember state.
    var playlistId, channelId;
    
    // Once the api loads call a function to get the channel information.
    function handleAPILoaded() {
      enableForm();
    }
    
    // Enable a form to create a playlist.
    function enableForm() {
      $('#playlist-button').attr('disabled', false);
    }
    
    // Create a private playlist.
    function createPlaylist() {
      var request = gapi.client.youtube.playlists.insert({
        part: 'snippet,status',
        resource: {
          snippet: {
            title: 'Test Playlist',
            description: 'A private playlist created with the YouTube API'
          },
          status: {
            privacyStatus: 'private'
          }
        }
      });
      request.execute(function(response) {
        var result = response.result;
        if (result) {
          playlistId = result.id;
          $('#playlist-id').val(playlistId);
          $('#playlist-title').html(result.snippet.title);
          $('#playlist-description').html(result.snippet.description);
        } else {
          $('#status').html('Could not create playlist');
        }
      });
    }
    
    // Add a video id from a form to a playlist.
    function addVideoToPlaylist() {
      addToPlaylist($('#video-id').val());
    }
    
    // Add a video to a playlist.
    function addToPlaylist(id, startPos, endPos) {
      var details = {
        videoId: id,
        kind: 'youtube#video'
      }
      if (startPos != undefined) {
        details['startAt'] = startPos;
      }
      if (endPos != undefined) {
        details['endAt'] = endPos;
      }
      var request = gapi.client.youtube.playlistItems.insert({
        part: 'snippet',
        resource: {
          snippet: {
            playlistId: playlistId,
            resourceId: details
          }
        }
      });
      request.execute(function(response) {
        $('#status').html('<pre>' + JSON.stringify(response.result) + '</pre>');
      });
    }
    
  • HTML (playlist_updates.html)

    The HTML page below uses JQuery, along with the auth.js and playlist_updates.js JavaScript files shown above.

    <!doctype html>
    <html>
      <head>
        <title>Playlist Updates</title>
      </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 id="buttons">
          <button id="playlist-button" disabled onclick="createPlaylist()">Create a new Private Playlist</button>
          <br>
          <label>Current Playlist Id: <input id="playlist-id" value='' type="text"/></label>
          <br>
          <label>Video Id: <input id="video-id" value='GZG9G5txtaE' type="text"/></label><button onclick="addVideoToPlaylist()">Add to current playlist</button>
        </div>
        <h3>Playlist: <span id="playlist-title"></span></h3>
        <p id="playlist-description"></p>
        <div id="playlist-container">
          <span id="status">No Videos</span>
        </div>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="auth.js"></script>
        <script src="playlist_updates.js"></script>
        <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
      </body>
    </html>
    

The code samples below are for an application that executes a YouTube search for a specified query and then displays the API result.

  • JavaScript (search.js)

    The JavaScript code below executes a YouTube search for the specified query term and then populates a DOM element with the API response. Again, you need to update the client ID in the auth.js file to run this code.

    // Once the api loads call enable the search box.
    function handleAPILoaded() {
      $('#search-button').attr('disabled', false);
    }
    
    // Search for a given string.
    function search() {
      var q = $('#query').val();
      var request = gapi.client.youtube.search.list({
        q: q,
        part: 'snippet'
      });
    
      request.execute(function(response) {
        var str = JSON.stringify(response.result);
        $('#search-container').html('<pre>' + str + '</pre>');
      });
    }
    
  • HTML (search.html)

    The HTML page below uses JQuery, along with the auth.js and playlist_updates.js JavaScript files shown above.

    <!doctype html>
    <html>
      <head>
        <title>Search</title>
      </head>
      <body>
        <div id="buttons">
          <label> <input id="query" value='cats' type="text"/><button id="search-button" disabled onclick="search()">Search</button></label>
        </div>
        <div id="search-container">
        </div>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script src="auth.js"></script>
        <script src="search.js"></script>
        <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
      </body>
    </html>
    

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.