YouTube

Developer's Guide: Java

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 Java client library. For help setting up the Java client library, check out the Getting Started Guide.

If you're interested in understanding more about the underlying protocol that the Java 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. Paging through results
  7. Uploading videos
    1. Direct upload
    2. Browser-based upload
    3. Checking upload status
  8. Updating and deleting videos
    1. Updating video information
    2. Deleting a video
  1. Using community features
    1. Adding a rating
    2. Comments
      1. Retrieving video comments
      2. Adding a comment
    3. Video Responses
    4. Flagging a video
  2. 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
  3. 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
  4. Activity feeds
    1. User activity feeds
    2. Friend activity feeds
  5. Batch processing
  6. Conclusion

About this document

Audience

This document is intended for programmers who want to write client applications that can interact with YouTube using the Java 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 know Java.

For reference information about the Java classes and methods, see the client library's Javadoc reference guide.

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 Java client library, check out the Getting Started Guide. To use the Java client library, you must be running Java 1.5. After downloading the client library, you'll find the classes you need to get started in the java/lib/gdata-client-1.0.jar and java/lib/gdata-youtube-1.0.jar files.

A full working copy of the sample code is included in the distribution, at http://code.google.com/p/gdata-java-client/downloads/list. Build and execution instructions are included in the same directory in the README.txt file. The sample client application performs a number of operations on the YouTube Data API feeds to demonstrate the use of the API. For a list of those operations, see the sample application's main method.

To compile the example snippets provided in this document into your own code, you will need to use the following import statements:

import com.google.gdata.client.*;
import com.google.gdata.client.youtube.*;
import com.google.gdata.data.*;
import com.google.gdata.data.geo.impl.*;
import com.google.gdata.data.media.*;
import com.google.gdata.data.media.mediarss.*;
import com.google.gdata.data.youtube.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import java.io.IOException;
import java.io.File;
import java.net.URL;

Authentication

The Java 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 write or upload operations using the YouTube API, you need to instantiate a YouTubeService object with your clientID and developer key as shown below:

YouTubeService service = new YouTubeService(clientID, developer_key);

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.

String requestUrl =
AuthSubUtil.getRequestUrl("http://www.example.com/RetrieveToken",
                        "http://gdata.youtube.com",
                        false,
                        true);

You pass the following parameters to the getRequestUrl method:

  • The next parameter contains the URL to which the user will be redirected after logging in to a Google Account.

  • The scope parameter identifies the service that the user is enabling your site to access on his behalf. The value of this parameter must be http://gdata.youtube.com.

  • The secure parameter contains a boolean value (0 or 1) that indicates whether the authentication service will return a secure or nonsecure token. Secure tokens are issued only to websites that have registered with Google, and video upload requests that use a secure token must be digitally signed. Please see the Google AuthSub documentation for more details about secure tokens.

  • The session parameter contains a boolean value (0 or 1) that indicates whether the single-use authentication token that the authentication service returns can be exchanged for a session token, which can be used multiple times. Set this variable to 1 to indicate that the single-use token can be exchanged for a session token. Please see the Google AuthSub documentation for an explanation of how to request a session token.

The AuthSub request URL will have the following format. (Your request URLs may specify different parameter values.)

https://www.google.com/accounts/AuthSubRequest?
  next=http%3A%2F%2Fwww.example.com%2Fwelcome.php
  &scope=http%3A%2F%2Fgdata.youtube.com
  &session=1
  &secure=0

After the user logs in via YouTube's authentication service, YouTube will redirect the user back to the URL identified in the next parameter in your AuthSub request. The redirect contains a single-use authentication token, which is identified by the token parameter in the URL as shown. If the value of the session parameter in your AuthSub request was 1, then you can exchange the single-use token for a session token by submitting an AuthSubSessionToken request. The following URL shows how the token parameter will appear in the redirect to your site.

http://www.example.com/welcome?token=DQAADKEDE

Your code needs to be able to extract the token from the page URL. For example, the servlet handling the page could retrieve the token from the URL by using the convenience function getTokenFromReply in the Java client library:

String onetimeUseToken =
  AuthSubUtil.getTokenFromReply(httpServletRequest.getQueryString());

Your application can set an authentication cookie before the user has the opportunity to link to the AuthSub request URL. The cookie can then enable your application to recognize the authenticated user after the AuthSub authentication page redirects the user to your web page.

Upgrading to a session token

As noted above, the token that you receive in the redirect URL is a single-use token. You can exchange the single-use token for a session token, which does not expire, by submitting an AuthSubSessionToken request.

The following code shows how to use the Java client library to make this exchange. The exchangeForSessionToken method takes two parameters. The first parameter specifies the single-use token being exchanged for a session token. The second parameter indicates whether the session token is a secure token, which means that you will digitally sign all API requests. The parameter should specify either your private key for a secure token or null for a nonsecure token. Learn more about signing requests.

String sessionToken = AuthSubUtil.exchangeForSessionToken(onetimeUseToken, null);

