LearnDeveloping over the YouTube API with JSON

   
Avatar

Jake Rocheleau
writes on May 22, 2013

The process to understand API development is generally complicated but should become easier with practice. Social networks like Twitter and YouTube offer XML/RSS/JSON feeds without the requirement of an API key. However, other smaller networking websites like Instagram and Etsy will require developers to sign up for a new API key before allowing them to make requests from the server.

In this tutorial I want to demonstrate a really simple HTML/CSS/JS web application building over the YouTube API. This demo will list a number of YouTube channels which you may click and pull out all the latest videos, plus their related metadata such as views and comments. All of this dynamic page content will be handled via jQuery so you do not need to host anything on a web server. Check out my sample demo to get an idea of what we are building.

preview tutorial youtube api json demo javascript jquery

Live DemoDownload Source Code

Getting Started

I will skip a lot of the boring HTML so that we can focus more deeply on the YouTube response and how we handle this in JavaScript. The most important HTML section you should recognize is the navigation along with the inner videos content div. I have used specific IDs so that we can target each element and check whenever the user clicks a link, then display that content inside #videos.

    <nav id="usersnav">
      <ul>
        <li><a href="#gotreehouse">gotreehouse</a></li>
        <li><a href="#thenextweb">thenextweb</a></li>
        <li><a href="#TEDxTalks">TEDxTalks</a></li>
        <li><a href="#wearechange">wearechange</a></li>
        <li><a href="#RTAmerica">RTAmerica</a></li>
        <li><a href="#G4ZDTechTV2">G4ZDTechTV2</a></li>
        <li><a href="#NovaCrystallisDotCom">NovaCrystallisDotCom</a></li>
      </ul>
    </nav>
    
    <div id="videos">
      <!-- vids go here -->
    </div>

In order for the whole process to work we will need a copy of the latest jQuery library. My demo includes this file from within the ./js/ directory so you won’t need to re-download anything. Also I have kept my custom-written jQuery codes inside the index file instead of moving them to an external JS script. It would obviously be easier to do so when you are running this on a live website, but for my demo it is quicker to study these codes from within the same page.

Pulling Results with jQuery

The first step is to define a set of variables which we need in the script. Then we can handle a click event from the user which is interfacing with any of the navigation links. Each of the anchor elements is using an HREF value containing a hash symbol plus username we need. It is important that we stop this default href from loading by using e.preventDefault() and then pull the value out so we can get the YouTube feed results.

