Querying Youtube API using C#

Posted in .NET 2.0 | Google API | YouTube at Thursday, December 20, 2007 10:40 PM UTC

This example shows how to use Google Data API to query and obtain videos from YouTube. There is also a downloadable zip file with the example in ASP.NET / C#.

  1. First of all, you need to download the Google Data APIs Client Libraries.
  2. Secondly, use the following namespaces:
    using Google.GData.Client;
    using Google.GData.Extensions;
    
  3. Use the service by querying by tag, or by search (you can also query related items, etc..):

    
        //by tag
        //feel free to change number of items, by there is a limit of 50, I believe. 
        //If you want to retreive more, you have to do a loop (retrieve 1-50, then 51 to 100, etc)
        protected void btoGo_Click(object sender, EventArgs e)
        {
            string url = "http://gdata.youtube.com/feeds/videos/-/" + this.txtTag.Text;
            AtomFeed myFeed = GetFeed(url, 1, 20);
            DisplayFeed(myFeed);        
        }
    
        //by search
        //feel free to change number of items, by there is a limit of 50, I believe. 
        //If you want to retreive more, you have to do a loop (retrieve 1-50, then 51 to 100, etc)
        protected void btoSearch_Click(object sender, EventArgs e)
        {
            string url = "http://gdata.youtube.com/feeds/videos?q=" + this.txtSearch.Text;
            AtomFeed myFeed = GetFeed(url, 1, 15);
            DisplayFeed(myFeed);
        }
    
    
  4. Use the following methods, or similars to get and display the Feed:

    /// 
        /// Create and returns and Google.GData.Client.AtomFee from url with the specific start and number of items
        /// 
        /// 
        /// 
        /// 
        /// 
        private static AtomFeed GetFeed(string url, int start, int number)
        {
            System.Diagnostics.Trace.Write("Conectando youtube at " + url);
            FeedQuery query = new FeedQuery("");
            Service service = new Service("youtube", "exampleCo");
            query.Uri = new Uri(url);
            query.StartIndex = start;
            query.NumberToRetrieve = number;
    
            AtomFeed myFeed = service.Query(query);
            return myFeed;
        }
    
        /// 
        /// Renders feed in example aspx page
        /// 
        /// 
        private void DisplayFeed(AtomFeed myFeed)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (AtomEntry entry in myFeed.Entries)
            {
                #region render each
                sb.Append("
    Title: "); sb.Append(entry.Title.Text); sb.Append("
    Categories: "); foreach (AtomCategory cat in entry.Categories) { sb.Append(cat.Term); sb.Append(","); } sb.Append(RenderVideoEmbedded(getIDSimple(entry.Id.AbsoluteUri))); sb.Append("
    Published on: "); sb.Append(entry.Published); #endregion } this.lblResults.Text = sb.ToString(); } private string RenderVideoEmbedded(string idSimple) { return string.Format("
    ", idSimple); }
Related resources:


Download example web site project in C#:
youtubeAPIExample.zip (65,91 KB)

kick it on DotNetKicks.com AddThis Social Bookmark Button

Wednesday, December 26, 2007 4:35:51 PM UTC
Great info.
What is the better way to retrieve the video´s thumbnail?

thanks
Tiago
Sunday, December 30, 2007 12:48:56 AM UTC
Hi Tiago,

As far as I know, there is not a public access to the thumbnail in the Google Data API. You may have to parse the description field (it is a chunk of HTML) to get the <img html element..

Hope it helps..

Iván
Wednesday, February 06, 2008 8:05:23 PM UTC
how do you get the description
Wednesday, March 26, 2008 12:39:54 PM UTC
Hello,

I can get a Playlist of a User and list all videos for one playlist?... like this: I get all Playlist from a username to a DropDownList, then I select one Playlist and show all videos.

Can help me to make this?

Regards,
LB
Lukas
Thursday, April 10, 2008 7:41:32 PM UTC
takes a long time for sime reason. and i cant access the dll's inside visual studio. i.e. leaves little room for modification. otherwise its a pretty neat example of a websevice
Thursday, April 17, 2008 1:25:00 AM UTC
Is there a way to convert the AtomFeed into a XmlDocument. The problem I am having is with &'s in the AtomFeed.

Thanks
James Arnott
Thursday, April 17, 2008 7:30:41 PM UTC
Hi James,

It has been a long time since I created the example... It is not fresh on mi mind. There should be a simple way to create a XmlDocument from any valid XML structure (and I assume the AtomFeed it is). I am sure there is a way to parse those entities.. Sorry I can not provide a defined way to go..
Friday, June 13, 2008 8:44:18 PM UTC
Nice work Ivan. I actually just got wind that YouTube provided an API for pulling video into your own site. I'm surprised at how simple this is to do. I noticed there wasn't any library support for .NET at http://code.google.com/apis/youtube/overview.html. I don't understand what the developer key is for? Didn't look like you used one here. It appears to be just using feeds. I'll have to read up on GData FeedQuery and Service objects or disassemble them to see whats going on there. Thanks again for the sample. Do you have any sites you like to share that have more information for us C# users?

Chuck
Monday, June 16, 2008 2:43:43 AM UTC
how i can check video on YouTube if it have ( Confirm Birth Date )
Hi , I'm Thanh
and i'm programmer (C#)
i use api in my app for get info from youtube (for downloading)

it's good work , but i can't get info if video have "Confirm Birth Date " OR No

how can i do that's Plz!
Monday, June 23, 2008 10:32:37 PM UTC
Do you have a sample for creating a playlist using YouTube API
k
Tuesday, June 24, 2008 6:25:09 AM UTC
Hey,
i am Ayaz Hussain sir help me out.
i m n Last semmestor of BCS-7th and i want to make a project and also a little bit easy i can't have any about my project. So i want to give me IDEA'S about project's name and so on

so Please ..........
i wait here for your kind reply..


ur Ayaz
Ayaz Hussain
Friday, November 07, 2008 7:10:54 AM UTC
Hi,

What does getIDSimple() in your sample code do?
Can you help me with it
rashida
Friday, November 07, 2008 9:29:13 AM UTC
getIDSimple() will parse the video URL ID provided by youtube and will give you something like "G5iaMbHuuxk", that I called simple ID
Tuesday, January 20, 2009 7:23:16 AM UTC
Thanks, for the detailed article and the code for searching videos on youtube.
Any how if someone wants the geIDSimple() funtion, here it is.

public string getIDSimple(string url)
{
string str ="http://gdata.youtube.com/feeds/videos/";

url = url.Remove(0, str.Length);
return url;
}
Ashraf
Tuesday, January 20, 2009 9:48:11 AM UTC
I am aware Google has recently published new and improved API's so stay tunned! (see their web site)
Friday, February 13, 2009 1:01:31 PM UTC

Thank You very much :)

so my search end here :)
zubair
Thursday, April 23, 2009 4:29:29 PM UTC
how to get the description, your atom feed do not have description hits , views and rating properties but it is in the feed, you are missing many infos.
Sunday, June 21, 2009 7:21:54 PM UTC
If anyone is trying to use more than one word in the search, for example instead of drums you want drum fills...try this