To instruct the Java client library to automatically send the session token with each request – the token is sent in the Authorization request header – call the YouTubeService object's setAuthSubToken method. This action enables you to use standard client library calls to interact with the YouTube API without having to worry about authorization tokens. This method takes the same two parameters as the exchangeForSessionToken method described earlier.

YouTubeService service = new YouTubeService(clientID, developer_key);
service.setAuthSubToken(sessionToken, null);

An AuthSub session token will not expire unless you specifically issue a request to revoke it. For example, your application could obtain a token at the beginning of a user's session and then revoke the token at the end of the session. A user can also revoke access to your application (and its associated token) through the Authorized Sites page in the user's YouTube account.

To revoke a session token using the Java client library, call the revokeToken method. This method takes the same two parameters as the exchangeForSessionToken method described earlier.

AuthSubUtil.revokeToken(sessionToken, null);

You can also revoke the token using the AuthSubRevokeToken handler.

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, invoke the setUserCredentials method of YouTubeService, specifying the email and password of the user associated with the authentication request.

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.

YouTubeService service = new YouTubeService(clientID, developer_key);
service.setUserCredentials("jo@gmail.com", "password");

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 VideoEntry 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:

VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
printVideoFeed(videoFeed, true);

public static void printVideoFeed(VideoFeed videoFeed, boolean detailed) {
  for(VideoEntry videoEntry : videoFeed.getEntries() ) {
    printVideoEntry(videoEntry, detailed);
  }
}

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 VideoEntry object, which corresponds to a particular YouTube video, and then prints the metadata for the video:

String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/ADos_xW4_J0";
VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl), VideoEntry.class);
printVideoEntry(videoEntry, true);

Video entry contents

A VideoEntry 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 VideoEntry 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.

public static void printVideoEntry(VideoEntry videoEntry, boolean detailed) {
  System.out.println("Title: " + videoEntry.getTitle().getPlainText());

  if(videoEntry.isDraft()) {
    System.out.println("Video is not live");
    YtPublicationState pubState = videoEntry.getPublicationState();
    if(pubState.getState() == YtPublicationState.State.PROCESSING) {
      System.out.println("Video is still being processed.");
    }
    else if(pubState.getState() == YtPublicationState.State.REJECTED) {
      System.out.print("Video has been rejected because: ");
      System.out.println(pubState.getDescription());
      System.out.print("For help visit: ");
      System.out.println(pubState.getHelpUrl());
    }
    else if(pubState.getState() == YtPublicationState.State.FAILED) {
      System.out.print("Video failed uploading because: ");
      System.out.println(pubState.getDescription());
      System.out.print("For help visit: ");
      System.out.println(pubState.getHelpUrl());
    }
  }

  if(videoEntry.getEditLink() != null) {
    System.out.println("Video is editable by current user.");
  }

  if(detailed) {

    YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();

    System.out.println("Uploaded by: " + mediaGroup.getUploader());

    System.out.println("Video ID: " + mediaGroup.getVideoId());
    System.out.println("Description: " + 
      mediaGroup.getDescription().getPlainTextContent());

    MediaPlayer mediaPlayer = mediaGroup.getPlayer();
    System.out.println("Web Player URL: " + mediaPlayer.getUrl());
    MediaKeywords keywords = mediaGroup.getKeywords();
    System.out.print("Keywords: ");
    for(String keyword : keywords.getKeywords()) {
      System.out.print(keyword + ",");
    }

    GeoRssWhere location = videoEntry.getGeoCoordinates();
    if(location != null) {
      System.out.println("Latitude: " + location.getLatitude());
      System.out.println("Longitude: " + location.getLongitude());
    }

    Rating rating = videoEntry.getRating();
    if(rating != null) {
      System.out.println("Average rating: " + rating.getAverage());
    }

    YtStatistics stats = videoEntry.getStatistics();
    if(stats != null ) {
      System.out.println("View count: " + stats.getViewCount());
    }
    System.out.println();

    System.out.println("\tThumbnails:");
    for(MediaThumbnail mediaThumbnail : mediaGroup.getThumbnails()) {
      System.out.println("\t\tThumbnail URL: " + mediaThumbnail.getUrl());
      System.out.println("\t\tThumbnail Time Index: " +
      mediaThumbnail.getTime());
      System.out.println();
    }

    System.out.println("\tMedia:");
    for(YouTubeMediaContent mediaContent : mediaGroup.getYouTubeContents()) {
      System.out.println("\t\tMedia Location: "+ mediaContent.getUrl());
      System.out.println("\t\tMedia Type: "+ mediaContent.getType());
      System.out.println("\t\tDuration: " + mediaContent.getDuration());
      System.out.println();
    }

    for(YouTubeMediaRating mediaRating : mediaGroup.getYouTubeRatings()) {
      System.out.println("Video restricted in the following countries: " +
        mediaRating.getCountries().toString());
    }
  }
}

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 Java 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 getEditLink method on that entry. The sample code below demonstrates how to determine whether a video entry is editable.