$(function(){
  $('#usersnav ul li a').on('click', function(e){
    e.preventDefault();
    var htmlString  = '<ul id="videoslisting">';
    var channelname = $(this).attr('href').substring(1);
    var ytapiurl    = 'http://gdata.youtube.com/feeds/api/users/'+channelname+'/uploads?alt=json&max-results=10';

The handy JavaScript substring() method will create a new string variable starting from the character marker 1(marker 0 is the first character). This removes our hash symbol so that we can now place the username into a generic API call which looks like this: http://gdata.youtube.com/feeds/api/users/CHANNELNAME/uploads?alt=json&max-results=10

The user’s channel name can be accessed to query YouTube and pull out their latest uploads. I am referencing a max results value of 10 and since we are not using pagination. I have not included any other callback methods, either. JSON is the response type we need so that way it’ll be easier parsing all this content inside jQuery.

Building a Loop

PHP and Rails and other programming languages often use logic loops to iterate through data patterns. While loops, for loops, do loops, and other common ideas are not as strict when you would compare them with JavaScript. However the methods for .parseJSON() and jQuery.each() offer the perfect system for looping through all of these results.

    $.getJSON(ytapiurl, function(data) {
      $.each(data.feed.entry, function(i, item) {                                
        var title    = item['title']['$t'];
        var videoid  = item['id']['$t'];
      
        var pubdate  = item['published']['$t'];
        var fulldate = new Date(pubdate).toLocaleDateString();
      
        var thumbimg = item['media$group']['media$thumbnail'][0]['url'];
        var tinyimg1 = item['media$group']['media$thumbnail'][1]['url'];
        var tinyimg2 = item['media$group']['media$thumbnail'][2]['url'];
        var tinyimg3 = item['media$group']['media$thumbnail'][3]['url'];
      
        var vlink    = item['media$group']['media$content'][0]['url'];
        var ytlink   = item['media$group']['media$player'][0]['url'];
        var numviews = item['yt$statistics']['viewCount'];
        var numcomms = item['gd$comments']['gd$feedLink']['countHint'];
      
        htmlString +='<li class="clearfix"><h2>' + title + '</h2>';
        htmlString +='<div class="videothumb"><a href="' + ytlink + '" target="_blank"><img src="' + thumbimg + '" width="480" height="360"></a></div>';
        htmlString +='<div class="meta"><p>Published on <strong>' + fulldate + '</strong></p><p>Total views: <strong>' + commafy(numviews) + '</strong></p><p>Total comments: <strong>'+ numcomms +'</strong></p><p><a href="'+ ytlink +'" class="external" target="_blank">View on YouTube</a></p><p><a href="'+ vlink +'" class="external" target="_blank">View in Fullscreen</a></p><p><strong>Alternate Thumbnails</strong>:<br><img src="'+ tinyimg1 +'"> <img src="' + tinyimg2 + '"> <img src="'+ tinyimg3 +'"></p></div></li>';
      }); // end each loop
    
      $('#videos').html(htmlString + "</ul>");
    }); // end json parsing

This code block seems very large but the majority of the content is generating variable names. YouTube will return a lot more information than we need so it would be foolish to create an array containing all the keys. Instead we should make new variables strictly for the content which will be used inside the layout, and then we create a final HTML string to return to the browser.

Each variable block will contain an important section of the final display. We will need the video title, original publishing date, the full-size thumbnail along with each of the 3 mini-thumbs, direct video URL, view count, and also the comments count. The HTML is displayed using an unordered list of items which finishes by applying the HTML content into the #videos container. This is easily accomplished by using the jQuery .html() method.

Parsing & Formatting Numbers

One other final point I’d like to bring up is the ability to parse through each view counter. Return data for videos which have over 1000 views will not include the comma between each set of 3 numbers. I found an excellent solution on Stack Overflow written using pure JavaScript. The function name is commafy() which is wrapped around each of the view count numbers. This will check if the digits are higher than 4 and automatically place a comma where it should be.

These codes are wonderful to use in any number of JavaScript solutions. The questions and solutions on Stack Overflow are always helpful with these kinds of matters. I think it is worth noting that you could write a much simpler function using jQuery or handling this method inside the .each() loop. But if everything is kept inside a separate file then you may not worry as much about the syntax or number of lines.

preview tutorial youtube api json demo javascript jquery

Live DemoDownload Source Code

Final Thoughts

Many developers who are not familiar with JSON should hit Google and read a few articles on the subject. It is basically JavaScript code which is written in a certain way so that the syntax can be read as data-value pairs. YouTube can present JSON data from their server and using jQuery it is possible to organize this data into the page dynamically. I hope this tutorial may prove useful to anybody who has been interested in developing over YouTube’s API, or any API for that matter. Feel free to download a copy of my demo and see if you can implement a similar method elsewhere in your own projects.

GET STARTED NOW

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Get Started

6 Responses to “Developing over the YouTube API with JSON”

  1. How to make my second blog my default one on Tumblr?

  2. hey
    your code is not working i am running it from local host so can u please help me out

  3. Great!

    I’m new to $.each, so I have to ask why you used data.feed.entry as the first argument. Presumably it’s to save you from typing out everything each time you declare a variable?

    How would this code look if your argument was simply ‘data’? I tried redoing the code this way but my pattern is off:

    var title = data.feed.entry[item].title.$t; doesn’t work.

  4. Sunil on May 31, 2013 at 1:15 pm said:

    Elegant and informative site build using Youtube API. http://914videos.com

  5. diegoRomero89 on May 26, 2013 at 7:08 pm said:

    Great I’d love to delevelop an app that uses youtube videos, even though im not sure how the site can stand the stress of the process 😐 probably I just use a testing software like agileload

Leave a Reply

You must be logged in to post a comment.

man working on his laptop

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Start a Free Trial
woman working on her laptop