string[] keyWords = this.txtSearch.Text.Split(' ');
string url = "http://gdata.youtube.com/feeds/videos?q=";
string keys = string.Empty;

foreach (string k in keyWords)
{
if (keys.Length == 0)
keys = string.Format("{0}", k);
else
keys += string.Format("+{0}", k);
}

url += keys;

...


...
Friday, July 03, 2009 12:53:08 PM UTC
To use more than one word in the search, you don't need to loop through the search term HttpUtility.UrlEncode(searchTerm) will substitute ' ' by '+' as well.
Frank
Wednesday, January 27, 2010 11:17:42 PM UTC
Hello,

I think there is a simple way to query youtube API. There is no need to import third party Dll's. For .NET 3.5 you can use SyndicationFeed that is located in "System.ServiceModel.Syndication;" assembly

Code example (search on youtube):

var scrubbed = HttpUtility.UrlEncode(expression);
var reader = XmlReader.Create( string.Format("http://gdata.youtube.com/feeds/videos?q={0}", scrubbed));
var feed = SyndicationFeed.Load(reader);
foreach (SyndicationItem item in feed.Items)
{
System.Console.WriteLine("The title is {0} and the link to the video is : {1}",item.Title,item.Links[0].Uri);
}

Thank you,
Maricel
ymark
Thursday, January 28, 2010 9:47:46 AM UTC
Hi Maricel,

I am sure you are right. There has been a while since I don't look at the API and I know it has been greatly improved.
Don't forget guys to check last version on Google!!

Thanks!

ivan
All comments require the approval of the site owner before being displayed.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, em, i, strike, strong) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview

Yeap, the sponsors! :-)

On this page...

Tags

Calendar

<December 2007>
SunMonTueWedThuFriSat
2526272829301
2345678
9101112131415
16171819202122
23242526272829
303112345

Navigation

Archives

Recommended .NET blogs

The author

Iván Loire
Iván Loire (Zaragoza, Spain)

View Ivan Loire's profile on LinkedIn
Microsoft Certified Trainer
Send mail to the author(s) E-mail

Syndication

Feed Icon