if(videoEntry.getEditLink() != null) {
  System.out.println("Video is editable by 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 URL 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.

String feedUrl = "http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed";
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
printVideoFeed(videoFeed, true);

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:

String feedUrl =
  "http://gdata.youtube.com/feeds/api/users/GoogleDevelopers/uploads";

VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
printVideoFeed(videoFeed, true);

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

if (videoEntry.getRelatedVideosLink() != null) {
  String feedUrl = videoEntry.getRelatedVideosLink().getHref();
  
  VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
  printVideoFeed(videoFeed, true);
}

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 YouTubeService.query 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(new URL("http://gdata.youtube.com/feeds/api/videos"));
// order results by the number of views (most viewed first)
query.setOrderBy(YouTubeQuery.OrderBy.VIEW_COUNT);

// search for puppies and include restricted content in the search results
query.setFullTextQuery("puppy");
query.setSafeSearch(YouTubeQuery.SafeSearch.NONE);

VideoFeed videoFeed = service.query(query, VideoFeed.class);
printVideoFeed(videoFeed, true);

In the client library code, the Query class and subclasses like YouTubeQuery are responsible for constructing feed URLs. 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.

setAuthor
The setAuthor method sets the author of the entry.
setFormats
The setFormats method specifies a video format or a set of video formats.
setFullTextQuery
The setFullTextQuery method sets a search query term. Searches for the specified string in all video metadata, such as titles, tags, and descriptions.
setLocation
The setLocation method specifies geographic coordinates (latitude, longitude) for a specific location.
setLocationRadius
The setLocationRadius method, in conjunction with the setLocation method, defines a geographic area. Search results will include videos associated with locations in that area.
setLocationRestrict
The setLocationRestrict method ensures that each video in the response has coordinates that can be plotted on a map.
setMaxResults
The setMaxResults method sets the maximum number of entries to return at one time.
setOrderBy
The setOrderBy method sets the order in which to list entries, such as by RELEVANCE, VIEW_COUNT, UPDATED, or RATING.
setSafeSearch
The setSafeSearch method indicates amount of filtering (NONE, MODERATE or STRICT) that YouTube should apply to remove restricted content from search results.
setStartIndex
The setStartIndex method sets the 1-based index of the first result to be retrieved (for paging).
setTime
The setTime method sets a time period to limit standard feed results to: TODAY, THIS_WEEK, THIS_MONTH, or ALL_TIME.
setUploader
The setUploader 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 CATEGORY_SCHEME categorization, while keywords correspond to the KEYWORD_SCHEME categorization.

YouTubeQuery query = new YouTubeQuery(new URL("http://gdata.youtube.com/feeds/api/videos"));

// a category filter holds a collection of categories to limit the search
Query.CategoryFilter categoryFilter1 = new Query.CategoryFilter();
Query.CategoryFilter categoryFilter2 = new Query.CategoryFilter();
Query.CategoryFilter categoryFilter3 = new Query.CategoryFilter();

//this restricts to videos tagged with the keywords "sports" and "football"
categoryFilter1.addCategory(new Category(YouTubeNamespace.KEYWORD_SCHEME, "sports"));
categoryFilter2.addCategory(new Category(YouTubeNamespace.KEYWORD_SCHEME, "football"));
//this restricts to videos in the category of "News".
categoryFilter3.addCategory(new Category(YouTubeNamespace.CATEGORY_SCHEME, "News"));

// multiple filters mean "AND" in a category query
query.addCategoryFilter(categoryFilter1);
query.addCategoryFilter(categoryFilter2);
query.addCategoryFilter(categoryFilter3);

VideoFeed videoFeed = service.query(query, VideoFeed.class);
printVideoFeed(videoFeed, true);

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(new URL("http://gdata.youtube.com/feeds/api/videos"));

// a category filter holds a collection of categories to limit the search
Query.CategoryFilter categoryFilter1 = new Query.CategoryFilter();
Query.CategoryFilter categoryFilter2 = new Query.CategoryFilter();

//this restricts to videos tagged with the keywords "sports" and "football"
categoryFilter1.addCategory(new Category(YouTubeNamespace.KEYWORD_SCHEME, "sports"));
categoryFilter1.addCategory(new Category(YouTubeNamespace.KEYWORD_SCHEME, "football"));
//this restricts to videos in the category of "News".
categoryFilter2.addCategory(new Category(YouTubeNamespace.CATEGORY_SCHEME, "News"));

// multiple filters mean "AND" in a category query
query.addCategoryFilter(categoryFilter1);
query.addCategoryFilter(categoryFilter2);

VideoFeed videoFeed = service.query(query, VideoFeed.class);
printVideoFeed(videoFeed, true);

Similarly, if you wanted to locate videos that matched either the "News" category OR the keyword "sports" OR the keyword "football", you would create one CategoryFilter object for all of those terms.

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(new URL("http://gdata.youtube.com/feeds/api/videos"));
Query.CategoryFilter categoryFilter = new Query.CategoryFilter();
categoryFilter.addCategory(new Category(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "xyzzy"));
      
query.addCategoryFilter(categoryFilter);

VideoFeed videoFeed = service.query(query, VideoFeed.class);
printVideoFeed(videoFeed, true);

Paging through results

API responses contain pagination links for the previous and/or next page of entries in a feed. The following code sample demonstrates how to retrieve the previous and next pages of results for a feed:

// See if the feed specifies a previous page of results.
if(videoFeed.getPreviousLink() != null) {
  previousVideoFeed = 
    service.getFeed(new URL(videoFeed.getPreviousLink().getHref()), 
    VideoFeed.class);
}

// See if the feed specifies a next page of results.
if(videoFeed.getNextLink() != null) {
  nextVideoFeed = service.getFeed(new URL(videoFeed.getNextLink().getHref()), 
    VideoFeed.class);
}

So, for example, you could use the following code to retrieve all results for a feed. This code performs the following operations:

  1. It retrieves a feed.
  2. It prints out all of the entries in the feed.
  3. It determines whether additional results for the feed are available.
    • If additional results are available, the code returns to step 1. (At this point, the feed being retrieved in step 1 is the next page of results.) The code repeats these steps until no additional results are available.

// Recursive function to print an entire feed.
public static void printEntireVideoFeed(YouTubeService service, 
  VideoFeed videoFeed, boolean detailed) throws MalformedURLException, 
  IOException, ServiceException {
 do {
   printVideoFeed(videoFeed, detailed);
   if(videoFeed.getNextLink() != null) {
     videoFeed = service.getFeed(new URL(videoFeed.getNextLink().getHref()), 
       VideoFeed.class);
   }
   else {
     videoFeed = null;
   }
 }
 while(videoFeed != null);
}

// Sample use of recursive function. Print all results for search term "puppy".
YouTubeQuery query = 
  new YouTubeQuery(new URL("http://gdata.youtube.com/feeds/api/videos"));
query.setFullTextQuery("puppy");
VideoFeed videoFeed = service.query(query, VideoFeed.class);
printEntireVideoFeed(service, videoFeed, false);

In an actual implementation, you might prefer to display pagination links rather than display all feed results on a single page. Since a feed could contain dozens or hundreds of results, pagination links might contribute to a more polished user interface.

If you do display pagination links, please be careful not to expose your developer credentials in those links. For example, if you use the client and key query parameters in API requests, then the pagination links in the API response will contain those values. As such, you would not want to expose those URLs directly through your user interface.

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 VideoEntry 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:

VideoEntry newEntry = new VideoEntry();

YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
mg.setTitle(new MediaTitle());
mg.getTitle().setPlainTextContent("My Test Movie");
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Autos"));
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword("cars");
mg.getKeywords().addKeyword("funny");
mg.setDescription(new MediaDescription());
mg.getDescription().setPlainTextContent("My description");
mg.setPrivate(false);
mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "mydevtag"));
mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "anotherdevtag"));

