YouTube Data API for ActionScript 3.0 : First Steps

This article was written and submitted by an external developer. The YouTube APIs and Tools team thanks Martin Legris for his time and expertise.


Martin Legris
March 2008

Introduction

In this tutorial I will show you how, with under 10 lines of actual AS3 code, you can retrieve the most popular videos on YouTube for the last day, week, month or all_time. You can get any of the standard feeds:

  • Most Viewed
  • Most Recent
  • Most Discussed
  • Most Linked
  • Most Responded
  • Recently Featured
  • Top Rated
  • Top Favorited
  • Videos for mobile phones

The library used in this example is hard-typed throughout, meaning once you have received the data, you can use the auto-completion feature in IDEs such as FlashDevelop, Flex IDE, Eclipse w/FDT, IntelliJ Idea, and more.

Important Resources

Before we start, here is the list of resources available to you - the AS3 developer interested in using data from the YouTube API.

Digging In

Making your first request

The code which follows is fairly well commented. I will, however, describe the functionality a bit before I dig in. The starting point for all requests is a class called YouTubeClient. This class is a singleton to which you get access doing the following:

// first you import it
import ca.newcommerce.youtube.webservice.YouTubeClient;

// then you get a reference to it
var client:YouTubeClient = YouTubeClient.getInstance();

Now we are ready to make a request:

client.getStandardFeed(YouTubeClient.STD_TOP_RATED, 
                                 YouTubeClient.TIME_MONTH,
                                 1, 
                                 10);

I just requested the top rated videos over the last month, results 1 to 10 (note that there is a maximum of 50 results per call). Easy!

Handling the results

Now, how do I access these results? Since the REST type webservice paradigm is asynchronous, it is easier to use events to handle the results instead of halting the code while the results are fetched. In this case, we need to declare an event listener for the StandardVideoFeedEvent.STANDARD_VIDEO_DATA_RECEIVED event. Our function will be called every time the YouTubeClient receives a response for a Standard Feed.

client.addEventListener(StandardVideoFeedEvent.STANDARD_VIDEO_DATA_RECEIVED, 
                        doVideosReceived);

The function to be called will be doVideosReceived. It will take one parameter, a variable of type StandardVideoFeedEvent. This follows the standard in AS3. Let us declare it, and make it trace a few things concerning the videos we received. We will trace to standard output:

  • the video's title,
  • the URL of the SWF to embed the video,
  • the view count,
  • the comment count,
  • the video duration,
  • and the author's name.
function doVideosReceived(evt:StandardVideoFeedEvent):void
{
	// get a reference to the feed containing the videos
	var feed:VideoFeed = evt.feed;
	
	// variable to hold each video retreived on the feed
	var video:VideoData;
	
	// iterate through the availabe results
	while(video = feed.next())
	{
		  // trace a newline followed by the video title
		  trace("\nvideo title:"+video.title);
		  
		  // trace the url to use to embed the flash player with this video playing in it..
		  trace("player url:"+video.swfUrl);
		  
		  // the view count
		  trace("viewCount:"+video.viewCount);
		  
		  // the comment count
		  trace("commentCount:"+video.commentCount);
		  
		  // the duration
		  trace("duration:"+video.duration);
		  
		  // the author
		  trace("author:"+video.authors.first().name);
	}
}

A few notes about the library & feeds

Almost all events have a .feed property. ProfileEvent is the one exception, it has a .profile property instead, as there is only one record returned by this call.

There are many types of feeds - they all implement the following methods:

  • first() -- retrieve the first record and point to it
  • next() -- retrieve the next available record
  • last() -- retrieve the last record and point to it
  • previous() -- retrieve the previous record on the feed
  • getAt() -- get a result at a specific position
  • count() -- the number of results available for this feed, not the same as totalResults

When you get to the end of the results, next() returns null. Same thing for previous, once you get to the first result, the next call to previous() will return null.

Note that data inside of feeds (e.g. categories) are wrapped inside of Iterators, so you can use the same functions to walk through available categories.

Complete Source Code

The following is the full source code for this example. You can download a zip which contains everything you need to run the example inside of Flash CS3, however, it is best to update the library in case we fixed bugs or update features. You can download the library by clicking here.

package
{
    // first import dependencies (You can be more specific than this if you want)
    import ca.newcommerce.youtube.data.*;
    import ca.newcommerce.youtube.events.*;
    import ca.newcommerce.youtube.feeds.*;
    import ca.newcommerce.youtube.iterators.*;
    import ca.newcommerce.youtube.webservice.YouTubeClient;

    public class ytTest()
    {
        // some class variables
        protected var _ws:YouTubeClient;
        protected var _requestId:Number;

        public function ytTest()
        {
            // now inside of an init function
            _ws = YouTubeClient.getInstance();

            // register to list to the events you are interested in
            _ws.addEventListener(StandardVideoFeedEvent.STANDARD_VIDEO_DATA_RECEIVED, doVideosReceived);

            // do your call.. get the Top Rated videos for the last month
            // results 1 to 10; it returns a requestId
            _requestId = _ws.getStandardFeed(YouTubeClient.STD_TOP_RATED,
                                                YouTubeClient.TIME_MONTH, 
                                                1,
                                                10);
        }

        protected function doVideosReceived(evt:StandardVideoFeedEvent):void
        {

            // get a reference to the feed containing the videos
            var feed:VideoFeed = evt.feed;

            // variable to hold each video retrieved on the feed
            var video:VideoData;

            while(video = feed.next())
            {
                // trace a newline followed by the video title
                trace("\nvideo title:"+video.title);

                // trace the swf URL (used for embedding)
                trace("player url:"+video.swfUrl);

                // the view count
                trace("viewCount:"+video.viewCount);

                // the comment count
                trace("commentCount:"+video.commentCount);

                // the duration
                trace("duration:"+video.duration);

                // the author
                trace("author:"+video.authors.first().name);
             }

        }

    }

}

Conclusion

Although this article barely touches the tip of the iceberg, it will give you a good idea of how simple it is to query the YouTube Data API using this library. Since I've taken the time to hard-type everything, it is a breeze to explore what data is available on each feed response. It doesn't support the new write and upload functionality yet, but if you want to contribute to the library, visit the project page.

Author Bio


AUTHORNAME

Martin Legris boasts 12 years of active software development. Today, he mainly concentrates on user interface research and his favorite tool is Flash w/ ActionScript. Check out his blog at blog.martinlegris.com and website (can be outdated) at www.newcommerce.ca.

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 United States License.