The YouTube Data API allows client applications to retrieve and update YouTube content in the form of Google Data API feeds. Your client application can use the YouTube Data API to fetch video feeds, comments, responses, and playlists, as well as query for videos that match particular criteria. You can also use the API to make authenticated requests to modify this information and to upload new video content to the site.
In addition to providing some background on the capabilities of the YouTube Data API, this document provides examples for interacting with the API using the .NET client library. For help setting up the .NET client library, check out the Getting Started Guide.
If you're interested in understanding more about the underlying protocol that the .NET client library uses to interact with YouTube, see the protocol guide.
This document is intended for programmers who want to write client applications that can interact with YouTube using the .NET client library. It provides a series of examples of basic data API interactions.
For YouTube Data API reference information, including expected latencies for data updates, please see the reference guide.
This document assumes that you understand the general ideas behind the Google Data APIs protocol, and that you are familiar with the .NET framework and know C#.
For reference information about the .NET classes and methods, see the .NET client library API reference.
This document contains the following sections:
The Authentication section describes the two different authentication methods available for associating API operations with a specific user account. This section also outlines the differences between authentication for the YouTube Data API and other Google Data APIs. Throughout this document, the explanations of specific API functions will clearly indicate whether the function requires user authentication. In general, all requests that modify video or feed data need to be authenticated. Read-only requests to retrieve public videos do not require authentication.
The Understanding video feeds and entries section provides a sample API response and explains how to extract information about a single video from a list of videos or a set of search results. This section also explains how to access metadata about a specific video entry.
The Retrieving and searching for videos section explains how to fetch a list of videos. The YouTube Data API defines several types of standard feeds, such as top-rated or most-viewed videos. This section explains how also to retrieve a list of videos uploaded by a specific user or a list of related videos. Finally, this section explains how to use the API to let users search through YouTube's video library for videos matching specific search terms or categories.
The Uploading videos section briefly explains two ways that you can allow users to upload videos to YouTube from your application. This section also explains how to let users delete videos from your application. These solutions are explained in more detail in the Protocol Guide. You may need to let users upload videos to use certain other API functions. For example, the API provides a function for adding a video response to a video. If the user is uploading a new video as a video response, then your client will need to follow the video uploading instructions to add the video to YouTube before identifying the new video as a response.
The Updating and deleting videos section describes how to use the API to update information about a YouTube video. It also describes how a video can be removed using the API.
The Using community features section describes API functions that allow your users to interact with YouTube videos. These functions explain requests for posting a rating, comment, video response or complaint to an existing video. You can also use the API to retrieve lists of video comments or video responses or to delete a video response.
The Saving and collecting videos section explains how to use the API to access, create and update favorite videos, video playlists and subscriptions to YouTube channels. It also explains how to modify video playlists and favorites by adding and removing videos.
The Enabling user interaction section explains how to use the API to retrieve and update user profiles. This section also explains how to retrieve, add, update and delete user contacts as well as how to retrieve, send and delete messages.
For help setting up the .NET client library, check out the Getting Started Guide.
The .NET client library requires the .NET 2.0 runtime. After downloading the client library, you will find the DLLs that you need to get started in the distribution's Redist
subdirectory.
To compile the example snippets provided in this document into your own code, you will need to use the following using
statements:
using Google.GData.Client; using Google.GData.Extensions; using Google.GData.YouTube; using Google.GData.Extensions.MediaRss; using Google.YouTube;
The .NET client library can be used to retrieve public feeds or to execute authenticated operations. All public feeds are read-only and do not require any authentication. Authenticated operations, on the other hand, include the retrieval of private feeds, such as a user's inbox feed, as well as write, upload, update and delete operations. You will need to sign up for a developer key to be able to execute authenticated operations.
You can authenticate requests using either AuthSub proxy authentication or ClientLogin username/password authentication.
To perform any operation using the YouTube API, you create a YouTubeRequestSettings
object, which specifies the authentication information and authentication scheme to be used. With that object, you then create a YouTubeRequest
object that you will use to actually perform the operations. (If you do not specify authentication information when creating the YouTubeRequestSettings
object, then you will only be able to use the YouTubeRequest
object to perform operations that do not require authentication.)
YouTubeRequestSettings settings = new YouTubeRequest("example app", clientID, developerKey); YouTubeRequest request = new YouTubeRequest(settings);
Note: Please visit http://code.google.com/apis/youtube/dashboard/ to obtain a developer key and client ID.
Please see the Protocol Guide and the authentication documentation for Google Data APIs for more information about AuthSub and ClientLogin.
AuthSub proxy authentication enables web applications to authenticate users to their YouTube accounts without having to access the user's YouTube username and password. You should use AuthSub authentication if you are building a web application that will let users link videos, comments, ratings, contacts or other information to their own YouTube accounts.
When a user visits your application for the first time, the user will not yet have been authenticated to use your application to access Google services. To authenticate the user, you need to display a link that points the user to a Google login page. After the user logs in, she can authorize your application to use the API to access her account. Google will then redirect the user back to a URL specified in your authentication request. The redirect will include a single-use token that your application can use to execute an API operation.
The following sample code constructs an AuthSub request URL. The code retrieves a nonsecure token that will be exchanged for a session token, which can then be used multiple times.
Note that the scope
for the YouTube API is http://gdata.youtube.com
.
authSubUrl = AuthSubUtil.getRequestUrl(next, scope, secure, session);
The Using AuthSub with the .NET Client Library article explains how to authenticate users with AuthSub in more detail. The following example demonstrates how to submit an AuthSub authentication request:
YouTubeRequestSettings settings = new YouTubeRequestSettings("example app", clientID, developerKey, (String) SessionToken); YouTubeRequest request = new YouTubeRequest(settings);
Note: The service name for the YouTube Data API is youtube
.
ClientLogin authentication is used in installed applications that store the user's email address (username) and password. To use ClientLogin authentication,
create a YouTubeRequestSettings
object that specifies your login credentials and then pass that object as a parameter when creating a new YouTubeRequest
object.
Note: ClientLogin authentication should not be used in Web applications, which should use AuthSub authentication instead.
The following code demonstrates how to use ClientLogin to authenticate a user.
Note that your authentication request must specify a clientID
and developerKey
, both of which are specified in the sample code, to retrieve private feeds, upload videos, or submit API requests for write operations. Please visit http://code.google.com/apis/youtube/dashboard to obtain a developer key and client ID.
YouTubeRequestSettings settings = new YouTubeRequestSettings("example app", clientID, developerKey, username, password); YouTubeRequest request = new YouTubeRequest(settings);
Please refer to the developer's guide for more detailed information about the AuthSub and ClientLogin mechanisms.
The YouTube Data API provides several video feeds that represent lists of videos, such as standard feeds, uploads, subscriptions, and favorite videos. The URL for each feed is documented in the reference guide.
Many feeds in the YouTube API consist of video entries. These feeds can be modeled most simply as VideoFeed
objects, each of which contains a number of YouTubeEntry
objects. Each video entry corresponds to exactly one YouTube video and contains information about that video.
The following code retrieves a video feed and then prints information about each entry in the feed:
Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl)); printVideoFeed(videoFeed); static void printVideoFeed(Feed<Video> feed) { foreach (Video entry in feed.Entries) { printVideoEntry(entry); } }
The Retrieving and searching for videos section describes different types of video feeds and provides the URLs and instructions for retrieving those feeds.
Each entry in a video feed contains a link
element for which the rel
attribute value is self
. This tag identifies the URL for a feed of information about that particular video. The URL has the following format:
http://gdata.youtube.com/feeds/api/videos/videoID
The following code retrieves a Video
object, which corresponds to a particular YouTube video, and then prints the metadata for the video:
Uri videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/videos/ADos_xW4_J0"); Video video = request.Retrieve<Video>(videoEntryUrl); printVideoEntry(videoEntry);
A Video
object, which corresponds to an entry in an Atom feed, contains many different pieces of metadata about a video, ranging from video player URLs to thumbnail images to details like the video's duration and keywords.
The following code demonstrates how to print a variety of details about a video.
For a complete list of all of the information that a YouTubeEntry
object contains, please refer to the <entry>
tag definition in the API Reference Guide. Specifically, refer to the <entry>
tag's subtags for retrieving a video entry.
static void printVideoEntry(Video video) { Console.WriteLine("Title: " + video.Title); Console.WriteLine(video.Description); Console.WriteLine("Keywords: " + video.Keywords); Console.WriteLine("Uploaded by: " + video.Uploader); if (video.YouTubeEntry.Location != null) { Console.WriteLine("Latitude: " + video.YouTubeEntry.Location.Latitude); Console.WriteLine("Longitude: " + video.YouTubeEntry.Location.Longitude); } if (video.Media != null && video.Media.Rating != null) { Console.WriteLine("Restricted in: " + video.Media.Rating.Country); } if (video.IsDraft) { Console.WriteLine("Video is not live."); string stateName = video.Status.Name; if (stateName == "processing") { Console.WriteLine("Video is still being processed."); } else if (stateName == "rejected") { Console.Write("Video has been rejected because: "); Console.WriteLine(video.Status.Value); Console.Write("For help visit: "); Console.WriteLine(video.Status.Help); } else if (stateName == "failed") { Console.Write("Video failed uploading because:"); Console.WriteLine(video.Status.Value); Console.Write("For help visit: "); Console.WriteLine(video.Status.Help); } if (video.ReadOnly == false) { Console.WriteLine("Video is editable by the current user."); } if(video.RatingAverage != -1) { Console.WriteLine("Average rating: " + video.RatingAverage); } if (video.ViewCount != -1) { Console.WriteLine("View count: " + video.ViewCount); } Console.WriteLine("Thumbnails:"); foreach (MediaThumbnail thumbnail in video.Thumbnails) { Console.WriteLine("\tThumbnail URL: " + thumbnail.Url); Console.WriteLine("\tThumbnail time index: " + thumbnail.Time); } Console.WriteLine("Media:"); foreach (Google.GData.YouTube.MediaContent mediaContent in video.Contents) { Console.WriteLine("\tMedia Location: " + mediaContent.Url); Console.WriteLine("\tMedia Type: " + mediaContent.Format); Console.WriteLine("\tDuration: " + mediaContent.Duration); } }
Note: For more information about how to generate the information required to embed a video with a player in your page please refer to the protocol guide.
You can determine whether the currently authenticated user is the owner of a particular video entry by calling the EditLink
method on that entry. The sample code below demonstrates how to determine whether a video entry is editable.
if (video.ReadOnly == false) { Console.WriteLine("Video is editable by the current user."); }
The YouTube Data API provides standard feeds selected based on a variety of criteria. Standard feeds are sitewide rather than user-specific. They contain lists of videos that either reflect YouTube user behavior, such as top-rated and most viewed video feeds, or were selected by YouTube staff, such as recently featured and mobile video feeds. Standard feeds are updated every few minutes.
The URLs for all standard feeds have the following format:
http://gdata.youtube.com/feeds/api/standardfeeds/FEED_IDENTIFIER
The following table lists the standard feeds available through the YouTube Data API.
The YouTubeQuery
object also has constants for all of these feeds.
Feed Name | Feed Identifier |
---|---|
Most Viewed | most_viewed |
Top Rated | top_rated |
Recently Featured | recently_featured |
Watch On Mobile | watch_on_mobile |
Most Discussed | most_discussed |
Top Favorites | top_favorites |
Most Responded | most_responded |
Most Recent | most_recent |
You can also retrieve region-specific standard feeds and category-specific standard feeds by specifying either a regionID, a category name, or both in the feed URL. The URL for a region- and category-specific standard feed has the following format:
http://gdata.youtube.com/feeds/api/standardfeeds/localeID/feedID_CATEGORY_NAME
For example, the following example shows the feed URL for a list of the top-rated comedies in Japan:
http://gdata.youtube.com/feeds/api/standardfeeds/JP/top_rated_Comedy
Please refer to the reference guide for more information about standard feeds, region-specific standard feeds and category-specific standard feeds.
The following example demonstrates how to retrieve a standard feed and print information about the videos in that feed.
Feed<Video> videoFeed = request.GetStandardFeed(YouTubeQuery.MostPopular); printVideoFeed(videoFeed);
For each YouTube user, the YouTube Data API defines a video feed that lists the videos that the user has uploaded. The video feed for a user's uploaded videos can be retrieved from the following URL:
http://gdata.youtube.com/feeds/api/users/username/uploads
The following code demonstrates how to retrieve a feed of videos uploaded by a particular user:
Uri uri = new Uri("http://gdata.youtube.com/feeds/api/users/GoogleDevelopers/uploads"); Feed<Video> videoFeed = request.Get<Video>(uri); printVideoFeed(videoFeed);
Note: In the feed URL, you can substitute the string default
instead of a username to retrieve the videos uploaded by the currently authenticated user. In this case, you would retrieve the feed located at http://gdata.youtube.com/feeds/api/users/default/uploads
.
Each video entry in a video feed identifies the URL for another video feed that contains videos related to the entry, as determined by YouTube.
The following code shows how to retrieve and print information about the related videos for a particular Video
.
Uri videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/videos/ADos_xW4_J0"); Video video = request.Retrieve<Video>(videoEntryUrl); Feed<Video> relatedVideos = request.GetRelatedVideos(video); printVideoFeed(relatedVideos);
The YouTube Data API lets you request a set of videos that match a particular search term. The API supports a variety of standard Google Data query parameters and custom parameters specifically related to video search. For example, you can search for videos uploaded by a particular author or videos associated with a particular YouTube category.
To execute a search request, you will create a YouTubeQuery
object that specifies your search criteria and pass that object to the YouTubeRequest.Get()
method.
The following example demonstrates how to perform a search query for videos that match the search term "puppy". The query specifies that the result set may include restricted content and will be ordered by view count:
YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri); //order results by the number of views (most viewed first) query.OrderBy = "viewCount"; // search for puppies and include restricted content in the search results // query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate query.Query = "puppy"; query.SafeSearch = YouTubeQuery.SafeSearchValues.None; Feed<Video> videoFeed = request.Get<Video>(query); printVideoFeed(videoFeed);
In the client library code, the Query
class and subclasses like YouTubeQuery
are responsible for constructing feed URLs. The YouTubeQuery
object in the example above constructs the following feed URL:
http://gdata.youtube.com/feeds/api/videos?q=keyword&safeSearch=none&orderby=viewCount
The following list identifies some of the most common
YouTubeQuery
methods for setting search parameters. The reference guide contains a complete list of query parameters and their definitions.
Author
Author
method sets the author of the entry.Formats
Formats
method specifies a video format or a set of video formats identified in the YouTubeQuery.VideoFormat
enumeration.Location
Location
method specifies geographic coordinates (latitude, longitude) for a specific location. To ensure that each video in the response has coordinates that can be plotted on a map, append an exclamation point to the coordinates – e.g. query.Location = "37,-122!"
.LocationRadius
LocationRadius
method, in conjunction with the Location
method, defines a geographic area. Search results will include videos associated with locations in that area.NumberToRetrieve
NumberToRetrieve
method sets the maximum number of entries to return at one time.OrderBy
OrderBy
method sets the order in which to list entries, such as by relevance
, viewCount
, published
, or rating
.Query
Query
method sets a search query term. Searches for the specified string in all video metadata, such as titles, tags, and descriptions.SafeSearch
SafeSearch
method indicates amount of filtering (NONE
, MODERATE
or STRICT
) that YouTube should apply to remove restricted content from search results.StartIndex
StartIndex
method sets the 1-based index of the first result to
be retrieved (for paging).Time
Time
method sets a time period to limit standard feed results to one of the members of the YouTubeQuery.UploadTime
enumeration.Uploader
Uploader
method restricts search results to videos from YouTube Partner Program participants.You can restrict search results to show only videos that match a given set of categories and/or keywords. The reference guide describes how to specify both predefined YouTube categories, such as "Comedy" or "Music", and user-defined keywords, which are also known as tags. Each video can have many keywords but can only be associated with one YouTube category.
Key point: Some words, such as "comedy", can be both a YouTube category and a keyword. To distinguish between categories and keywords, the API uses the convention that capitalized words (e.g. "Comedy") denote YouTube categories and lowercase words (e.g. "comedy") denote keywords.
The following code demonstrates how to search for videos in the "News" category that match the keywords "sports" and "football". The example shows how to filter search results using both categories and keywords.
YouTube categories correspond to the YouTubeNameTable.CategorySchema
categorization, while keywords correspond to the YouTubeNameTable.KeywordSchema
categorization.
YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri); AtomCategory category1 = new AtomCategory("News", YouTubeNameTable.CategorySchema); AtomCategory category2 = new AtomCategory("sports", YouTubeNameTable.KeywordSchema); AtomCategory category3 = new AtomCategory("football", YouTubeNameTable.KeywordSchema); query.Categories.Add(new QueryCategory(category1)); query.Categories.Add(new QueryCategory(category2)); query.Categories.Add(new QueryCategory(category3)); Feed<Video> videoFeed = request.Get<Video>(query); printVideoFeed(videoFeed);
The previous example retrieved videos that matched the "News" category and the keywords "sports" and "football". The following example, on the other hand, retrieves videos that match the "News" category and either or both of those keywords. Note that to specify that a video must match the keyword "sports" or the keyword "football",
the code attached both keywords to the same CategoryFilter
.
YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri); AtomCategory category1 = new AtomCategory("News", YouTubeNameTable.CategorySchema); AtomCategory category2 = new AtomCategory("sports", YouTubeNameTable.KeywordSchema); AtomCategory category3 = new AtomCategory("football", YouTubeNameTable.KeywordSchema); query.Categories.Add(new QueryCategory(category1)); query.Categories.Add(new QueryCategory(category2.UriString, QueryCategoryOperator.OR)); query.Categories.Add(new QueryCategory(category3)); Feed<Video> videoFeed = request.Get<Video>(query); printVideoFeed(videoFeed);
The reference guide explains how to retrieve a list of categories that can be used to classify YouTube videos. The guide also explains how to retrieve localized category lists for several languages and locales.
When a user uploads a video through your site or application, you can associate the video with developer tags that you use to identify the video. YouTube does not display developer tags to YouTube users; however, you can retrieve or update videos that match a specific developer tag.
Developer tags can only be associated with a video at the time that the video is uploaded. In addition, developer tags that are assigned when a video is uploaded cannot be altered thereafter.
Each developer tag that is associated with a video is linked to the developer key specified in the request to upload that video. To search for videos that match a particular developer tag, the search request must specify the same developer key as the original upload requests for those videos. This restriction ensures that information about videos associated with a particular developer tag is only available to the developer that assigned that tag. Search requests for videos matching a particular developer tag do not require user authentication.
The following code demonstrates how to retrieve a list of videos associated with a particular developer tag:
YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri); AtomCategory category = new AtomCategory("uploaded_on_example.com", YouTubeNameTable.DeveloperTagSchema); query.Categories.Add(new QueryCategory(category)); YouTubeFeed videoFeed = service.Query(query); printVideoFeed(videoFeed);
You can upload videos in one of two ways:
Direct uploading allows you to add videos that are in your video library to YouTube. You should choose a direct-upload implementation if you want to host or store videos uploaded through your site and also add those videos to YouTube. In a direct-uploading scenario, when a user uploads a video through your site, the video will be sent to your servers. Your application will subsequently send an API request to upload the video from your server to YouTube.
Browser-based uploading allows you to accept video uploads from your users without having to handle, host or proxy the actual video files. You should choose a browser-based uploading process if you do not want to host or store the uploaded video files.
You must provide the following fields for all uploaded videos:
Note: Uploaded videos should be visible in the authenticated user's uploads feed immediately. In addition, a newly uploaded video will typically be included in search results a couple of hours after the upload completes. However, this delay may be longer during periods of heavy API server loads. Please see the Checking upload status section for more information.
To upload a video, you must construct a new YouTubeEntry
object that contains metadata about the video. The following example shows how to upload the Quicktime video "file.mov" to YouTube with the following properties:
Property | Value |
---|---|
Title | My Test Movie |
Category | Autos |
Keywords | cars, funny |
Description | My description |
Video private? | false |
Developer tag | mydevtag, anotherdevtag |
Video location | 37,-122 (lat,long) |
Filename | file.mov |
File MIME type | video/quicktime |
The following code uploads the video:
Video newVideo = new Video(); newVideo.Title ="My Test Movie"; newVideo.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema)); newVideo.Keywords = "cars, funny"; newVideo.Description = "My description"; newVideo.YouTubeEntry.Private = false; newVideo.Tags.Add(new MediaCategory("mydevtag, anotherdevtag", YouTubeNameTable.DeveloperTagSchema)); newVideo.YouTubeEntry.Location = new GeoRssWhere(37, -122); // alternatively, you could just specify a descriptive string // newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA"); newVideo.YouTubeEntry.MediaSource = new MediaFileSource("c:\\file.mov", "video/quicktime"); Video createdVideo = request.Upload(newVideo);
Browser-based uploading follows almost the same process as direct uploading. However, there are a few key differences:
When you use direct uploading, your request specifies the location of the media file source. However, when you use browser-based uploading, the video is uploaded from the user's browser to YouTube and not directly from your server.
As such, with browser-based uploading you do not attach a MediaSource
object to the YouTubeEntry
you are constructing.
Browser-based uploading uses a special URL instead of the authenticated user's uploads URL:
http://gdata.youtube.com/action/GetUploadToken
When you use direct uploading, YouTube returns a YouTubeEntry
for the uploaded video. However, when you use browser-based uploading, YouTube returns a URL and upload token that you will use to build a form through which the user completes the upload process.
The browser-based uploading process has several steps:
You create a YouTubeEntry
object that only contains metadata about the video being uploaded. The metadata includes all of the fields that you would specify in the direct uploading process – e.g. title, description, category, etc. – except the location of the actual video file.
You pass the YouTubeEntry
object as a parameter to the FormUpload
method.
YouTube returns a URL and upload token that you then use to build a form through which the user uploads the video file associated with the metadata uploaded in the previous step. The following code sample completes steps 1 through 3 of this process:
Video newVideo = new Video(); newVideo.Title ="My Test Movie"; newVideo.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema)); newVideo.Keywords = "cars, funny"; newVideo.Description = "My description"; newVideo.YouTubeEntry.Private = false; newVideo.Tags.Add(new MediaCategory("mydevtag, anotherdevtag", YouTubeNameTable.DeveloperTagSchema)); newVideo.YouTubeEntry.Location = new GeoRssWhere(37, -122); // alternatively, you could just specify a descriptive string // newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA"); FormUploadToken token = request.CreateFormUploadToken(newVideo); Console.WriteLine(token.Url); Console.WriteLine(token.Token);
You build a standard HTML form through which the user can upload the video file. The form must follow these guidelines:
It must use the upload URL, which was parsed from the API response in step 3, as the value of the <form>
tag's action
attribute.
You need to add the nexturl
parameter to the form's target URL. This parameter specifies the URL to which YouTube will redirect the user's browser after the user uploads the video file.
You must set the value of the <form>
tag's enctype
attribute to multipart/form-data
.
The form must contain an <input>
tag that identifies the video file, and the value of the name
attribute for that tag must be file
.
The form must contain a hidden <input>
tag that specifies the token value parsed from the API response in step 3. The value of the name
attribute for that tag must be token
.
The following code shows a sample form.
In the form, post_url
represents the value of token.getUrl()
and token_value
represents the value of token.getToken()
.
<form action="post_url?nexturl=http://example.com" method ="post" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="hidden" name="token" value="token_value"/> <input type="submit" value="go" /> </form>
After uploading the video file, the user is redirected to the nexturl
specified in your form. If the upload was successful, YouTube appends id
and status
parameters to the URL as shown in the following example:
http://www.example.com/youtube_uploads?status=200&id=JPF-DXF7hzc
If the upload was not successful, YouTube appends status
and code
parameters to the URL to help you diagnose the cause of the failure. The reference guide provides more information about these parameters.
After a user uploads a video, it will immediately be visible in the authenticated user's uploads feed:
http://gdata.youtube.com/feeds/api/users/default/uploads
However, the video will not be publicly visible on YouTube until YouTube has finished processing the video. In addition, videos that YouTube rejected or that failed to upload successfully will only be listed in the authenticated user's uploads feed. The following code checks the status of a Video
object to determine whether YouTube is still processing the video, failed to process the video, or rejected the video.
if (video.IsDraft) { Console.WriteLine("Video is not live."); string stateName = video.Status.Name; if (stateName == "processing") { Console.WriteLine("Video is still being processed."); } else if (stateName == "rejected") { Console.Write("Video has been rejected because: "); Console.WriteLine(video.Status.Value); Console.Write("For help visit: "); Console.WriteLine(video.Status.Help); } else if (stateName == "failed") { Console.Write("Video failed uploading because:"); Console.WriteLine(video.Status.Value); Console.Write("For help visit: "); Console.WriteLine(video.Status.Help); }
To modify the metadata for a video, update the Video
object and then
use the YouTubeRequest.Update
method.
The following code demonstrates how to
update the video's description.
video.Description = "new description"; Video updatedVideo = request.Update(video);
Please refer to the Determining whether a user can edit a video entry section for more information about editing videos.
To delete a video, invoke the
Delete
method on the
YouTubeRequest
object
with the Video
that is being deleted. For example, you could retrieve the uploaded videos feed for the authenticated user and then delete a video selected by the user.
request.Delete(video);
Note: The authenticated user must be the owner of the video that is being deleted.
A user can add a rating to a video. YouTube uses a 1-5 rating system in which 1 is the lowest rating that can be given. Users cannot update or delete ratings. Typically, a user would rate a video after watching that video.
To rate a video,
set the Rating
on the Video
that is being rated.
The following code shows how to add a rating to a video:
video.Rating = 5; request.Insert(video.RatingsUri, video);
A comment is a text response to a video. Logged-in users can add comments to a video but cannot modify or delete those comments. In addition, please note that YouTube will convert any HTML markup that appears in a comment into plain text. Typically, a user would add a comment to a video after watching that video.
The following code demonstrates how to retrieve the comments feed URL from a Video
object and then print the comments for the video.
Feedcomments = request.GetComments(v); foreach (Comment c in comments.Entries) { Console.WriteLine(c.Content); }
To add a comment to a video,
add a Comment
object to the video.
The following code demonstrates how to
add a new comment for a video:
Comment c = new Comment(); c.Content = "This is my comment."; request.AddComment(video, c);
Users can also add a comment as a reply to an existing comment as shown in the following sample code.
// retrieve the comments for the video Feedfc = request.GetComments(video); List comments = new List (fc.Entries); // create a reply to the third comment Comment c = comments[2]; Comment reply = new Comment(); reply.ReplyTo(c); reply.Content = "This is the reply text"; request.AddComment(video, reply);
A video response is a video that is associated, as a reply, with a second video. A video can be designated as a video response to exactly one other video. An authenticated user can add or delete video responses, but the user must have uploaded a video to modify that video's video response status.
Each video entry in a video feed can have an associated video response feed. That feed, which lists all of the video responses to the video described in the video entry, is itself a video feed.
The following code demonstrates how to retrieve and print information about the video responses for a given Video
.
Uri videoEntryUrl = new Uri("http://gdata.youtube.com/feeds/api/videos/ADos_xW4_J0"); Video video = request.Retrieve<Video>(videoEntryUrl); Feed<Video> responses = request.GetResponseVideos(video); printVideoFeed(responses);
To add a video response, which is identified by a Video
object, insert it into the video responses feed URL for the original video. The following code demonstrates how to retrieve the video responses feed URL for a video and then add a new video response to the feed.
request.Insert(video.ResponseUri, responseVideo);
If you retrieved the video responses to a video as a feed, you can also insert a new response (identified by a Video
object) directly into the VideoFeed
object as shown in the code below:
request.Insert(videoFeed, responseVideo);
Note: A video owner has the opportunity to review and approve all video responses to the owner's videos. A video response will only be included in a video responses feed if the video owner has approved the response.
The currently authenticated user can delete a video from a video responses feed if she is the owner of the video that was responded to.
To delete a video response, call the Delete
method, passing in the Video
object that you are deleting.
request.Delete(responseVideo);
To post a complaint about a video, insert
a Complaint
to the complaints link for the Video
object that describes that video.
The entry specifies a complaint category as well as the full text of the complaint. The following code demonstrates how to flag a video:
Complaint c = new Complaint(); c.Type = ComplaintEntry.ComplaintType.PORN; c.Content = "This video offends my better sensibilities."; request.Insert(video.ComplaintUri, c);
Note: The ComplaintEntry.ComplaintType
enumeration lists several different complaint categories.
YouTube users can choose to mark videos that they watch as favorite videos. A user's favorite videos feed can be retrieved from the following URL:
http://gdata.youtube.com/feeds/api/users/username/favorites
Note: Using the string default
instead of a username retrieves the favorite videos of the currently authenticated user.
The following code
retrieves and prints a specified user's favorite videos. The returned feed is a regular video feed, which contains YouTubeEntry
objects.
Feed<Video> feed = request.GetFavoriteVideo(username
);
printVideoFeed(videoFeed);
To add a favorite video,
insert a YouTubeEntry
object that identifies the video
to the authenticated user's favorite videos feed.
string videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/ADos_xW4_J0"; YouTubeEntry videoEntry = (YouTubeEntry) service.Get(videoEntryUrl); service.Insert(new Uri(feedUrl), videoEntry);
To delete a favorite video from the currently authenticated user's favorite videos feed, call the Delete
method, passing in the Video
object that corresponds to the
the favorite video you want to delete.
request.Delete(favoriteVideo);
Note: You must retrieve the Video
object that identifies the favorite video from the authenticated user's favorite videos feed. Otherwise, your request will attempt to delete the actual video itself.
A YouTube user's playlists feed contains a list of that user's playlists, with each feed entry corresponding to a single playlist. The client library enables you to retrieve, add, update and delete playlists. It also lets you retrieve a list of the videos in a single playlist as well as add, update or delete playlist videos.
To retrieve a feed of a particular user's playlists, you use the following URL:
http://gdata.youtube.com/feeds/api/users/username/playlists
Note: Using the string default
instead of a username retrieves the profile of the currently authenticated user.
The following code demonstrates how to retrieve and print information about a particular user's playlists:
Feed<Playlist> userPlaylists = request.GetPlaylistsFeed(username); foreach (Playlist p in userPlaylists.Entries) { Console.WriteLine("Title: " + p.Title); Console.WriteLine(p.Summary); Console.WriteLine("Number of entries: " + p.CountHint); }
The following code demonstrates how to print information about the videos in a playlist.
Feed<Video> list = request.GetPlaylist(p); foreach (Video v in list.Entries) { printVideoEntry(v); }
Note: The PlaylistEntry
object also contains the members of a YouTubeEntry
object. Please see the Video entry contents section for more information about the information that can be retrieved from a YouTubeEntry
object.
To add a new playlist,
insert a Playlist
into the authenticated user's playlists feed.
Playlist pl = new Playlist(); pl.Title = "this is the title"; pl.Summary = "this is my new playlist"; Playlist createdPlaylist = request.Insert( new Uri("http://gdata.youtube.com/feeds/api/users/default/playlists"), pl);
You can use the API to update a playlist's title, description and or public/private status. To update a playlist,
modify the Playlist
object for that playlist and then call the object's Update
method.
The following code updates a playlist's description.
pl.Summary = "updated summary"; request.Update(pl);
You can add a video to a playlist by using
a PlaylistMember
object. The following code creates a PlaylistMember
object with a known ID value and then adds it to the Playlist
object (p
).
Since the request does not specify a position where the video will appear in the playlist, the new video is added to the end of the playlist.
// ForPlaylist
object p PlaylistMember pm = new PlaylistMember(); // Insert <id> or <videoid> for video here pm.Id =VIDEOID
; request.AddToPlaylist(p, m);
You can modify the position of each video in a playlist by
updated the PlaylistMember
object for the video and calling the Update
method.
// move PlaylistMember pm
to the top of the playlist
pm.Position = 1;
request.Update(pm);
To remove a video from a playlist, use the Delete
method
and pass in the PlaylistMember
object that is being deleted.
request.Delete(playlistMember);
To delete a playlist,
call the Delete
method and pass in the PlaylistMember
object that is being deleted.
request.Delete(playlist);
To fetch a list of the channels, favorite video lists and search queries that a given user has subscribed to, send a request to the following URL:
http://gdata.youtube.com/feeds/api/users/username/subscriptions
Note: Using the string default
instead of a username retrieves the currently authenticated user's subscriptions.
The following code demonstrates how to retrieve and print the list of subscriptions for a given user:
string feedUrl = "http://gdata.youtube.com/feeds/api/users/GoogleDevelopers/subscriptions"; YouTubeQuery query = new YouTubeQuery(feedUrl); SubscriptionFeed subFeed = service.GetSubscriptions(query); foreach (SubscriptionEntry entry in subFeed.Entries) { Console.WriteLine("Title: " + entry.Title.Text); Console.WriteLine(entry.Content.Src.Content); }
You can create a new subscription by inserting a new Subscription
into the authenticated user's subscriptions feed. Users can subscribe to another user's channel, another user's list of favorite videos, a playlist or a search query.
The following code subscribes the authenticated user to the "GoogleDevelopers" channel.
Subscription s = new Subscription(); s.Type = SubscriptionEntry.SubcriptionType.channel; s.UserName = "GoogleDevelopers"; request.Insert(new Uri(YouTubeQuery.CreateSubscriptionUri(null)), s);
The following code subscribes the authenticated user to the "GoogleDevelopers" user's list of favorite videos:
Subscription s = new Subscription(); s.Type = SubscriptionEntry.SubcriptionType.favorites; s.UserName = "GoogleDevelopers"; request.Insert(new Uri(YouTubeQuery.CreateSubscriptionUri(null)), s);
The following code subscribes the authenticated user to the Android playlist, which has the playlist ID 586D322B5E2764CF
, in the 'GoogleDevelopers' channel.
Subscription s = new Subscription(); s.Type = SubscriptionEntry.SubcriptionType.playlist; string playlistId = "586D322B5E2764CF"; s.PlaylistId = playlistId; request.Insert(new Uri(YouTubeQuery.CreateSubscriptionUri(null)), s);
The following code subscribes the authenticated user to videos that match the search term "puppies":
Subscription s = new Subscription(); s.Type = SubscriptionEntry.SubcriptionType.query; s.QueryString = "puppies"; request.Insert(new Uri(YouTubeQuery.CreateSubscriptionUri(null)), s);
To delete a subscription, call the
Delete
method, passing in the Subscription
to be deleted.
request.Delete(s);
To retrieve a user's profile, send a request to the following URL:
http://gdata.youtube.com/feeds/api/users/username
Note: Using the string default
instead of a username retrieves the profile of the currently authenticated user.
The following code prints out a number of attributes from a specified user's profile:
string feedUrl = "http://gdata.youtube.com/feeds/api/users/GoogleDevelopers"; ProfileEntry profile = (ProfileEntry) service.Get(feedUrl); Console.WriteLine("Username : " + profile.UserName); Console.WriteLine("Age : " + profile.Age); Console.WriteLine("Gender : " + profile.Gender); Console.WriteLine("Single? : " + profile.Relationship); Console.WriteLine("Books : " + profile.Books); Console.WriteLine("Company : " + profile.Company); Console.WriteLine("Description: " + profile.Description); Console.WriteLine("Hobbies : " + profile.Hobbies); Console.WriteLine("Hometown : " + profile.Hometown); Console.WriteLine("Location : " + profile.Location); Console.WriteLine("Movies : " + profile.Movies); Console.WriteLine("Music : " + profile.Music); Console.WriteLine("Job : " + profile.Occupation); Console.WriteLine("School : " + profile.School); Console.WriteLine("Subscriber count: " + profile.Statistics.SubscriberCount); Console.WriteLine("View count: " + profile.Statistics.ViewCount); Console.WriteLine("Watch count: " + profile.Statistics.WatchCount); Console.WriteLine("Last web access: " + profile.Statistics.LastWebAccess);
To retrieve a list of a user's contacts, send a request to the following URL:
http://gdata.youtube.com/feeds/api/users/username/contacts
The following code demonstrates how to retrieve and print the contacts of a specified user:
string feedUrl = "http://gdata.youtube.com/feeds/api/users/GoogleDevelopers/contacts"; YouTubeQuery query = new YouTubeQuery(feedUrl); FriendsFeed friendFeed = service.GetFriends(query); foreach (FriendsEntry entry in friendFeed.Entries) { Console.WriteLine("Username: " + entry.UserName); Console.WriteLine("Status: " + entry.Status); }
To add a contact,
insert a new FriendsEntry
into the authenticated user's contacts feed.
The request can specify any number of user-defined categories to associate the contact with groups, such as "Family", "Bowling Enthusiasts," "Wizards" and so forth. The example below adds a contact with the username "GoogleDevelopers" to the "Cool Dudes" category.
string feedUrl = "http://gdata.youtube.com/feeds/api/users/default/contacts"; FriendsEntry newFriend = new FriendsEntry(); newFriend.UserName = "GoogleDevelopers"; newFriend.Categories.Add(new AtomCategory("Cool Dudes", YouTubeNameTable.FriendsCategorySchema)); service.Insert(new Uri(feedUrl), newFriend);
You can accept or reject a contact by updating the status of the corresponding FriendsEntry
object.
The following example shows how to accept a contact:
entry.Status = "accepted"; entry.Update();
The following example shows how to reject a contact:
entry.Status = "rejected"; entry.Update();
To delete a contact, call the
Delete
method on the FriendsEntry
that you are deleting.
friendEntry.Delete();
The API enables you to send messages between YouTube users who have mutually accepted each other as contacts. All messages sent through the API must include a video.
To retrieve the contents of a user's inbox, make an authenticated request to the following URL:
http://gdata.youtube.com/feeds/api/users/username/inbox
The following example prints the contents of the authenticated user's inbox.
string feedUrl = "http://gdata.youtube.com/feeds/api/users/default/inbox"; YouTubeQuery query = new YouTubeQuery(feedUrl); MessageFeed messagesFeed = service.GetMessages(query); foreach (MessageEntry entry in messagesFeed.Entries) { Console.WriteLine("Message from: " + entry.Authors[0].Name); Console.WriteLine("Subject: " + entry.Title.Text); Console.WriteLine(entry.Summary.Text); Console.WriteLine("Attached video: " + entry.AlternateUri.Content); }
To send a message to a user, construct a MessageEntry
object and insert it into the user's inbox feed.
The following code sends a message containing a video to a user identified by the variable
receivingUser
:
string friendsInbox = "http://gdata.youtube.com/feeds/api/users/" + receivingUser + "/inbox"; string videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/ADos_xW4_J0"; YouTubeEntry videoEntry = (YouTubeEntry) service.Get(videoEntryUrl); MessageEntry newMessage = new MessageEntry(); newMessage.Title.Text = "My Subject"; newMessage.Summary.Text = "This is the message body."; newMessage.Id = videoEntry.Id; service.Insert(new Uri(friendsInbox), newMessage);
Note: The recipient of the message must be an accepted contact of the sender of the message.
To delete a message, call the Delete
method on a MessageEntry
object:
entry.Delete();
The YouTube Data API supports batch processing, enabling you to execute up to 50 operations with a single API request rather than submit a separate request for each individual operation. A batch processing request can combine multiple query (HTTP GET), insert (POST), update (PUT) and delete (DELETE) operations.
Batch operations are available for all YouTube feeds, and different types of feeds support different types of batch operations. For example, you can update, insert or delete playlists. However, you can only insert or delete favorite videos since favorite videos cannot be updated.
Note: Batch processing requests support query (HTTP GET) operations for feed entries but not for entire feeds. For example, if you are sending a batch request for a playlist, you can include one or more entries that retrieve information about individual playlist entries. However, the batch request cannot retrieve the entire feed for the playlist.
When you submit a batch processing request, the API server will try to perform each requested operation even if some of the operations in the request are not completed successfully.
The following code demonstrates how to create and execute a batch processing request using the .NET client library. The code sample retrieves the batch URL for a playlist feed and then specifies four different operations to perform on the feed:
YouTubeRequestSettings settings = new YouTubeRequestSettings("NETUnittests", this.ytClient, this.ytDevKey, this.ytUser, this.ytPwd); YouTubeRequest request = new YouTubeRequest(settings); // Retrieve the user's playlists feed and create a list of playlists Feed<Playlist> playlistsFeed = request.GetPlaylistsFeed(null); List<Playlist> playlists = new List(playlistsFeed.Entries); // Retrieve a list of the videos in the third playlist in the feed. // (You could choose another playlist.) Feed<PlaylistMember> playlistMembersFeed = request.GetPlaylist(playlists[2]); List<PlaylistMember> playlistMembers = new List<PlaylistMember>(playlistsMembersFeed.Entries); List<PlaylistMember> batch = new List<PlaylistMember>(); // Delete the third item in the list toBatch = playlistMembers[2]; toBatch.BatchData = new GDataBatchEntryData(); toBatch.BatchData.Id = "DELETED_PLAYLIST_ENTRY"; toBatch.BatchData.Type = GDataBatchOperationType.delete; batch.Add(toBatch); // Add a video to the playlist PlaylistMember toBatch = new PlaylistMember(); // Set videoid
to the videoid of video being added to the playlist toBatch.VideoId =videoid
; toBatch.BatchData = new GDataBatchEntryData(); toBatch.BatchData.Id = "NEW_PLAYLIST_ENTRY"; toBatch.BatchData.Type = GDataBatchOperationType.insert; batch.Add(toBatch); // Change the second video to be the first video in the playlist toBatch = playlistMembers[1]; toBatch.YouTubeEntry.Position = 1; toBatch.BatchData = new GDataBatchEntryData(); toBatch.BatchData.Id = "UPDATED_PLAYLIST_ENTRY"; toBatch.BatchData.Type = GDataBatchOperationType.update; batch.Add(toBatch); // Update the list of videos in the playlist by performing the batch operations. FeedupdatedPlaylistMembers = request.Batch(batch, playlistMembersFeed);
Questions? Feedback? Notice a typo in this doc? Let us know in the discussion forum. Happy coding!