newEntry.setGeoCoordinates(new GeoRssWhere(37.0,-122.0));
// alternatively, one could specify just a descriptive string
// newEntry.setLocation("Mountain View, CA");

MediaFileSource ms = new MediaFileSource(new File("file.mov"), "video/quicktime");
newEntry.setMediaSource(ms);

String uploadUrl =
  "http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";

VideoEntry createdEntry = service.insert(new URL(uploadUrl), newEntry);

To upload videos as private, pass a value of true to the setPrivate method used in the example above.

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 MediaFileSource object to the VideoEntry 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 VideoEntry 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 VideoEntry 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 VideoEntry object as a parameter to the getFormUploadToken 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:

    VideoEntry newEntry = new VideoEntry();
    
    YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
    mg.setTitle(new MediaTitle());
    mg.getTitle().setPlainTextContent("My Test Movie");
    mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Autos"));
    mg.setKeywords(new MediaKeywords());
    mg.getKeywords().addKeyword("cars");
    mg.getKeywords().addKeyword("funny");
    mg.setDescription(new MediaDescription());
    mg.getDescription().setPlainTextContent("My description");
    mg.setPrivate(false);
    mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "mydevtag"));
    mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "anotherdevtag"));
    
    newEntry.setGeoCoordinates(new GeoRssWhere(37.0,-122.0));
    // alternatively, one could specify just a descriptive string
    // newEntry.setLocation("Mountain View, CA");
    
    URL uploadUrl = new URL("http://gdata.youtube.com/action/GetUploadToken");
    FormUploadToken token = service.getFormUploadToken(uploadUrl, newEntry);
    
    System.out.println(token.getUrl());
    System.out.println(token.getToken());
    
  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 VideoEntry object to determine whether YouTube is still processing the video, failed to process the video, or rejected the video.

