YouTube Data API via JSON: embedding videos in your site

The YouTube Data API normally outputs information about videos, playlists, subscriptions, user profiles and more in the format of Atom feeds. However, due to cross-domain restrictions, it's not very easy to retrieve and parse XML data on remote servers from within JavaScript. Because of this, most Google Data APIs also provide JSON as an alternative output format. JSON is short for JavaScript Object Notation and enables cross-domain retrieval of data from the Data APIs.

Capabilities

Read-only unauthenticated access to public data served from the YouTube Data API.

Requirements

Nothing! Well, a browser and a web server that'll serve static HTML

How does it work?

You only need two things:

These bits of information are combined together to create a <script> tag. An example:

<script 
    type="text/javascript" 
    src="http://gdata.youtube.com/feeds/users/GoogleDevelopers/uploads?alt=json-in-script&format=5&callback=showMyVideos">
</script>

Adding this tag to your page will retrieve a feed of the embeddable videos belong to the user GoogleDevelopers and, after the feed is retrieved, call the showMyVideos function with the data returned.

What's the callback function look like?

The callback function can be really simple or very complex depending on what you would like to do with the data returned. Let's start off with a simple example that creates an unordered list of the videos in the GoogleDevelopers account.

function showMyVideos(data) {
  var feed = data.feed;
  var entries = feed.entry || [];
  var html = ['<ul>'];
  for (var i = 0; i < entries.length; i++) {
    var entry = entries[i];
    var title = entry.title.$t;
    html.push('<li>', title, '</li>');
  }
  html.push('</ul>');
  document.getElementById('videos').innerHTML = html.join('');
} 

The complete picture

Demo:

Source:

<html>
<head>
<title>My Videos</title>
<script type="text/javascript">
function showMyVideos(data) {
  var feed = data.feed;
  var entries = feed.entry || [];
  var html = ['<ul>'];
  for (var i = 0; i < entries.length; i++) {
    var entry = entries[i];
    var title = entry.title.$t;
    html.push('<li>', title, '</li>');
  }
  html.push('</ul>');
  document.getElementById('videos').innerHTML = html.join('');
}
</script>
</head>
<body>
<div id="videos" />
<script 
    type="text/javascript" 
    src="http://gdata.youtube.com/feeds/users/GoogleDevelopers/uploads?alt=json-in-script&format=5&callback=showMyVideos">
</script>
</body>
</html>

Making it more attractive

YouTube is all about videos. Videos should contain pictures and sound-- so why are we just outputting a boring list of videos? You have a good point, so let's jazz this up a bit!

The following example uses the value of the MediaRSS thumbnails, MediaRSS content and MediaRSS player. These values are in each video entry as media$group.media$thumbnail[] and media$group.media$player.

Demo:

Source:

<html>
<head>
<title>My Videos</title>
<style>
.titlec {
  font-size: small;
}
ul.videos li {
  float: left;
  width: 10em;
  margin-bottom: 1em;
}
ul.videos
{
  margin-bottom: 1em;
  padding-left : 0em;
  margin-left: 0em;
  list-style: none;
}
</style>
<script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script>
<script type="text/javascript">
function loadVideo(playerUrl, autoplay) {
  swfobject.embedSWF(
      playerUrl + '&rel=1&border=0&fs=1&autoplay=' + 
      (autoplay?1:0), 'player', '290', '250', '9.0.0', false, 
      false, {allowfullscreen: 'true'});
}

function showMyVideos2(data) {
  var feed = data.feed;
  var entries = feed.entry || [];
  var html = ['<ul class="videos">'];
  for (var i = 0; i < entries.length; i++) {
    var entry = entries[i];
    var title = entry.title.$t.substr(0, 20);
    var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
    var playerUrl = entries[i].media$group.media$content[0].url;
    html.push('<li onclick="loadVideo(\'', playerUrl, '\', true)">',
              '<span class="titlec">', title, '...</span><br /><img src="', 
              thumbnailUrl, '" width="130" height="97"/>', '</span></li>');
  }
  html.push('</ul><br style="clear: left;"/>');
  document.getElementById('videos2').innerHTML = html.join('');
  if (entries.length > 0) {
    loadVideo(entries[0].media$group.media$content[0].url, false);
  }
}
</script>
</head>
<body>
<div id="playerContainer" style="width: 20em; height: 180px; float: left;">
    <object id="player"></object>
