YouTube

Developer's Guide: .NET

Note: The YouTube Data API (v2) has been officially deprecated as of March 4, 2014. Please refer to our deprecation policy for more information.

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.

Contents

  1. About this document
    1. Audience
    2. Document structure
  2. Getting started
  3. Authentication
    1. AuthSub for web applications
    2. ClientLogin for installed applications
  4. Understanding video feeds and entries
    1. Displaying a feed of videos
    2. Retrieving a specific video entry
    3. Video entry contents
      1. Determining whether a user can edit a video entry
  5. Retrieving and searching for videos
    1. Retrieving standard feeds
    2. Videos uploaded by a specific user
    3. Retrieving related videos
    4. Searching for videos
      1. Searching for videos using categories and keywords
      2. Searching for videos using developer tags
  6. Uploading videos
    1. Direct upload
    2. Browser-based upload
    3. Checking upload status
  7. Updating and deleting videos
    1. Updating video information
    2. Deleting a video
  8. Using community features
    1. Adding a rating
    2. Comments
      1. Retrieving video comments
      2. Adding a comment
    3. Video Responses
    4. Flagging a video
  9. Saving and collecting videos
    1. Favorite videos
      1. Retrieving a user's favorite videos
      2. Adding a favorite video
      3. Deleting a favorite video
    2. Playlists
      1. Retrieving a user's playlists
      2. Retrieving playlist information
      3. Adding a playlist
      4. Updating a playlist
        1. Adding a video to a playlist
        2. Editing information for a playlist video
        3. Removing a video from a playlist
      5. Deleting a playlist
    3. Subscriptions
      1. Retrieving a user's subscriptions
      2. Adding a subscription
      3. Deleting a subscription
  10. Enabling user interaction
    1. Profiles
      1. Retrieving a user's profile
    2. Contacts
      1. Retrieving a user's contacts
      2. Adding a contact
      3. Accepting or rejecting a contact
      4. Deleting a contact
    3. Messages
      1. Retrieving messages
      2. Sending a message
      3. Deleting a message
  11. Batch processing
  12. Conclusion

About this document

Audience

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.

Document structure

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, such as a standard feed of YouTube's most popular 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.

  • 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, or complaint to an existing video. You can also use the API to retrieve lists of video comments.

  • 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.

Getting started

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;

Authentication

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 YouTubeRequestSettings("example app", clientID, developerKey);
YouTubeRequest request = new YouTubeRequest(settings);

Note: Please visit https://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 for web applications

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 for installed applications

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.

Understanding video feeds and entries

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.

Displaying a feed of videos

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.

Retrieving a specific video entry

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);

Video entry contents

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.

Determining whether a user can edit a video entry

The API only returns editable video entries when you retrieve the authenticated user's uploaded videos feed. In other video feeds, such as search results feeds, video entries do not contain the information that the .NET client library checks to determine whether a video is editable.

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.");
}

Retrieving and searching for videos

Retrieving standard feeds

The YouTube Data API provides a standard feed of YouTube's most popular videos. The API previously supported other standard feeds, which have since been deprecated. See the Developer's Guide for more information.

The URLs for the feed of YouTube's most popular videos has the following format:

http://gdata.youtube.com/feeds/api/standardfeeds/most_popular

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/most_popular_CATEGORY_NAME

For example, the following example shows the feed URL for a list of the most popular comedies in Japan:

http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_popular_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);

Videos uploaded by a specific user

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

You can also retrieve a specific entry for an uploaded video by sending an API request to the following URL:

http://gdata.youtube.com/feeds/api/users/username/uploads/VIDEO_ID

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);

In the feed URL, you can use the string default instead of a username to retrieve the videos uploaded by the currently authenticated user. In that case, you would retrieve the feed located at http://gdata.youtube.com/feeds/api/users/default/uploads.

In addition, when you retrieve the uploaded videos feed or a specific entry from that feed for the currently authenticated user, the feed entries (or the single entry) will be editable using the client library code. See the Identifying_Editable_Video_Entries section for more details.

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);

Searching for videos

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
The Author method sets the author of the entry.
Formats
The Formats method specifies a video format or a set of video formats identified in the YouTubeQuery.VideoFormat enumeration.
Location
The 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
The LocationRadius method, in conjunction with the Location method, defines a geographic area. Search results will include videos associated with locations in that area.
NumberToRetrieve
The NumberToRetrieve method sets the maximum number of entries to return at one time.
OrderBy
The OrderBy method sets the order in which to list entries, such as by relevance, viewCount, published, or rating.
Query
The Query method sets a search query term. Searches for the specified string in all video metadata, such as titles, tags, and descriptions.
SafeSearch
The SafeSearch method indicates amount of filtering (NONE, MODERATE or STRICT) that YouTube should apply to remove restricted content from search results.
StartIndex
The StartIndex method sets the 1-based index of the first result to be retrieved (for paging).
Time
The Time method sets a time period to limit standard feed results to one of the members of the YouTubeQuery.UploadTime enumeration.
Uploader
The Uploader method restricts search results to videos from YouTube Partner Program participants.

