I noticed the YouTube site has an API so I've been playing around with it. Here's an example of how to call a YouTube API from C# to list the videos relating to golf.
protected void Page_Load(object sender, EventArgs e)
{
//GS - Empty the buffer of anything written already
Response.Clear();
//GS - Call the YouTube api to list all videos for a tag
string uri = "http://www.youtube.com/api2_rest?";
uri += "method=youtube.videos.list_by_tag";
uri += "&dev_id=YOUR_KEY_HERE";
uri += "&tag=golf";
XPathDocument xpd = null;
try
{
xpd = new XPathDocument(uri);
}
catch (XmlException xe)
{
Response.Write("The following xml error occurred: " +
xe.Message);
Response.End();
return;
}
//GS - Create a navigator
XPathNavigator xpn = xpd.CreateNavigator();
//GS - Handle any errors
XPathNodeIterator xniError = xpn.Select(@"/ut_response");
xniError.MoveNext();
if(xniError.Current.GetAttribute("status",String.Empty)=="fail")
{
//GS - Get the error
string expression = "/ut_response/error/description";
string errorText = xpn.SelectSingleNode(expression).InnerXml;
//GS - Inform the user
Response.Write("The YouTube API reported the " +
"following error: " + errorText);
Response.End();
return;
}
//GS - No errors so get all the video elements returned
try
{
XPathNodeIterator xni =
xpn.Select(@"/ut_response/video_list/video");
//GS - Write out a heading
Response.Write("<h1>Golfing Videos</h1>");
//GS - Start an unordered list
Response.Write("<ul>");
//GS - For each video write thumb nail image and title
string title = "";
string url = "";
string thumbUrl = "";
while (xni.MoveNext())
{
title = xni.Current.SelectSingleNode(@"title").InnerXml;
url = xni.Current.SelectSingleNode(@"url").InnerXml;
thumbUrl =
xni.Current.SelectSingleNode(@"thumbnail_url").InnerXml;
Response.Write("<li>");
Response.Write("<img height='75' width='75' src='" +
thumbUrl + "' />");
Response.Write("<br />");
Response.Write("<a href='" + url + "'>" + title + "</a>");
Response.Write("<p />");
Response.Write("</li>");
}
//GS - Close the unordered list
Response.Write("</ul>");
//GS - Write to the browser
Response.End();
}
catch (XPathException xpe)
{
Response.Write("The following XPath exception occurred: "
+ xpe.Message);
Response.End();
return;
}
}
Tags: YouTube, Mashup, C#