Tuesday, July 17, 2012

How to consume YouTube video feed from C#

Before starting you should register developer key: https://code.google.com/apis/youtube/dashboard

Here is link to documentation: https://developers.google.com/youtube/2.0/developers_guide_protocol_audience

We will start by installing Google.GData.YouTube NuGet package:

PM> Install-Package Google.GData.YouTube
**Note** If you using MonoDevelop IDE, sorry but first you will have to download .NET library for the Google Data API manually from here

Let's create new console application project. In our example will fetch title and id of all uploaded videos of TobyGames user. Pay attention that we will use StartIndex and NumberToRetrieve on query object for result pagination. And here follows the source code of our example:

using System;
using Google.YouTube;
using Google.GData.Client;
using Google.GData.YouTube;

namespace YouTubeApiSample
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            var settings = new YouTubeRequestSettings ("API_YouTube", "YOUR_API_KEY_HERE");
            
            int index = 1;
            int pageSize = 9;

            while (true) {

                var request = new YouTubeRequest (settings);
                var query = new YouTubeQuery("http://gdata.youtube.com/feeds/api/users/windowsazure/uploads");
                
                query.OrderBy = "published";
                query.StartIndex = index;
                query.NumberToRetrieve = pageSize;

                Feed<Video> feed = null;

                try
                {
                    feed = request.Get<Video>(query);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error have occurred while retrieving data from YouTube: {0}", ex.Message);
                }
                
                if (feed != null && feed.Entries != null) {

                    int count = 0;
                    try
                    {
                        foreach (var entry in feed.Entries) {
                            Console.WriteLine("Video title: {0} -> Id: {1}", entry.Title, entry.Id);
                            count++;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error have occurred while retrieving data from YouTube: {0}", ex.Message);
                        break;
                    }

                    if (count < pageSize) {
                        Console.WriteLine("All data fetched!");
                        break;
                    }

                    index = index + count + 1;
                }
                else {
                    Console.WriteLine("Error have occurred while retrieving data from YouTube.");
                    break;
                }
            }
        }
    }
}