Searching for videos using categories and keywords

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.

Searching for videos using developer tags

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);

Uploading videos

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:

  • Title
  • Description
  • Category
  • Keywords

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.

Direct upload

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:

PropertyValue
TitleMy Test Movie
CategoryAutos
Keywordscars, funny
DescriptionMy description
Video private?false
Developer tagmydevtag, anotherdevtag
Video location37,-122 (lat,long)
Filenamefile.mov
File MIME typevideo/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 upload

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:

  1. 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.

  2. You pass the YouTubeEntry object as a parameter to the FormUpload method.

  3. 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);
    
  4. 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>
    
  5. 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.

Checking upload status

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);
}

Updating and deleting videos

Updating video information

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.

Deleting a video

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.

Using community features

Adding a rating

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);

Comments

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.

Retrieving video comments

The following code demonstrates how to retrieve the comments feed URL from a Video object and then print the comments for the video.

Feed comments = request.GetComments(v);
foreach (Comment c in comments.Entries)
{
  Console.WriteLine(c.Content);
}

Adding a comment

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
Feed fc = 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);

Video Responses

A YouTube video response was a video that was associated, as a reply, with a second video. The video responses feature has been retired as explained in this announcement. While existing video responses are still available, YouTube no longer supports the ability to retrieve a list of video responses for a video, to upload new video responses, or to delete video responses, though you can delete the video that was used in a video response. Consequently, these functions are also no longer supported in the API.

API requests for video response operations now return the following:

  • A request to retrieve video responses for a video returns an empty list.
  • A request to add a video response returns a 403 HTTP response code.
  • A request to delete a video response returns a 403 HTTP response code.

Flagging a video

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.

Saving and collecting videos

Favorite videos

Retrieving a user's favorite videos

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);

Adding a favorite video

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);

Deleting a favorite video

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.

Playlists

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.

Retrieving a user's playlists

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);
}

Retrieving playlist information

The following code demonstrates how to print information about the videos in a playlist.

Feed<PlayListMember> 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.

Adding a playlist

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);

Updating a playlist

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);

Adding a video to a playlist

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.

// For Playlist object p
PlayListMember pm = new PlayListMember();

// Insert <id> or <videoid> for video here
pm.VideoId = VIDEOID;
request.AddToPlaylist(p, pm);

Editing information for a playlist video

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);

Removing a video from a playlist

To remove a video from a playlist, use the Delete method and pass in the PlayListMember object that is being deleted.

request.Delete(playListMember);

Deleting a playlist

To delete a playlist, call the Delete method and pass in the Playlist object that is being deleted.

request.Delete(playlist);

Subscriptions

Retrieving a user's subscriptions

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);
}

Adding a subscription

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.

Subscribing to a channel

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);
Subscribing to a list of favorite videos

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);
Subscribing to a playlist

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);
Subscribing to a search query

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);

Deleting a subscription

To delete a subscription, call the Delete method, passing in the Subscription to be deleted.

request.Delete(s);

Enabling user interaction

Profiles

Retrieving a user's profile

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);

Contacts

Retrieving a user's contacts

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);
}

Adding a contact

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);

Accepting or rejecting a contact

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();

Deleting a contact

To delete a contact, call the Delete method on the FriendsEntry that you are deleting.

friendEntry.Delete();

Messages

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.

Retrieving messages

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);
}

Sending a message

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.

Deleting a message

To delete a message, call the Delete method on a MessageEntry object:

entry.Delete();

Batch processing

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 (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.

Please note the following characteristics of batch processing requests:

  • Batch processing requests support query (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 playlist feed that contains those entries.

  • 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.

  • Submitting requests in a batch process does not reduce the amount of quota that your application uses and, therefore, does not reduce the likelihood that your application will exceed our limits on API calls.

  • Some of the API's client libraries may not support batch processing.

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:

  1. Delete the third video in the playlist.
  2. Add a new video to the playlist.
  3. Move the second video to be the first video in the playlist.
  4. Retrieve the updated entry.

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.
Feed updatedPlayListMembers = 
  request.Batch(batch, playListMembersFeed);

Conclusion

Questions? Feedback? Please use Stack Overflow to ask technical API questions or the Issue Tracker template to report a bug.

For general questions about YouTube functionality, please use http://www.google.com/support/forum/p/youtube.

Happy coding!

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.