</div>
<div id="videos2"></div>
<script 
    type="text/javascript" 
    src="http://gdata.youtube.com/feeds/users/GoogleDevelopers/uploads?alt=json-in-script&callback=showMyVideos2&max-results=30">
</script>
</body>
</html>

On your own

The easiest way to get started using the JSON output from the YouTube Data API is to copy and paste one of the examples above and modify it to fit your needs. While the JSON output from the API looks very similar to the XML output, it's still often helpful to use a debugger such as Firebug to look at the JSON returned from the server and find the data you need for your application. If you have any questions about how to use the JSON output feature, please post a message on the YouTube APIs developer forum.

The example above currently includes the videos from the GoogleDevelopers YouTube channel. You can easily change the source by changing the script tag's src attribute, or by adding a function that does dynamic script injection. Here's some example script tags:

30 videos which match the word 'puppy':

<script 
    type="text/javascript" 
    src="http://gdata.youtube.com/feeds/api/videos?q=puppy&alt=json-in-script&callback=showMyVideos2&max-results=30&format=5">
</script> 

Most viewed videos this week:

<script 
    type="text/javascript" 
    src="http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed?time=this_week&alt=json-in-script&callback=showMyVideos2&max-results=30&format=5">
</script> 

Most viewed videos in Japan today:

<script 
    type="text/javascript" 
    src="http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_viewed?time=today&alt=json-in-script&callback=showMyVideos2&max-results=30&format=5">
</script> 

Videos which are tagged with the word 'goldendoodle':

<script 
    type="text/javascript" 
    src="http://gdata.youtube.com/feeds/api/videos/-/goldendoodle?alt=json-in-script&callback=showMyVideos2&max-results=30&format=5">
</script> 

For more information on the types of feeds availalble, please see the Reference Guide.

A more advanced YouTube Video Browser allows the user to browse thumbnails of related videos, select standard feeds and query the feeds using search terms.

Want something a little easier?

The AJAX Search Video Bar allows you to embed a bar of your YouTube videos onto your site with ease.

Demo:

Loading...

Source:

Head over to the Video Bar wizard and configure some of the Video Bar parameters. It'll generate the code for you.

Here's what the code for the bar above looks like:

<html>
<head>
<title>My Videos</title>
</head>
<body>
  <!--
  // The Following div element will end up holding the actual videobar.
  // You can place this anywhere on your page.
  -->
  <div id="videoBar-bar">
    <span style="color:#676767;font-size:11px;margin:10px;padding:4px;">Loading...</span>

  </div>

  <!-- Ajax Search Api and Stylesheet
  // Note: If you are already using the AJAX Search API, then do not include it
  //       or its stylesheet again
  -->
  <script src="http://www.google.com/uds/api?file=uds.js&v=1.0&source=uds-vbw"
    type="text/javascript"></script>
  <style type="text/css">
    @import url("http://www.google.com/uds/css/gsearch.css");
  </style>

  <!-- Video Bar Code and Stylesheet -->
  <script type="text/javascript">
    window._uds_vbw_donotrepair = true;
  </script>
  <script src="http://www.google.com/uds/solutions/videobar/gsvideobar.js?mode=new"
    type="text/javascript"></script>
  <style type="text/css">
    @import url("http://www.google.com/uds/solutions/videobar/gsvideobar.css");
  </style>
  <style type="text/css">
    .playerInnerBox_gsvb .player_gsvb {
      width : 320px;
      height : 260px;
    }
  </style>
  <script type="text/javascript">
    function LoadVideoBar() {
    var videoBar;
    var options = {
        largeResultSet : !true,
        horizontal : true,
        autoExecuteList : {
          cycleTime : GSvideoBar.CYCLE_TIME_MEDIUM,
          cycleMode : GSvideoBar.CYCLE_MODE_LINEAR,
          executeList : ["ytchannel:GoogleDevelopers"]
        }
      }
    videoBar = new GSvideoBar(document.getElementById("videoBar-bar"),
                              GSvideoBar.PLAYER_ROOT_FLOATING,
                              options);
    }
    // arrange for this function to be called during body.onload
    // event processing
    GSearch.setOnLoadCallback(LoadVideoBar);
  </script>
<!-- ++End Video Bar Wizard Generated Code++ -->
</body>
</html>