The YouTube Data API allows client applications to view YouTube content in the form of Google Data API feeds. Your client application can use the YouTube Data API feeds 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 used by the Java client library to interact with YouTube, see the Protocol Guide.
This document is intended for programmers who want to write client applications that can interact with YouTube using the Java client library. It provides a series of examples of basic data API interactions.
For YouTube Data API reference information, 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.
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 GData APIs. Throughout this document, the explanations of specific API functions will clearly indicate whether the function requires user authentication.
The Understanding video feeds and entries section provides a sample API responses 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 meta-data about a specific video entry.
The Retrieving and searching for videos section explains how to fetch a list of videos. The YouTube Data API defines several types of standard feeds, such as top-rated or most-viewed videos. This section explains how also to retrieve a list of videos uploaded by a specific user or a list of related videos. Finally, this section explains how to use the API to let users search through YouTube's video library for videos matching specific search terms or categories.
The Uploading videos section briefly explains two ways that you can allow users to upload videos to YouTube from your application. This section also explains how to let users delete videos from your application. These solutions are explained in more detail in the Protocol Guide. You may need to let users upload videos to use certain other API functions. For example, the API provides a function for adding a video response to a video. If the user is uploading a new video as a video response, then your client will need to follow the video uploading instructions to add the video to YouTube before identifying the new video as a response.
The Updating and deleting videos section describes how to use the API to update information about a YouTube video. It also describes how a video can be removed using the API.
The Using community features section describes API functions that allow your users to interact with YouTube videos. These functions explain requests for posting a rating, comment, video response or complaint to an existing video. You can also use the API to retrieve lists of video comments or video responses or to delete a video response.
The Saving and collecting videos section explains how to use the API to access, create and update favorite videos, video playlists and subscriptions to YouTube channels.
The Enabling user interaction section explains how to use the API to retrieve and update user profiles. This section also explains how to retrieve, add, update and delete user contacts as well as how to retrieve, send and delete messages.
For help setting up the 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 available in the
distribution, at gdata/java/sample/youtube/YouTubeClient.java.
Build and execution instructions are included in the same directory in
the README.txt file. The sample performs a number of
operations on the YouTube Data API feeds to demonstrate the use of the
API. For a list of the operations performed, see the main method of the sample client application.
To compile the example snippets provided in this document into your own code, you'll 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;
The Java client library can be used to work with either public or private feeds. Public feeds are read-only, but do not require any authentication. Some YouTube feeds can be accessed without authenticating, but all changes to a feed require authentication. This can be done via ClientLogin username/password authentication or AuthSub proxy authentication.
In order to perform any write or upload operations using the YouTube API, you have to instantiate a YouTubeService object with your clientID and developer key as follows:
YouTubeService service = new YouTubeService(clientID, developer_key);
If you don't have a developer key, you can apply for a developer key. This page will also provide you with a clientID.
Please see the authentication documentation for more information on AuthSub and ClientLogin.
To acquire an AuthSub token for a given user and a given service, your application must redirect the user to the AuthSubRequest URL, which prompts them to log into their Google account.
For more information on the AuthSubRequest URL, see the AuthSub documentation.
To construct the AuthSubRequest URL for your application, make a Java client library call as follows:
String requestUrl =
AuthSubUtil.getRequestUrl("http://www.example.com/RetrieveToken",
"http://gdata.youtube.com",
false,
true);
The getRequestUrl method takes several parameters (corresponding to the query parameters used by the AuthSubRequest handler): the "next" URL (which is the URL that Google will redirect to after the user logs into their account and grants access); the scope (as determined in the previous section); and two booleans, one to indicate whether the token will be used in registered mode or not, and one to indicate whether the token will later be exchanged for a session token or not. The above example shows a call in unregistered mode (the first boolean is false), for a token that will be exchanged for a session token later (the second boolean is true); adjust the booleans appropriately for your application.
After constructing the "next" URL, your server-side application can use it in a variety of ways to send the user to the AuthSubRequest handler. The most common approach is to display a page that tells the user that they need to follow a link to authorize your application to access your Google account; then attach the request URL to the link. For example, you could display the following string on a page:
String suggestAuthorization = "<p>MyApp needs access to your YouTube account. To authorize MyApp to access your account, <a href=\"" + requestUrl + "\">log in to your account</a>.</p>";
The user follows the link to the AuthSub page at Google, and logs in. The AuthSub system then redirects the user back to your application, using the "next" URL you provided.
When Google redirects back to your application, the token is appended to the "next" URL as a query parameter. So in the case of the above "next" URL, after the user logs in, Google redirects to a URL like http://www.example.com/RetrieveToken?token=DQAADKEDE.
The user's browser is redirected to that URL. The servlet handling that URL should then examine the query parameters in the requested URL to retrieve the token set by Google. For example, the servlet can retrieve the token from the URL by using the convenience function getTokenFromReply from the Java client library:
String onetimeUseToken = AuthSubUtil.getTokenFromReply(httpServletRequest.getQueryString());
Your application can recognize which user has authenticated with Google's servers using AuthSub by setting an authentication cookie prior to having them click the AuthSub link, then reading this cookie after the user has been authenticated and returned to your webpage.
The token you retrieve with getTokenFromReply is always a one-time use token. You can exchange this token for a session token using the AuthSubSessionToken URL, as described in the AuthSub documentation. Your application can make this exchange using the Java client library as follows:
String sessionToken = AuthSubUtil.exchangeForSessionToken(onetimeUseToken,
null);
You pass your one-time use token to the exchangeForSessionToken method, along with either null (for unregistered mode) or a private key (for registered mode), and the AuthSub interface returns a session token. For more information about registered applications and private keys, refer to the AuthSub documentation.
You can use the session token to authenticate requests to the server by placing the token in the Authorization header, as described in the AuthSub documentation. To tell the Java client library to automatically send the Authorization header (containing the session token) with each request, you call the YouTubeService object's setAuthSubToken method:
YouTubeService service = new YouTubeService(clientID, developer_key); service.setAuthSubToken(sessionToken, null);
If you're using registered mode, then you provide your private key instead of null. Also note you have to pass a clientID and developer key to the constructor of YouTubeService.
After you've called setAuthSubToken, you can use the standard GData client library calls to interact with the service, without having to think about the token.
If you want to retrieve information about the token's parameters, you can pass the token to the getTokenInfo method, which returns a set of name-value pairs containing information about the token. For example:
Map<String, String> info = AuthSubUtil.getTokenInfo(sessionToken, null);
AuthSub session tokens don't expire; your client can store the session token for as long as needed.
When your client is done using the session token, it can revoke the token using the AuthSubRevokeToken handler, as described in the AuthSub documentation.
For example, if you want to manage tokens in a traditional session-like way, then your client can get a token at the beginning of a user's session and revoke it at the end of the user's session.
To revoke a token using the Java client library, call revokeToken. Include your private key for registered mode, or null otherwise. For example:
AuthSubUtil.revokeToken(sessionToken, null);
To use ClientLogin (also called "Authentication for Installed Applications"), invoke the setUserCredentials method of YouTubeService, specifying the ID and password of the user on whose behalf your client is sending the query. For example:
YouTubeService service = new YouTubeService(clientID, developer_key);
service.setUserCredentials("jo@gmail.com", "password");
Note that you also have to provide a clientID and developer key to the YouTubeService object in order to perform write operations and retrieve private feeds using the YouTube API. You can apply for a developer key if you don't have one.
For more information about authentication systems, see the Google Account Authentication documentation.
The YouTube Data API provides several video feeds that represent lists of videos, such as standard feeds, uploads, subscriptions, and favorites. The URL for each feed is documented in the reference guide.
Many feeds in the YouTube API consist of video entries. These feeds can most simply be modeled as VideoFeed objects, each containing a number of VideoEntry objects. Each video entry corresponds to exactly one video on YouTube and contains information about the video.
The basic structure of retrieving a list of videos is to construct a URL to a video feed and then process the entries one at a time, similar to the following code:
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
for(VideoEntry entry : videoFeed.getEntries() ) {
System.out.println("Title: " + entry.getTitle().getPlainText());
System.out.println(entry.getMediaGroup().getDescription().getPlainTextContent());
}
The Retrieving and searching for videos section details many common feed URLs and how to retrieve various video feeds.
You can retrieve just the information for a specific video entry if you know its self link, which is a link element within the Atom entry describing the video with the rel attribute set to self. The self link is a URL that is based on the video ID:
http://gdata.youtube.com/feeds/api/videos/videoID
In the case of video entries, the self link is also identical to the entry ID provided in the id element.
The following code retrieves a VideoEntry corresponding to video on YouTube:
String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/ADos_xW4_J0";
VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl), VideoEntry.class);
System.out.println("Title: " + videoEntry.getTitle().getPlainText());
System.out.println(videoEntry.getMediaGroup().getDescription().getPlainTextContent());
There are many pieces of meta-data that can be retrieved from a VideoEntry object, such as thumbnails, player URLs, and video duration. The following code demonstrates how to get at some of this information. For a complete list of all possible XML elements, please read the reference guide.
System.out.println("Title: " + videoEntry.getTitle().getPlainText());
System.out.println("Uploaded by: " + videoEntry.getAuthors().get(0).getName());
YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
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();
}
The YouTube Data API currently provides standard feeds of videos for various criteria. These feeds are site-wide, not user specific. The URLs of all standard feeds
start with http://gdata.youtube.com/feeds/api/standardfeeds/,
followed by the feed's identifier. Here is a table of the available feeds:
| Feed Name | Feed Identifier |
|---|---|
| Most Viewed | most_viewed |
| Top Rated | top_rated |
| Recently Featured | recently_featured |
| Watch On Mobile | watch_on_mobile |
| Most Discussed | most_discussed |
| Top Favorites | top_favorites |
| Most Linked | most_linked |
| Most Responded | most_responded |
| Most Recent | most_recent |
You can also retrieve locale-specific standard feeds by specifying a localeID in the format: http://gdata.youtube.com/feeds/api/standardfeeds/localeID/feedID. For example, the most viewed videos in Japan would be: http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_viewed.
The below example prints out the titles and description of the most viewed videos on the site:
String feedUrl = "http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed";
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
for(VideoEntry entry : videoFeed.getEntries() ) {
System.out.println("Title: " + entry.getTitle().getPlainText());
System.out.println(entry.getMediaGroup().getDescription().getPlainTextContent());
}
Each YouTube user has an associated video feed corresponding to the
videos he or she has uploaded, at /feeds/api/users/userID/uploads.
The following code prints out the titles and descriptions of the videos uploaded by the "GoogleDevelopers" user.
String feedUrl = "http://gdata.youtube.com/feeds/api/users/GoogleDevelopers/uploads";
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
for(VideoEntry entry : videoFeed.getEntries() ) {
System.out.println("Title: " + entry.getTitle().getPlainText());
System.out.println(entry.getMediaGroup().getDescription().getPlainTextContent());
}
You can use the username "default" to refer to the currently authenticated user. So to retrieve the videos for the authenticated user, you would use the URL http://gdata.youtube.com/feeds/api/users/default/uploads.
Each video entry in a video feed has a link to another video feed containing all related videos, as determined by YouTube. The following code shows how to retrieve and print information about the related videos of a particular VideoEntry.
if (videoEntry.getRelatedVideosLink() != null) {
String feedUrl = videoEntry.getRelatedVideosLink().getHref();
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
for(VideoEntry entry : videoFeed.getEntries() ) {
System.out.println("Title: " + entry.getTitle().getPlainText());
System.out.println(entry.getMediaGroup().getDescription().getPlainTextContent());
}
}
The YouTube data API lets you request a set of entries that match
specified criteria, such as requesting video entries published by a
particular author or containing a particular keyword. To do this, you
create a YouTubeQuery object and pass it to the
YouTubeService.query() method.
For example, to perform a
keyword query, with results ordered by view count, and include
restricted videos, use the setVideoQuery, setOrderBy, and setIncludeRacy methods of the YouTubeQuery object. The following code snippet prints the titles and summaries of all videos matching the keyword "puppy", including restricted videos, 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);
// do not exclude restricted content from the search results
query.setIncludeRacy(true);
//search for puppies!
query.setVideoQuery("puppy");
VideoFeed videoFeed = service.query(query, VideoFeed.class);
for(VideoEntry entry : videoFeed.getEntries() ) {
System.out.println("Title: " + entry.getTitle().getPlainText());
System.out.println(entry.getMediaGroup().getDescription().getPlainTextContent());
}
The Query class, and subclasses like YouTubeQuery,
are responsible for constructing feed URLs. The YouTubeQuery shown
above constructs a URL equivalent to the following:
http://gdata.youtube.com/feeds/api/videos?vq=keyword&racy=include&orderby=viewCount
Here are some of the most common YouTubeQuery methods
for setting search parameters:
setAuthorsetMaxResultssetStartIndexsetVideoQuerysetIncludeRacysetFormatssetOrderByRELEVANCE, VIEW_COUNT, UPDATED, or RATING.setTimeTODAY, THIS_WEEK, THIS_MONTH, or ALL_TIME.For more information about query parameters, see the YouTube Data API Reference Guide and the Google Data APIs Reference Guide.
You can restrict search results to show only videos that match a given set of categories and keywords. The reference guide describes how to specify both predefined YouTube categories and user-defined keywords (also known as tags).
The following code demonstrates how to search using keywords, which corresponds to using the KEYWORD_SCHEME categorization, and how to search using YouTube categories, which corresponds to using the CATEGORY_SCHEME categorization. Remember that every video can have many keywords, but only one category.
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 keyword "puppy".
categoryFilter1.addCategory(new Category(YouTubeNamespace.KEYWORD_SCHEME, "puppy"));
//this restricts to videos in the category of "Comedy".
categoryFilter2.addCategory(new Category(YouTubeNamespace.CATEGORY_SCHEME, "Comedy"));
// multiple filters mean "AND" in a category query
query.addCategoryFilter(categoryFilter1);
query.addCategoryFilter(categoryFilter2);
VideoFeed videoFeed = service.query(query, VideoFeed.class);
for(VideoEntry entry : videoFeed.getEntries() ) {
System.out.println("Title: " + entry.getTitle().getPlainText());
System.out.println(entry.getMediaGroup().getDescription().getPlainTextContent());
}
In the above code retrieves all videos inside of the Comedy category that have the keyword of "puppy". If you wanted to retrieve videos that were either in the "Comedy" category or having the keyword of "puppy", you can simply use a single CategoryFilter that contains both Category objects.
A list of all usable categories is available at: http://gdata.youtube.com/schemas/2007/categories.cat.
Developer tags are additional, hidden keywords that a developer may use to tag their uploaded content. These keywords will not be visible to the public, but may be used to retrieve videos. The following code retrieves a feed of all videos with the developer tag 'xyzzy':
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);
for(VideoEntry entry : videoFeed.getEntries() ) {
System.out.println("Title: " + entry.getTitle().getPlainText());
System.out.println(entry.getMediaGroup().getDescription().getPlainTextContent());
}
In order to retrieve videos with a developer tag, you must use the developer key that was used to upload the video with that tag. You do not need to authenticate the request, only provide the developer key.
Uploading videos can be done in one of two ways: either by uploading the video directly or by sending just the video meta-data and having a user upload the video through an HTML form.
Uploaded videos will take some time to be processed and indexed on YouTube. Under conditions of heavy load, they may not be visible in the public feeds until the next day. However, they should be visible in the authenticated user's uploads feed immediately. Please see the section Checking upload status for more information.
In order to upload a video, you must first construct a new VideoEntry object and specify some required members. The following example shows uploading the Quicktime video "file.mov" to YouTube with the following properties:
| Property | Value |
|---|---|
| Title | testing |
| Category | Autos |
| Keywords | foo |
| Description | my description |
| Filename | file.mov |
| File MIME type | video/quicktime |
| Video private? | false |
| Video location | 37,-122 (lat,long) |
| Developer tag | xyzzy |
The following fields are mandatory when uploading a video: title, description, category, and keywords.
VideoEntry newEntry = new VideoEntry();
newEntry.setGeoCoordinates(new GeoRssWhere(37.0,-122.0));
//alternatively, one could specify just a descriptive string
newEntry.setLocation("Mountain View, CA");
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Autos"));
mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "xyzzy"));
mg.setPrivate(false);
mg.setTitle(new MediaTitle());
mg.getTitle().setPlainTextContent("testing");
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword("foo");
mg.setDescription(new MediaDescription());
mg.getDescription().setPlainTextContent("my description");
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);
Browser-based uploads allows your site to have the user's browser upload the video directly to YouTube. This method of uploading uses a special URL instead of the authenticated user's uploads URL:
http://gdata.youtube.com/action/GetUploadToken
Although the user will be uploading the video file directly, your code must first send the meta-data of the video to YouTube, in a fashion almost identical to direct uploading. This only difference, besides the custom URL, is that you do not attach a MediaFileSource object to the VideoEntry you are constructing.
The following fields are mandatory when uploading a video: title, description, category, and keywords.
VideoEntry newEntry = new VideoEntry();
newEntry.setGeoCoordinates(new GeoRssWhere(37.0,-122.0));
//alternatively, one could specify just a descriptive string
newEntry.setLocation("Mountain View, CA");
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Autos"));
mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "xyzzy"));
mg.setTitle(new MediaTitle());
mg.setPrivate(false);
mg.getTitle().setPlainTextContent("testing");
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword("foo");
mg.setDescription(new MediaDescription());
mg.getDescription().setPlainTextContent("my description");
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());
The above code prints out a link and a token that is used to construct an HTML form to display in the user's browser. A simple example form is shown below, with post_url representing the value of token.getUrl() and token_value representing 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>
In order for the user to be redirected to your website after submitting the form, make sure to append a nexturl parameter to the post_url above, which functions identically to the next parameter of an AuthSub link.
After uploading a video, it will immediately be visible in an authenticated user's uploads feed:
http://gdata.youtube.com/feeds/api/users/default/uploads
However, it will not be public on the site until it has been processed. Videos that have been rejected or failed to upload successfully will also only be in the authenticated user's uploads feed. The following code checks the status of a VideoEntry to see if it is not live yet or if it has been rejected.
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());
}
}
To update video meta-data, simply update the VideoEntry object and use the update method. The following example updates a video description:
entry.getMediaGroup().getDescription().setPlainTextContent("new description");
entry.update();
Deleting a video is as simple as retrieving the uploads feed for the authenticated user and invoking the delete method on the VideoEntry object for that video.
videoEntry.delete();
To rate a video, simply add a Rating object to a VideoEntry and POST it to the rating link of that VideoEntry.
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);
Given a VideoEntry object, you can retrieve and print a
feed containing the comments for the video using the following
code:
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());
}
Once you have retrieved the comment URL as shown in the previous section, you can submit a new comment.
CommentEntry newComment = new CommentEntry();
newComment.setContent(new PlainTextConstruct("my pithy comment"));
service.insert(new URL(commentUrl), newComment);
You can also add a comment as a reply to an existing comment. The below code shows how to do this assuming that entry is an existing CommentEntry object.
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.getId()));
service.insert(new URL(commentUrl), newComment);
Each video entry in a video feed can have an associated video response
feed, which is itself a video feed. This code demonstrates how
to retrieve and print information about the video responses for a given VideoEntry.
if (videoEntry.getVideoResponsesLink() != null) {
String feedUrl = videoEntry.getVideoResponsesLink().getHref();
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
for(VideoEntry entry : videoFeed.getEntries() ) {
System.out.println("Title: " + entry.getTitle().getPlainText());
System.out.println(entry.getMediaGroup().getDescription().getPlainTextContent());
}
}
For more information about how you can retrieve feeds from within the various objects, see Navigating between feeds in the Reference guide.
After retrieving a video response link, as demonstrated in the previous section, you can POST a VideoEntry corresponding to a video that you would like to flag as being a video response to the original video.
service.insert(new URL(responseVideosLink), videoResponseEntry);
If you retrieved the video responses as a feed, you can also insert directly into the VideoFeed object.
videoFeed.insert(videoResponseEntry);
Remember that all video responses have to be approved by the owner of the video you responded to before they will show up in the video responses feed.
If you have own one of the videos listed in a VideoFeed object that is retrieved by using a video responses link, you can remove your video as a video response by calling delete on that entry.
videoResponseEntry.delete();
Adding a complaint about a video is done through POSTing an Atom entry to the complaints link of the VideoEntry object. The below code gives an example of flagging a video.
String complaintUrl = badVideoEntry.getComplaintsLink().getHref();
ComplaintEntry complaintEntry = new ComplaintEntry();
complaintEntry.setComment("This video offends my sensibilities.");
service.insert(new URL(complaintUrl), complaintEntry);
Each YouTube video can have favorite videos. The feed corresponding to these favorite videos is conceptually just an unnamed playlist. The favorites feed for a user can be retrieved from the following URL:
http://gdata.youtube.com/feeds/api/users/userID/favorites
The below code prints out a list of a user's favorites:
String feedUrl = "http://gdata.youtube.com/feeds/api/users/YTDebates/favorites";
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
for(VideoEntry entry : videoFeed.getEntries() ) {
System.out.println("Title: " + entry.getTitle().getPlainText());
System.out.println(entry.getMediaGroup().getDescription().getPlainTextContent());
}
Remember that the string default can be used in place of a username to mean "the currently authenticated user".
To add a favorite, simply insert the VideoEntry of the video you would like to add to the authenticated user's favorites feed.
String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/ADos_xW4_J0"; VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl), VideoEntry.class); service.insert(new URL(feedUrl), videoEntry);
To delete a favorite, simply use the delete method on a VideoEntry from the favorites feed of the authenticated user.
entry.delete();
Each YouTube user has an associated playlists feed which is a list of links to a feed containing the videos in each playlist.
To retrieve a feed of a particular user's playlists, you use the following URL:
http://gdata.youtube.com/feeds/api/users/userID/playlists
The following code demonstrates how to retrieve and print a playlists feed using that URL:
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.getDescription());
}
Remember that the string default can be used in place of a username to mean "the currently authenticated user".
Given a PlaylistLinkEntry, as retrieved in the previous example, you can fetch and print
the playlist contents using the following code:
String playlistUrl = entry.getFeedLink().getHref();
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.getDescription());
System.out.println("Position: " + playlistEntry.getPosition());
System.out.println("Video URL: " + playlistEntry.getHtmlLink().getHref());
}
Keep in mind that PlaylistEntry inherits from VideoEntry. For more information on what can be retrieved from a VideoEntry object, read the section Video entry contents.
You can create a new playlist by inserting 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.setDescription("this is my new playlist.");
PlaylistLinkEntry createdEntry = service.insert(new URL(feedUrl), newEntry);
To update playlist data such as title or description, simply modify the PlaylistLinkEntry object and call its update method. The below code updates a playlist's description.
entry.setDescription("updated description");
entry.update();
You can add a video to a playlist by using a VideoEntry object. The below code retrieves a VideoEntry with a known entry ID and then adds it to the playlist corresponding to the PlaylistLinkEntry. Since a position is not specified, the new video is added to the end of the playlist.
String playlistUrl = playlistLinkEntry.getFeedLink().getHref();
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);
playlistEntry.setTitle(new PlainTextConstruct("Custom title"));
playlistEntry.setDescription("Custom description");
service.insert(new URL(playlistUrl), playlistEntry);
Note that the above code specifies a custom title and description for the video. This is not required, and if these are not specified, then the video's actual title and description will be used.
You can modify the custom titles and descriptions of each video in a playlist by updating the PlaylistEntry object for the video and calling its update method.
playlistEntry.setDescription("updated description");
//move this entry to the top of the playlist
playlistEntry.setPosition(0);
playlistEntry.update();
If you would like to change a video's description and title on a playlist back to the video's original title and description you can do it with the following code:
playlistEntry.setDescription(null); playlistEntry.setTitle(null); playlistEntry.update();
To remove a video from a playlist, use the delete method of the PlaylistEntry:
playlistEntry.delete();
To delete a playlist, simply call the delete method of the corresponding PlaylistLinkEntry object.
entry.delete();
To fetch a list of the channels, searches, and favorites that a given user is subscribed to, use the following URL:
http://gdata.youtube.com/feeds/api/users/userID/subscriptions
The following code demonstrates how to retrieve and print the list of subscriptions for a given user, using that URL:
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.getFeedLink().getHref());
}
Remember that the string default can be used in place of a username to mean "the currently authenticated user".
You can create a new subscription by inserting a new SubscriptionEntry into the authenticated user's subscriptions feed. 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);
You can also subscribe to the favorites of the "GoogleDevelopers" user:
SubscriptionEntry newSubscription = new SubscriptionEntry();
newSubscription.addSubscriptionType(SubscriptionEntry.Type.FAVORITES);
newSubscription.setUsername("GoogleDevelopers");
service.insert(new URL(feedUrl), newSubscription);
Lastly, you can also subscribe to specific search terms:
SubscriptionEntry newSubscription = new SubscriptionEntry();
newSubscription.addSubscriptionType(SubscriptionEntry.Type.QUERY);
newSubscription.setQueryString("puppy");
service.insert(new URL(feedUrl), newSubscription);
To remove a subscription, call the delete method on the corresponding SubscriptionEntry object.
entry.delete();
A YouTube user's profile can be retrieved as an Atom entry from the following URL:
http://gdata.youtube.com/feeds/api/users/userID
The following code prints out various attributes from a 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("Describe: " + 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());
}
Remember that the string default can be used in place of a username to mean "the currently authenticated user".
To retrieve a list of a user's contacts, you can use the following URL:
http://gdata.youtube.com/feeds/api/users/userID/contacts
The following code prints out all the friends for 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());
}
You can add a contact by inserting a new FriendEntry into the authenticated user's contacts feed. A category is used to control which contact group the contact falls under, if any. The below code adds the "GoogleDevelopers" user as a contact.
FriendEntry newFriend = new FriendEntry();
newFriend.getCategories().add(new Category(YouTubeNamespace.CONTACT_LIST_SCHEME, "Friends"));
newFriend.setUsername("GoogleDevelopers");
service.insert(new URL(feedUrl), newFriend);
You can accept or reject a contact by updating the status of the corresponding FriendEntry.
To accept a request:
friendEntry.setStatus(YtStatus.Value.ACCEPTED); friendEntry.update();
To reject a request:
friendEntry.setStatus(YtStatus.Value.REJECTED); friendEntry.update();
To delete a contact, call the delete method on a FriendEntry.
friendEntry.delete();
Messages can be sent between YouTube users, optionally including a video.
To retrieve the contents of a user's inbox, make an authenticated request to the following URL:
http://gdata.youtube.com/feeds/api/users/userID/inbox
The below example prints out 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.getDescription());
}
To send a message to a user, construct a VideoMessageEntry and insert it into their inbox feed. All messages sent through the API require a VideoEntry object to be included.
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.setDescription("This is the message body.");
service.insert(new URL(msgUrl), newMessage);
The recipient of the message must be an accepted contact of the sender of the message.
To delete a message, call the delete method on a VideoMessageEntry object:
entry.delete();