if(entry.isDraft()) {
  System.out.println("Video is not live");
  YtPublicationState pubState = entry.getPublicationState();
  if(pubState.getState() == YtPublicationState.State.PROCESSING) {
    System.out.println("Video is still being processed.");
  }
  else if(pubState.getState() == YtPublicationState.State.REJECTED) {
    System.out.print("Video has been rejected because: ");
    System.out.println(pubState.getDescription());
    System.out.print("For help visit: ");
    System.out.println(pubState.getHelpUrl());
  }
  else if(pubState.getState() == YtPublicationState.State.FAILED) {
    System.out.print("Video failed uploading because: ");
    System.out.println(pubState.getDescription());
    System.out.print("For help visit: ");
    System.out.println(pubState.getHelpUrl());
  }
}

Updating and deleting videos

Updating video information

To modify the metadata for a video, update the VideoEntry object and then use the update method. The following code demonstrates how to update the video's description.

entry.getMediaGroup().getDescription().setPlainTextContent("new description");
entry.update();

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 VideoEntry object 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.

videoEntry.delete();

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, insert a Rating object to the ratings feed URL for the VideoEntry that is being rated. The following code shows how to add a rating to a video:

String ratingUrl = entry.getRatingLink().getHref();
Rating myRating = new Rating();
myRating.setValue(5);
myRating.setMax(5);
myRating.setMin(1);
entry.setRating(myRating);
service.insert(new URL(ratingUrl), entry);

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 VideoEntry object and then print the comments for the video.

String commentUrl = videoEntry.getComments().getFeedLink().getHref();
       
CommentFeed commentFeed = service.getFeed(new URL(commentUrl), CommentFeed.class);
for(CommentEntry comment : commentFeed.getEntries()) {
  System.out.println(comment.getPlainTextContent());
}

Adding a comment

To add a comment to a video, insert a CommentEntry object into the comments feed URL for the video. The following code demonstrates how to retrieve the comments feed URL for a video and then add a new comment for a video:

commentUrl = videoEntry.getComments().getFeedLink().getHref();
CommentEntry newComment = new CommentEntry();
newComment.setContent(new PlainTextConstruct("my pithy comment"));
service.insert(new URL(commentUrl), newComment);

Users can also add a comment as a reply to an existing comment as shown in the following sample code. In the code sample, the entry is the existing CommentEntry object that is being commented on.

CommentEntry newComment = new CommentEntry();
newComment.setContent(new PlainTextConstruct("I disagree with your comment"));
newComment.getLinks().add(new Link(YouTubeNamespace.IN_REPLY_TO,
                                   "application/atom+xml",
                                   entry.getSelfLink().getHref()));

service.insert(new URL(feedUrl), newComment);

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 ComplaintEntry to the complaints link for the VideoEntry 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:

String complaintUrl = badVideoEntry.getComplaintsLink().getHref();
ComplaintEntry complaintEntry = new ComplaintEntry();
complaintEntry.setComment("This video offends my sensibilities.");
complaintEntry.getCategories().add(
  new Category(YouTubeNamespace.COMPLAINT_REASON_SCHEME, "RIGHTS"));
service.insert(new URL(complaintUrl), complaintEntry);

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 VideoEntry objects.

String feedUrl = "http://gdata.youtube.com/feeds/api/users/YTDebates/favorites";
    
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
printVideoFeed(videoFeed, true);

Adding a favorite video

To add a favorite video, insert a VideoEntry object that identifies the video to the authenticated user's favorite videos feed.

String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/VIDEO_ID";
VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl), VideoEntry.class);

service.insert(new URL(feedUrl), videoEntry);

Deleting a favorite video

To delete a favorite video from the currently authenticated user's favorite videos feed, call the delete method on the VideoEntry object that corresponds to the favorite video you want to delete.

favoriteVideoEntry.delete();

Note: You must retrieve the VideoEntry 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:

String feedUrl = "http://gdata.youtube.com/feeds/api/users/YTdebates/playlists";

PlaylistLinkFeed feed = service.getFeed(new URL(feedUrl), PlaylistLinkFeed.class);

for(PlaylistLinkEntry entry : feed.getEntries()) {
  System.out.println("Title: " + entry.getTitle().getPlainText());
  System.out.println("Description: " + entry.getSummary().getPlainText());
  System.out.println("Number of entries: " + entry.getCountHint());
}

Retrieving playlist information

The following code demonstrates how to use a PlaylistLinkEntry, as retrieved in the previous example, to retrieve and print information about the videos in that playlist.

String playlistUrl = entry.getFeedUrl();

PlaylistFeed playlistFeed = service.getFeed(new URL(playlistUrl), PlaylistFeed.class);

for(PlaylistEntry playlistEntry : playlistFeed.getEntries()) {
  System.out.println("Title: " + playlistEntry.getTitle().getPlainText());
  System.out.println("Description: " + playlistEntry.getSummary().getPlainText());
  System.out.println("Position: " + playlistEntry.getPosition());
  System.out.println("Video URL: " + playlistEntry.getHtmlLink().getHref());
}

