How to embed videos in your site via YouTube Data API?


YouTube Data API via JSON: embedding videos in your site

Video_list

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 theGoogleDevelopers 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:

  • Google+ Developers Live: Sign-in Best Practices Episode #2
  • Implementing Content Experiments in Google Analytics
  • Mobile Web Thursdays: Developer Workflow
  • GDL Italia – Offline HTML5 Agenda (parte 4)
  • Skia Path Ops : High Performance Set Operations for Geometry
  • DART, Una visión de los nuevos estilos de programacion
  • Chrome Apps: In App Payments
  • YouTube Developers Live: Introduction to Invideo Programming
  • AdWords API Intro
  • Google+ Sign-In Best Practices: Greeting the user and reflecting their profile.
  • Google Drive SDK: Floreysoft!
  • Maps Shortcuts: Driving Geometry Overlays with D3.js
  • Developing on a Chromebook with Codenvy
  • Google Compute Engine – Ten Minute Test Drive: Set Up your own Web Server
  • Chrome Mobile: StackOverflow Office Hours
  • GDL Italia – Google Cloud Platform in the real world
  • GDL Italia – Google Prediction API, machines that learn
  • Cloud Platform, la computación en la nube desde Compute Engine
  • All about Chrome Academy
  • Chrome Apps Office Hours: Behind Reditr
  • Apps Script Crash Course: Import/Export Apps Script Code
  • Off the Charts: Campaigns and Attribution for Android Applications using Google Analytics
  • Chrome Mobile: WebRTC
  • GDL Italia – Google Cloud Storage overview
  • GDL Italia – Google Compute Engine overview

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[] andmedia$group.media$player.

Demo:

  • Google+ Developers L…
  • Implementing Content…
  • Mobile Web Thursdays…
  • GDL Italia – Offline…
  • Skia Path Ops : High…
  • DART, Una visión de …
  • Chrome Apps: In App …
  • YouTube Developers L…
  • AdWords API Intro…
  • Google+ Sign-In Best…
  • Google Drive SDK: Fl…
  • Maps Shortcuts: Driv…
  • Developing on a Chro…
  • Google Compute Engin…
  • Chrome Mobile: Stack…
  • GDL Italia – Google …
  • GDL Italia – Google …
  • Cloud Platform, la c…
  • All about Chrome Aca…
  • Chrome Apps Office H…
  • Apps Script Crash Co…
  • Off the Charts: Camp…
  • Chrome Mobile: WebRT…
  • GDL Italia – Google …
  • GDL Italia – Google …
  • YouTube API, la ener…
  • The Independent Web …
  • Google Developers Li…
  • Escaping the Passwor…
  • GDL Italia – Mobile …

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>'];
  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>', 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;">

</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:

powered by

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>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s