Note: The PlaylistEntry object inherits from the VideoEntry object. Please see the Video entry contents section for more information about the information that can be retrieved from a VideoEntry object.

Adding a playlist

To add a new playlist, insert a PlaylistLinkEntry into the authenticated user's playlists feed.

String feedUrl = "http://gdata.youtube.com/feeds/api/users/default/playlists";

PlaylistLinkEntry newEntry = new PlaylistLinkEntry();
newEntry.setTitle(new PlainTextConstruct("new playlist"));
newEntry.setSummary(new PlainTextConstruct("this is my new playlist."));

PlaylistLinkEntry createdEntry = service.insert(new URL(feedUrl), newEntry);

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 PlaylistLinkEntry object for that playlist and then call the object's update method.

The following code updates a playlist's description.

playlistLinkEntry.setSummary(new PlainTextConstruct("updated playlist description"));
playlistLinkEntry.update();

Adding a video to a playlist

You can add a video to a playlist by using a VideoEntry object. The following code retrieves a VideoEntry object with a known entry ID and then adds it to the playlist corresponding to the PlaylistLinkEntry object. 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.

String playlistUrl = playlistLinkEntry.getFeedUrl();
String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/ADos_xW4_J0";
VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl), VideoEntry.class);

PlaylistEntry playlistEntry = new PlaylistEntry(videoEntry);
service.insert(new URL(playlistUrl), playlistEntry);

Editing information for a playlist video

You can modify the position of each video in a playlist by updating the PlaylistEntry object for the video and calling its update method.

//move this entry to the top of the playlist
playlistEntry.setPosition(0);
playlistEntry.update();

Removing a video from a playlist

To remove a video from a playlist, use the delete method of the PlaylistEntry.

playlistEntry.delete();

Deleting a playlist

To delete a playlist, call the delete method of the corresponding PlaylistLinkEntry object.

playlistLinkEntry.delete();

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";
    
SubscriptionFeed feed = service.getFeed(new URL(feedUrl), SubscriptionFeed.class);

for(SubscriptionEntry entry : feed.getEntries()) {
  System.out.println("Title: " + entry.getTitle().getPlainText());
  System.out.println("Feed Link: " + entry.getFeedUrl();
}

Adding a subscription

You can create a new subscription by inserting a new SubscriptionEntry 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.

SubscriptionEntry newSubscription = new SubscriptionEntry();
newSubscription.addSubscriptionType(SubscriptionEntry.Type.CHANNEL);
newSubscription.setUsername("GoogleDevelopers");
service.insert(new URL(feedUrl), newSubscription);
Subscribing to a list of favorite videos

The following code subscribes the authenticated user to the "GoogleDevelopers" user's list of favorite videos:

SubscriptionEntry newSubscription = new SubscriptionEntry();
newSubscription.addSubscriptionType(SubscriptionEntry.Type.FAVORITES);
newSubscription.setUsername("GoogleDevelopers");
service.insert(new URL(feedUrl), newSubscription);
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.

SubscriptionEntry newSubscription = new SubscriptionEntry();
newSubscription.addSubscriptionType(SubscriptionEntry.Type.PLAYLIST);
newSubscription.setPlaylistId("586D322B5E2764CF");
service.insert(new URL(feedUrl), newSubscription);
Subscribing to a search query

The following code subscribes the authenticated user to videos that match the search term "puppies":

SubscriptionEntry newSubscription = new SubscriptionEntry();
newSubscription.addSubscriptionType(SubscriptionEntry.Type.QUERY);
newSubscription.setQueryString("puppies");
service.insert(new URL(feedUrl), newSubscription);

Deleting a subscription

To delete a subscription, call the delete method on the corresponding SubscriptionEntry object.

entry.delete();

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 API returns the profile as a UserProfileEntry object. The following code prints out a number of attributes from a specified user's profile:

String profileUrl = "http://gdata.youtube.com/feeds/api/users/YTdebates";
UserProfileEntry profileEntry = service.getEntry(new URL(
    profileUrl), UserProfileEntry.class);
System.out.println("Username: " + profileEntry.getUsername());
System.out.println("Age     : " + profileEntry.getAge());
System.out.println("Gender  : " + profileEntry.getGender());
System.out.println("Single? : " + profileEntry.getRelationship());
System.out.println("Books   : " + profileEntry.getBooks());
System.out.println("Company : " + profileEntry.getCompany());
System.out.println("Description: " + profileEntry.getDescription());
System.out.println("Hobbies : " + profileEntry.getHobbies());
System.out.println("Hometown: " + profileEntry.getHometown());
System.out.println("Location: " + profileEntry.getLocation());
System.out.println("Movies  : " + profileEntry.getMovies());
System.out.println("Music   : " + profileEntry.getMusic());
System.out.println("Job     : " + profileEntry.getOccupation());
System.out.println("School  : " + profileEntry.getSchool());

YtUserProfileStatistics stats = profileEntry.getStatistics();
    
if(stats != null) {
  System.out.println("Subscriber count: " + stats.getSubscriberCount());
  System.out.println("Last web access: " + stats.getLastWebAccess().toUiString());
}

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

FriendFeed friendFeed = service.getFeed(new URL(feedUrl), FriendFeed.class);

for(FriendEntry friendEntry : friendFeed.getEntries()) {
  System.out.print("Friend: " + friendEntry.getUsername());
  System.out.println("Status:" + friendEntry.getStatus().toString());
}

Adding a contact

To add a contact, insert a new FriendEntry 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.

FriendEntry newFriend = new FriendEntry();
newFriend.getCategories().add(new Category(YouTubeNamespace.CONTACT_LIST_SCHEME, "Cool Dudes"));
newFriend.setUsername("GoogleDevelopers");

service.insert(new URL(feedUrl), newFriend);

Accepting or rejecting a contact

You can accept or reject a contact by updating the status of the corresponding FriendEntry object.

The following example shows how to accept a contact:

friendEntry.setStatus(YtStatus.Value.ACCEPTED);
friendEntry.update();

The following example shows how to reject a contact:

friendEntry.setStatus(YtStatus.Value.REJECTED);
friendEntry.update();

Deleting a contact

To delete a contact, call the delete method on the FriendEntry 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";

VideoMessageFeed feed = service.getFeed(new URL(feedUrl), VideoMessageFeed.class);

for(VideoMessageEntry entry : feed.getEntries()) {
  System.out.println("Message from: " + entry.getAuthors().get(0).getName());
  System.out.println("Subject: " + entry.getTitle().getPlainText());
  System.out.println(entry.getSummary().getPlainText());
}

Sending a message

To send a message to a user, construct a VideoMessageEntry object and insert it into the user's inbox feed. Any message sent through the API must specify a VideoEntry object.

The following code sends a message containing a video to a user identified by the variable receivingUser:

String msgUrl =
  "http://gdata.youtube.com/feeds/api/users/"+receivingUser+"/inbox";
String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/Wegp-JOae0g";
VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl), VideoEntry.class);
VideoMessageEntry newMessage = new VideoMessageEntry(videoEntry);
newMessage.setTitle(new PlainTextConstruct("my subject"));
newMessage.setSummary(new PlainTextConstruct("This is the message body."));
service.insert(new URL(msgUrl), 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 VideoMessageEntry object:

entry.delete();

Activity feeds

Activity feeds list actions that a particular user or set of users has taken on the YouTube site. The API enables you to retrieve two types of activity feeds:

  • A subscription activity feed identifies actions associated with the authenticated user's subscriptions.
  • A user activity feed identifies actions taken by one or more users who are specified in the API request.

In addition, the API previously supported a third type of activity feed, the friend activity feed. This feed type has been deprecated, and requests to retrieve a friend activity feed will instead return the authenticated user's subscription activity feed.

User events in activity feeds

Activity feeds list the following events:

  • Rating a video
  • Sharing a video
  • Marking a video as a favorite
  • Commenting on a video
  • Uploading a video
  • Creating a subscription to a channel

Each activity feed entry contains information about a particular event, including the event type as well as additional elements that describe the event. For example, a feed entry that identifies a VIDEO_RATED event contains the YouTube video ID for the video and the rating that the user gave to that video. However, the entry does not contain other metadata like the video's title, description or owner.

To retrieve additional information about the videos or users identified in an activity feed, you should submit a batch processing request, which lets you retrieve up to 50 video entries or user profile entries.

The following sections explain how to retrieve and process activity feeds:

  1. User activity feeds
  2. Friend activity feeds

User activity feeds

To retrieve a user activity feed, make an authenticated request to the following URL. In the request, set the author parameter value to a comma-delimited list of up to 20 YouTube usernames. The API response will contain activities performed by any of those users.

http://gdata.youtube.com/feeds/api/events?author=usernames

The following example sets a list of usernames, retrieves an activity feed for those users, and then prints out some information about each event in the activity feed:

/**
 * Shows a user's activity feed.
 *
 * @param service a YouTubeService object.
 * @throws IOException Error sending request or reading the feed.
 * @throws ServiceException If the service is unable to handle the request.
 */
private static void showActivity(YouTubeService service) throws IOException,
    ServiceException {
  String users = "username1,username2,username3";
  String feed = "http://gdata.youtube.com/feeds/api/events?author=";
  printActivityFeed(service, feed + users);
}

/**
 * Fetches a feed of activities and prints information about them.
 *
 * @param service An authenticated YouTubeService object
 * @param feedUrl The url of the activity feed to print.
 * @throws IOException Error sending request or reading the feed.
 * @throws ServiceException If the service is unable to handle the request.
 */
private static void printActivityFeed(YouTubeService service, String feedUrl)
    throws IOException, ServiceException {
  UserEventFeed activityFeed = service.getFeed(new URL(feedUrl),
      UserEventFeed.class);
  String title = activityFeed.getTitle().getPlainText();
  printUnderlined(title);
  if (activityFeed.getEntries().size() == 0) {
    System.out.println("This feed contains no entries.");
    return;
  }
  for (UserEventEntry entry : activityFeed.getEntries()) {
    String user = entry.getAuthors().get(0).getName();
    if(entry.getUserEventType() == UserEventEntry.Type.VIDEO_UPLOADED) {
      System.out.println(user + " uploaded a video " + entry.getVideoId());
    }
    else if(entry.getUserEventType() == UserEventEntry.Type.VIDEO_RATED) {
      System.out.println(user + " rated a video " + entry.getVideoId() +
          " " + entry.getRating().getValue() + " stars");
    }
    else if(entry.getUserEventType() == UserEventEntry.Type.VIDEO_FAVORITED) {
      System.out.println(user + " favorited a video " + entry.getVideoId());
    }
    else if(entry.getUserEventType() == UserEventEntry.Type.VIDEO_SHARED) {
      System.out.println(user + " shared a video " + entry.getVideoId());
    }
    else if(entry.getUserEventType() == UserEventEntry.Type.VIDEO_COMMENTED) {
      System.out.println(user + " commented on video " + entry.getVideoId());
    }
    else if(entry.getUserEventType()
        == UserEventEntry.Type.USER_SUBSCRIPTION_ADDED) {
      System.out.println(user + " subscribed to the channel of " +
          entry.getUsername());
    }
    else if(entry.getUserEventType() == UserEventEntry.Type.FRIEND_ADDED) {
      System.out.println(user + " friended " + entry.getUsername());
    }
  }
  System.out.println();
}

Friend activity feeds

To retrieve a friend activity feed, make an authenticated request to the following URL. Note that a user can only retrieve the friend activity feed for her own friends.

http://gdata.youtube.com/feeds/api/users/default/friendsactivity

The following example retrieves the logged-in user's friend activity feed and then prints information about each event in the feed:

/**
 * Shows a user's friends' activity feed.
 *
 * @param service a YouTubeService object.
 * @throws IOException Error sending request or reading the feed.
 * @throws ServiceException If the service is unable to handle the request.
 */
private static void showFriendsActivity(YouTubeService service) 
    throws OException, ServiceException {
  printActivityFeed(service,
    "http://gdata.youtube.com/feeds/api/users/default/friendsactivity");
}

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

// include batch namespace
import com.google.gdata.data.batch.*;

// retrieve a playlist feed and do some batch operations on it
PlaylistFeed feed = service.getFeed(new URL(feedUrl), PlaylistFeed.class);

// retrieve the batch link from the feed
URL batchUrl = new URL(feed.getFeedBatchLink().getHref());
PlaylistFeed batchFeed = new PlaylistFeed();

// delete the third playlist entry
PlaylistEntry entryToDelete = feed.getEntries().get(2);
BatchUtils.setBatchId(entryToDelete, "B");
BatchUtils.setBatchOperationType(entryToDelete, BatchOperationType.DELETE);
batchFeed.getEntries().add(entryToDelete);

// add a new video to the playlist
PlaylistEntry entryToAdd = new PlaylistEntry();
entryToAdd.setId("mTrp-GKG9Bo");
BatchUtils.setBatchId(entryToAdd, "A");
BatchUtils.setBatchOperationType(entryToAdd, BatchOperationType.INSERT);
batchFeed.getEntries().add(entryToAdd);

// move the second entry to the top of the playlist
PlaylistEntry entryToUpdate = feed.getEntries().get(1);
entryToUpdate.setPosition(0);
BatchUtils.setBatchId(entryToUpdate, "C");
BatchUtils.setBatchOperationType(entryToUpdate, BatchOperationType.UPDATE);
batchFeed.getEntries().add(entryToUpdate);

// return the updated entry
PlaylistEntry entryToGet = feed.getEntries().get(0);
BatchUtils.setBatchId(entryToGet, "D");
BatchUtils.setBatchOperationType(entryToGet, BatchOperationType.QUERY);
batchFeed.getEntries().add(entryToGet);

PlaylistFeed batchResponse = service.batch(batchUrl, batchFeed);

for(PlaylistEntry entry : batchResponse.getEntries()) {
 if(BatchUtils.isSuccess(entry)) {
   System.out.println("Operation " + BatchUtils.getBatchId(entry) + " succeeded!");
   String operation = BatchUtils.getBatchOperationType(entry).getName();
   System.out.println("The " + operation + " worked!");
 }
 else {
   System.out.println("Operation " + BatchUtils.getBatchId(entry) + "failed!");
   BatchStatus status = BatchUtils.getBatchStatus(entry);
   System.out.println(status.getCode() + " - " + status.getContent());
 }
}

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.