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 feeds to fetch, search and update videos, comments, responses, playlists, user profiles and user contacts as well as query for videos that match particular criteria.
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 Python Client Library. To use the Python client library, you'll need Python 2.0+ and the Element Tree, httplib, and urllib modules. See Dependency Modules for further details.
If you need help setting up the Python client library, the Getting Started Guide is the place to look. If you're interested in understanding more about the underlying protocol used by the Python client library to interact with YouTube, see the Developer's Guide protocol page.
- About this document
- Getting started
- Understanding video feeds and entries
- Retrieving and searching for videos
- Uploading videos
- Updating and deleting videos
- Using community features
- Saving and collecting videos
- Favorite videos
- Enabling user interaction
About this document
This document is intended for programmers who want to write client applications that can interact with YouTube using the Python 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 how to program in Python.
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 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 meta-data about a specific video entry. Finally, this section explains the mechanism for updating an individual video entry.
The Retrieving and searching for videos section explains how to fetch specific lists of videos, such as a standard feed of YouTube's most popular videos. Other lists of videos include videos uploaded by a specific user and lists of videos related to a particular video. This section also explains how to use the API to let users search through YouTube's video library by 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. Additionally, this section also explains how to upload videos as responses to other videos.
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 shows 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.
RequirementsYour client application can use the YouTube Data API feeds to search for, retrieve and update videos, comments, responses, playlists, subscriptions, user profiles and more.
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 Python Client Library. To use the Python client library, you'll need Python 2.2+ and the Element Tree, httplib, and urllib modules. See Dependency Modules for further details.
See the Getting Started Guide for more information on configuring your environment. If you're interested in understanding more about the underlying protocol used by the Python client library to interact with YouTube, see the Developer's Guide protocol page.
The snippets of sample code below can be copied/pasted into your code and modified to fit your needs.
Before you can perform any operations with the YouTube Data API, you must initialize a
object, as shown below. The
import statements listed below will automatically perform further imports from the
gdata.media and the
gdata.geo modules. Please note that all actions aside from retrieving public content will require authentication.
import gdata.youtube import gdata.youtube.service yt_service = gdata.youtube.service.YouTubeService() # Turn on HTTPS/SSL access. # Note: SSL is not available at this time for uploads. yt_service.ssl = True
Most of the method examples in this guide operate upon an instance of
gdata.youtube.service.YouTubeService. It may be beneficial to test the unauthenticated requests from the interactive python interpreter.
Note: the Python client library must be properly added in your path. Please make sure you install it by running the provided
setup.py script. Refer to the Getting Started Guide for more information.
The Python client library can be used to work with either public or private feeds. Public feeds are read-only and do not require any authentication. Private feeds require that you authenticate to the YouTube servers.
Setting your developer key and client ID
A developer key identifies the YouTube developer that is submitting an API request. A client ID identifies your application for logging and debugging purposes.
When you make an API request using the Python client library, the
X-GData-Key request header is used to specify your developer key and the
X-GData-Client header is used to specify your client ID. The developer key and client ID can be set on the
YouTubeService object, independently of the authentication scheme that is being used:
yt_service.developer_key = 'ABCxyz123...' yt_service.client_id = 'My-Client_id'
You will need to sign up for a YouTube developer key.
AuthSub authentication for web applications
AuthSub proxy authentication is used by web applications which need to authenticate their users to YouTube/Google accounts. The operator does not need access to the username and password for the YouTube user — only special AuthSub tokens are required.
When the user first visits your application, they have not yet been authenticated with Google's services. In this case, you need to provide them with a link directing the user to Google to authorize your applications' request for access to their YouTube account. The Python client library provides a function to generate this URL. The code below sets up a link to the AuthSubRequest page.
def GetAuthSubUrl(): next = 'http://www.example.com/video_upload.pyc' scope = 'http://gdata.youtube.com' secure = False session = True yt_service = gdata.youtube.service.YouTubeService() return yt_service.GenerateAuthSubURL(next, scope, secure, session) authSubUrl = GetAuthSubUrl() print '<a href="%s">Login to your Google account</a>' % authSubUrl
Notice the parameters sent to the service objects'
- next — the URL of the page that YouTube should redirect the user to after they have authorized your application to access their account.
- scope — indicating that the application will only access YouTube API feeds.
- secure — indicating that the token returned will not be a secure token.
- session — indicating this token can be exchanged for a multi-use (session) token.
The returned URL will look something like this:
The user can then follow the link to log-in to their YouTube account. After the user authorizes your application to access their account, they will then be redirected back to the
next URL. The URL will have a single-use token value appended to it as a query parameter. The URL looks something like this:
The next section will demonstrate how to upgrade this token. The snippet below demonstrates one of the ways to retrieve this token from the URL:
import cgi parameters = cgi.FieldStorage() authsub_token = parameters['token' ]
Upgrading to a session token
For security, this token is single-use only, so now you need to exchange this single-use token for a session token. This process is described in the AuthSub documentation. The following code snippet shows how to upgrade the token.
yt_service = gdata.youtube.service.YouTubeService() yt_service.SetAuthSubToken(authsub_token) yt_service.UpgradeToSessionToken()
This token value represents a single-use AuthSub token. Since
session = True was specified above, this token can be exchanged for an AuthSub session token using the
UpgradeToSessionToken method, which calls the
YouTubeService object is now fully authenticated and can be used to perform all further requests with the YouTube API. AuthSub session tokens will not expire unless you specifically issue a request to revoke them, or the user decides to revoke access by visiting the Authorized Sites page in their YouTube account.
ClientLogin authentication for installed applications
ClientLogin authentication is used in installed applications that can either store or query your user for their username and password. To use this form of authentication, invoke the
ProgrammaticLogin method of
YouTubeService inherited from the
gdata.service.GDataService class, specifying the ID and password of the user on whose behalf your client is sending the request to authenticate.
yt_service = gdata.youtube.service.YouTubeService() yt_service.email = 'firstname.lastname@example.org' yt_service.password = 'mypassword' yt_service.source = 'my-example-application' yt_service.ProgrammaticLogin()
Once the credentials have been set, the
YouTubeService object can be used to handle all further requests. To be able to perform uploads and any kind of 'write' requests (adding comments, etc) to the YouTube API, ensure that you also pass your developer key and client ID to the
yt_service object when you perform authentication:
# A complete client login request yt_service.email = 'email@example.com' yt_service.password = 'mypassword' yt_service.source = 'my-example-application' yt_service.developer_key = 'ABC123...' yt_service.client_id = 'my-example-application' yt_service.ProgrammaticLogin()
YouTubeService object automatically sets the correct
X-GData-Client headers when the
client_id attributes are set.
Note: Please refer to the Google Data APIs authentication documentation for more detailed information on both 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 favorites. 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 most simply be modeled as
gdata.youtube.YouTubeVideoFeed objects, each containing a number of
gdata.youtube.YouTubeVideoEntry 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:
def GetAndPrintVideoFeed(uri): yt_service = gdata.youtube.service.YouTubeService() feed = yt_service.GetYouTubeVideoFeed(uri) for entry in feed.entry: PrintEntryDetails(entry) # full documentation for this function
The Retrieving and searching for videos section details many common feed URLs and how to retrieve various video feeds.
Retrieving a specific video entry
You can retrieve just the information for a specific video entry if you know its video ID. The entry URL is based on the video ID:
The following code retrieves a
gdata.youtube.YouTubeVideoEntry corresponding to a video on YouTube:
entry = yt_service.GetYouTubeVideoEntry(video_id='the0KZLEacs')
Video entry contents
There are many pieces of meta-data that can be retrieved from a
gdata.youtube.YouTubeVideoEntry object, such as thumbnails, player URLs, and video duration. The following code demonstrates how to get at some of this information. The Python client library abstracts most of this functionality by mapping XML elements into classes. Most of the important information about a
YouTubeVideoEntry entry is available from the children of the
media attribute (containing a
gdata.media.Group object) within the entry (representing the XML
media:group element). Below is an example of how to retrieve video meta-data:
def PrintEntryDetails(entry): print 'Video title: %s' % entry.media.title.text print 'Video published on: %s ' % entry.published.text print 'Video description: %s' % entry.media.description.text print 'Video category: %s' % entry.media.category[0].text print 'Video tags: %s' % entry.media.keywords.text print 'Video watch page: %s' % entry.media.player.url print 'Video flash player URL: %s' % entry.GetSwfUrl() print 'Video duration: %s' % entry.media.duration.seconds # non entry.media attributes print 'Video geo location: %s' % entry.geo.location() print 'Video view count: %s' % entry.statistics.view_count print 'Video rating: %s' % entry.rating.average # show alternate formats for alternate_format in entry.media.content: if 'isDefault' not in alternate_format.extension_attributes: print 'Alternate format: %s | url: %s ' % (alternate_format.type, alternate_format.url) # show thumbnails for thumbnail in entry.media.thumbnail: print 'Thumbnail url: %s' % thumbnail.url
Note: For more information on how to generate the required information for embedding a video with a player in your page please refer to the protocol guide.
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:
Note: 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 popular videos in Japan would be:
http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_popular. For a complete list of supposed localeIDs, please refer to the reference guide.
def PrintVideoFeed(feed): for entry in feed.entry: PrintEntryDetails(entry) def GetAndPrintFeedByUrl: yt_service = gdata.youtube.service.YouTubeService() # You can retrieve a YouTubeVideoFeed by passing in the URI uri = 'http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_popular' PrintVideoFeed(yt_service.GetYouTubeVideoFeed(uri))
Retrieving videos uploaded by a specific user
Each YouTube user has an associated video feed corresponding to the
videos he or she has uploaded, at
The following code demonstrates how to fetch and display a user uploads feed:
def GetAndPrintUserUploads(username): yt_service = gdata.youtube.service.YouTubeService() uri = 'http://gdata.youtube.com/feeds/api/users/%s/uploads' % username PrintVideoFeed(yt_service.GetYouTubeVideoFeed(uri))
Note: You may also use the string 'default' in place of
username to retrieve videos for the currently authenticated user.
Retrieving related videos
To retrieve related videos, pass the video id of the
gdata.youtube.YouTubeVideoEntry object to the
GetYouTubeRelatedVideoFeed method. This retrieves a
YouTubeVideoFeed object containing related entries.
related_feed = yt_service.GetYouTubeRelatedVideoFeed(video_id='abc123')
Searching for videos
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, by video format or containing a particular keyword. To do this, you
gdata.service.YouTubeVideoQuery object with your particular search criteria and pass it to the
The example below shows how to perform a search query, with results ordered by view count, including restricted videos (referred to as 'Racy' by the API):
def SearchAndPrint(search_terms): yt_service = gdata.youtube.service.YouTubeService() query = gdata.youtube.service.YouTubeVideoQuery() query.vq = search_terms query.orderby = 'viewCount' query.racy = 'include' feed = yt_service.YouTubeQuery(query) PrintVideoFeed(feed)
gdata.service.Query class and subclasses like
YouTubeVideoQuery, are responsible for constructing feed URLs. The
VideoQuery shown above constructs a URL equivalent to the following:
- Sets the author of the entry. Author is synonymous with YouTube username.
- Specifies a video format. Accepts numeric parameters to specify one of two kinds of RTSP streaming URLs for mobile video playback or a HTTP URL to the embeddable Flash player.
- Indicates whether restricted content should be included in the results. Accepts only two parameters: 'include' or 'exclude'.
- Sets the maximum number of entries to return at one time.
- Sets the 1-based index of the first result to be retrieved (for paging).
- Sets the order in which to list entries, such as by
- Sets a time period to limit standard feed results to:
- Sets a search query term. Searches for the specified string in all video metadata, such as titles, tags, and descriptions.
Searching with categories and keywords
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 pre-defined YouTube categories (such as Music, People & Blogs, etc.) and user-defined keywords (tags).
The following code demonstrates how to search using keywords (tags) by changing the search terms to lowercase. Note: Since some words (such as "comedy") can be both a YouTube category and a keyword, category and keyword queries use the convention that a capitalized word ("Comedy") denotes a YouTube category, while a lowercase word ("comedy") denotes a keyword.
def SearchAndPrintVideosByKeywords(list_of_search_terms): yt_service = gdata.youtube.service.YouTubeService() query = gdata.youtube.service.YouTubeVideoQuery() query.orderby = 'viewCount' query.racy = 'include' for search_term in list_of_search_terms: new_term = search_term.lower() query.categories.append('/%s' % new_term) feed = yt_service.YouTubeQuery(query) PrintVideoFeed(feed)
Searching by developer Tags
Developer tags are additional, hidden keywords that a developer may use to tag content uploaded through their application by end users. Developer tags are matched to the developer key set in the headers during the upload. These keywords will not be visible to the public and may be used to retrieve videos. To search for videos by a specific developer tag, send a general YouTube Data API search request using your developer key. Be sure to specify the category scheme and the developer tag that videos must match. You can retrieve a feed of videos matching to your developer tag ('your_tag_here' in our example) from the URL below:
developer_tag_uri = 'http://gdata.youtube.com/feeds/videos/-/%7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007%2Fdevelopertags.cat%7Dyour_tag_here' yt_service = gdata.youtube.service.YouTubeService() PrintVideoFeed(yt_service.GetYouTubeVideoFeed(developer_tag_uri))
Please make sure to review the diagrams in the protocol guide for a high-level overview of the upload process. Uploading videos can be done in one of two ways:
- either by uploading the video directly from your servers through the Direct Upload method
- or by sending the meta-data first, and then having the user upload the video directly to YouTube through the Browser-based Upload method
In order to upload a video, you must first construct a new
gdata.youtube.YouTubeVideoEntry object, passing it a
gdata.media.Group object containing required meta-data. The following example shows uploading the Quicktime video "mytestmovie.mov" to YouTube with the following properties:
|Title||My Test Movie|
|File MIME type||video/quicktime|
|Video location||37,-122 (lat,long)|
|Developer Tags||mydevelopertag, anotherdevelopertag|
gdata.youtube.VideoEntryobject containing meta-data
filename_or_handle— A file-like object or the filename from which the video will be read from
youtube_username— An optional string specifying the username into which account this video is to be uploaded. Your account will need the appropriate permissions of course. This defaults to the currently authenticated user's account.
content_type— An optional string specifying the MIME-type of the video to be uploaded.
yt_servicevariable refers to a fully authenticated
# prepare a media group object to hold our video's meta-data my_media_group = gdata.media.Group( title=gdata.media.Title(text='My Test Movie'), description=gdata.media.Description(description_type='plain', text='My description'), keywords=gdata.media.Keywords(text='cars, funny'), category=[gdata.media.Category( text='Autos', scheme='http://gdata.youtube.com/schemas/2007/categories.cat', label='Autos')], player=None ) # prepare a geo.where object to hold the geographical location # of where the video was recorded where = gdata.geo.Where() where.set_location((37.0,-122.0)) # create the gdata.youtube.YouTubeVideoEntry to be uploaded video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group, geo=where) # set the path for the video file binary video_file_location = '/path/to/my/file.mov' new_entry = yt_service.InsertVideoEntry(video_entry, video_file_location)
If we wanted to tag our video with optional developer tags (see Searching by Developer Tags for more details), we could have used the
AddDeveloperTags method prior to perfoming the call to
developer_tags = ['some_tag_01', 'another_tag'] video_entry.AddDeveloperTags(developer_tags)
Note: To upload videos as private, a private attribute must be passed to the
my_media_group = gdata.media.Group( title=gdata.media.Title(text='My Test Movie'), description=gdata.media.Description(description_type='plain', text='My description'), keywords=gdata.media.Keywords(text='cars, funny'), category=[gdata.media.Category( text='Autos', scheme='http://gdata.youtube.com/schemas/2007/categories.cat', label='Autos')], player=None, private=gdata.media.Private() ) video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group) # assuming that video_file_location points to a valid path new_entry = yt_service.InsertVideoEntry(video_entry, video_file_location)
Browser-based uploading is performed almost identically to direct uploading, except that you do not upload your file binary in the same request that you use to send in the video meta-data. Instead, you simply create a
YouTubeVideoEntry that contains meta-data only. This video entry then gets posted to a special link on the YouTube API server. The XML response contains a
token and a
url which can then be used to upload the binary file using a standard HTML form.
# create media group as usual my_media_group = gdata.media.Group( title=gdata.media.Title(text='My Test Movie'), description=gdata.media.Description(description_type='plain', text='My description'), keywords=gdata.media.Keywords(text='cars, funny'), category=[gdata.media.Category( text='Autos', scheme='http://gdata.youtube.com/schemas/2007/categories.cat', label='Autos')], player=None ) # create video entry as usual video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group) # upload meta data only response = yt_service.GetFormUploadToken(video_entry) # parse response tuple and use the variables to build a form (see next code snippet) post_url = response[0] youtube_token = response[1]
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
youtube_token representing the content of the returned token element, as shown being retrieved from
YouTubeVideoEntry above. In order for the user to be redirected to your website after submitting the form, make sure to append a
next parameter to the
post_url (as shown below), which will function in the same way as the
next parameter of an AuthSub link. The only difference is that here, instead of a single-use token, a
status and an
id variable are returned as URL parameters.
next = 'http://example.com/post_video_upload.pyc' form = """<form action="%s?nexturl=%s" method="post" enctype="multipart/form-data"> <input name="file" type="file"/> <input name="token" type="hidden" value="%s"/> <input value="Upload Video File" type="submit" /> </form>""" % (post_url, next, youtube_token)
A response for a successful upload would then look like this:
status parameter returns the HTTP transaction status of the upload transaction. The
id parameter returns the YouTube video id that was assigned to the uploaded video.
Checking upload status
After uploading a video, it will immediately be visible in an authenticated user's uploads feed. 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
YouTubeVideoEntry to see if it is not live yet or if it has been rejected.
upload_status = yt_service.CheckUploadStatus(new_entry) if upload_status is not None: video_upload_state = upload_status[0] detailed_message = upload_status[1]
Updating and deleting videos
Updating video information
To update video meta-data, simply update the
YouTubeVideoEntry object and then use the
UpdateVideoEntry method. This method takes as a parameter a
YouTubeVideoEntry that contains updated meta-data.
# assuming we have a video entry that was just posted in our 'new_entry' variable new_entry.media.title.text = 'My Updated Video Title' new_entry.media.description.text = 'Just updated' updated_entry = yt_service.UpdateVideoEntry(new_entry)
Deleting a video
response = yt_service.DeleteVideoEntry(entry_to_be_deleted) if response: print 'Video successfully deleted!'
Using community features
Adding a rating
video_id_to_rate = 'Ncakifd_16k' video_entry = yt_service.GetYouTubeVideoEntry(video_id=video_id_to_rate) response = yt_service.AddRating(3, video_entry)
Retrieving comments for a video
YouTubeVideoEntry object or a simple video Id, you can retrieve and print a feed containing the comments for the video using the
GetYouTubeVideoCommentFeed method of the
YouTubeService object. The resulting feed is a
gdata.youtube.YouTubeCommentFeed, consisting of
gdata.youtube.YouTubeCommentEntry objects. The feed can be parsed like any other feed:
video_id = 'ABC123...' comment_feed = yt_service.GetYouTubeVideoCommentFeed(video_id=video_id) for comment_entry in comment_feed.entry: print comment_entry.ToString()
Adding a comment
To add a new comment, simpy use the
AddComment method of the
YouTubeService object. The method requires a full
YouTubeVideoEntry object which is to be commented on, as well as a string that represents the comment:
my_comment = 'what a boring test video' video_id = '9g6buYJTt_g' video_entry = yt_service.GetYouTubeVideoEntry(video_id=video_id) yt_service.AddComment(comment_text=my_comment, video_entry=video_entry)
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
Adding a complaint about a video is done with the
AddComplaint method on the
YouTubeService object. The complaint term must be a valid category. Please refer to the Adding a complaint section in the protocol guide for more information.
video_id_to_flag = 'Ncakifd_16k' complaint_term = 'VIOLENCE' complaint_text = ('Please ignore this complaint. ' 'I\'m testing a YouTube API and needed to issue ' 'a complaint to test the add complaint function. ') response = yt_service.AddComplaint(complaint_text, complaint_term, video_id_to_flag)
Saving and collecting videos
Retrieving a user's favorite videos
YouTube users can choose to mark videos they watch as favorites. The general location for a user's favorite feed is the following URL.
To retrieve a user's favorite videos, use the
GetUserFavoritesFeed method of the
YouTubeService object. The method takes an optional string as a parameter representing the YouTube username of the user whose favorite feed is to be retrieved.
favorite_feed = yt_service.GetUserFavoritesFeed(username='gdpython')
The returned feed is a regular video feed, containing
Note: Alternatively, you may pass in the string
default to retrieve favorites for the currently authenticated user. This is the default behavor of the
GetUserFavoritesFeed method if no username is provided.
Adding a favorite
To add a favorite video use the
AddVideoEntryToFavorites method. The parameters are the
YouTubeVideoEntry which is to be added and optionally the username to whose favorites it is to be added (the default is the currently authenticated user).
video_id = 'Ncakifd_16k' video_entry = yt_service.GetYouTubeVideoEntry(video_id=video_id) response = yt_service.AddVideoEntryToFavorites(video_entry) # The response, if succesfully posted is a YouTubeVideoEntry if isinstance(response, gdata.youtube.YouTubeVideoEntry): print 'Video successfully added to favorites'
Deleting a favorite
video_id = 'Ncakifd_16k' response = yt_service.DeleteVideoEntryFromFavorites(video_id) if response is True: print 'Video deleted from favorites'
Each YouTube user has a playlist feed which contains all of the playlists that the user has created. Each playlist then has a feed for all the videos that are on it.
Retrieving user playlists
To fetch a list of all of a user's playlists by hand, you would use the following URL:
playlist_feed = yt_service.GetYouTubePlaylistFeed(username='gdpython') # instead of passing in a username, you can also pass the URI to the playlist feed: playlist_feed = yt_service.GetYouTubePlaylistFeed(uri='http://gdata.youtube.com/feeds/api/users/default/playlists')
Note: Instead of passing a specific username (such as 'gdpython' in the example above), you can also pass in the string
'default' to refer to the currently authenticated user.
gdata.youtube.YouTubePlaylistFeed represents a feed of
gdata.youtube.YouTubePlaylistEntry objects. These refer to the individual playlists that a user may have. Video entries on a particular playlist are represented as
gdata.youtube.YouTubePlaylistVideoEntry objects. These objects are very similar to regular
gdata.youtube.YouTubeVideoEntry objects with a few exceptions. Custom titles and descriptions can be applied to the videos, and a position field indicates where the video appears in the playlist.
Retrieving playlist information
YouTubePlaylistEntry (representing a specific playlist), you can obtain a
YouTubePlaylistVideoFeed that contains
YouTubePlaylistVideoEntry objects. As explained above, these objects represent individual videos on a playlist (with optional custom titles and description). You can obtain this feed by passing the URI of your playlist to the
GetYouTubePlaylistVideoFeed method of the
# a typical playlist URI playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505' playlist_video_feed = yt_service.GetYouTubePlaylistVideoFeed(uri=playlist_uri) # iterate through the feed as you would with any other for playlist_video_entry in playlist_video_feed.entry: print playlist_video_entry.title.text
Adding a playlist
To add a new playlist, simply use the
AddPlaylist method of the
YouTubeService object. This method takes the following parameters: playlist_title, playlist_description (both strings) and an optional boolean that can be set to
True if the playlist is to be marked as private.
new_public_playlistentry = yt_service.AddPlaylist('my new playlist', 'a new playlist') if isinstance(new_public_playlistentry, gdata.youtube.YouTubePlaylistEntry): print 'New playlist added' # adding a private playlist new_private_playlistentry = yt_service.AddPlaylist('new private playlist', 'a new private playlist', True) if isinstance(new_private_playlistentry, gdata.youtube.YouTubePlaylistEntry): print 'New private playlist added'
Updating a playlist
To update a playlist, use the
UpdatePlaylist method of the
YouTubeService object. The method takes the following parameters: the id of the playlist to be updated, a new title, a new description, an optional boolean to mark the playlist private and an optional string indicating the username that owns the playlist. The string will default to the currently authenticated user.
# here we are updating a public playlist with a new title while also making it private # we assume that playlist_to_be_updated here represents a YouTubePlaylistEntry object playlist_entry_id = playlist_to_be_updated.id.text.split('/')[-1] # we want to keep the original description for the playlist so we store it first original_description = playlist_to_be_updated.description.text updated_playlist = yt_service.UpdatePlaylist(playlist_entry_id, 'a new updated title', original_playlist_description, playlist_private=True)
Add video to playlist
custom_video_title = 'my test video on my test playlist' custom_video_description = 'this is a test video on my test playlist' video_id = 'Ncakifd_16k' playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505' playlist_video_entry = yt_service.AddPlaylistVideoEntryToPlaylist( playlist_uri, video_id, custom_video_title, custom_video_description) if isinstance(playlist_video_entry, gdata.youtube.YouTubePlaylistVideoEntry): print 'Video added'
Note: Please note that a custom title and description are not required, and if these are not specified, then the video's actual title and description will be used.
Edit video info on playlist
UpdatePlaylistVideoEntryMetaData method of the
YouTubeService object to change the meta-data for a
YouTubePlaylistVideoEntry. In the example below we decide to give our video a new custom title and move it to the first position (position 1) on our playlist.
playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505' playlist_entry_id = 'B0F29389E537F888' new_video_title = 'a useful video' new_video_description = 'updated video description' updated_playlist_video_entry = yt_service.UpdatePlaylistVideoEntryMetaData( playlist_uri, playlist_entry_id, new_video_title, new_video_description, 1)
Note: If you would like to revert a video's description and title on a playlist back to the original meta-data, just pass in
NULL for both title and description.
Remove video from playlist
To remove a video from a playlist, use the
DeletePlaylistVideoEntry method of the
YouTubeService object. The method requires the URI of the playlist that contains the entry to be deleted as well as the id of the entry:
playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505' playlist_entry_id = 'B0F29389E537F888' response = yt_service.DeletePlaylistVideoEntry(playlist_uri, playlist_entry_id) if response is True: print 'Entry successfully deleted'
Deleting a playlist
playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505' response = yt_service.DeletePlaylist(playlist_uri) if response is True: print 'Playlist successfully deleted'
To fetch a list of the channels, searches, and favorites that a given user is subscribed to, use the following URI:
Note: Alternatively, you may pass in the string
default to retrieve favorites for the currently authenticated user.
Retrieving user subscriptions
The following code demonstrates how to retrieve and print the list of subscriptions for a given user. Subscriptions are represented as a
gdata.youtube.YouTubeSubscriptionFeed consisting of
gdata.youtube.YouTubeSubscriptionEntry objects. To retrieve subscriptions, use the
GetYouTubeSubscriptionFeed method of the
YouTubeService object, passing in either the URI of a subscription feed or the username whose subscription feed is to be retrieved. The username parameter defaults to the currently authenticated user.
subscription_feed = yt_service.GetYouTubeSubscriptionFeed(username='gdpython') if isinstance(subscription_feed, gdata.youtube.YouTubeSubscriptionFeed)): # given a YouTubeSubscriptionEntry we can determine it's type (channel, favorite, or query) for entry in subscription_feed.entry: print entry.GetSubscriptionType()
Adding a subscription
You can create a new subscription by inserting a new
YouTubeSubsciptionEntry into the authenticated user's subscriptions feed. We can create three types of subscriptions: A subscription to a user's channel (using
AddSubscriptionToChannel), a subscription to a user's favorites (using
AddSubscriptionToFavorites or a subscription to a specific keyword (using
AddSubscriptionToQuery). The following code subscribes the authenticated user to the "GoogleDevelopers" channel.
new_subscription = yt_service.AddSubscriptionToChannel( username_to_subscribe_to='GoogleDevelopers') if isinstance(new_subscription, gdata.youtube.YouTubeSubscriptionEntry): print 'New subscription added'
You can also subscribe to the favorites of the "GoogleDevelopers" user:
new_subscription = yt_service.AddSubscriptionToFavorites( username='GoogleDevelopers') if isinstance(new_subscription, gdata.youtube.YouTubeSubscriptionEntry): print 'New subscription added'
Lastly, you can also subscribe to specific search terms. Here we are subscribing to a query for videos tagged "python".
new_subscription = yt_service.AddSubscriptionToQuery(query='python') if isinstance(new_subscription, gdata.youtube.YouTubeSubscriptionEntry): print 'New subscription added'
Deleting a subscription
sample_subscription_uri = ('http://gdata.youtube.com/feeds/api/users/' 'gdpython/subscriptions/c0c77ca6102a7479') response = yt_service.DeleteSubscription(sample_subscription_uri) if response is True: print 'Subscription successfully deleted'
Enabling user interaction
Retrieving a user's profile
To fetch a user's YouTube profile by hand, you would use the following URI:
user_entry = yt_service.GetYouTubeUserEntry(username='gdpython') # we can then write a helper function to print out the user details def PrintUserEntry(entry): # print required fields where we know there will be information print 'URI: %s\n' % entry.id.text print 'Age: %s\n' % entry.age.text print 'Gender: %s\n' % entry.gender.text print 'Location: %s\n' % entry.location.text # check if there is information in the other fields and if so print it if user.first_name: print 'First Name: %s\n' % user.first_name.text if user.last_name: print 'Last Name: %s\n' % user.last_name.text if user.relationship: print 'Relationship: %s\n' % user.relationship.text if user.description: print 'About me: %s\n' % user.description.text for link in user.link: if link.rel == 'related': print 'Website: %s\n' % link.href if user.company: print 'Company: %s\n' % user.company.text if user.occupation: print 'Occupation: %s\n' % user.occupation.text if user.school: print 'School: %s\n' % user.school.text if user.hobbies: print 'Hobbies: %s\n' % user.hobbies.text if user.movies: print 'Movies: %s\n' % user.movies.text if user.music: print 'Music: %s\n' % user.music.text if user.books: print 'Books: %s\n' % user.books.text if user.hometown: print 'Hometown: %s\n' % user.hometown.text
The list of contacts for a given user can be retrieved from the following URL:
Retrieving user contacts
contact_feed = yt_service.GetYouTubeContactFeed(username='GoogleDevelopers') for entry in contact_feed.entry: print entry.title.text # find the apprpriate category element to find out the contact type for category in entry.category: if category.scheme == 'http://gdata.youtube.com/schemas/2007/contact.cat': print category.term
Adding a contact
new_contact = yt_service.AddContact(contact_username='GoogleDevelopers') if isinstance(new_contact, gdata.youtube.YouTubeContactEntry) print 'New contact added'
Accepting/rejecting a contact
To update a contact, use the
UpdateContact method of the
YouTubeService object. This method can be used to accept/reject contact requests and also to categorize contacts as either 'Friend' or 'Family'. In the example below we accept a contact, and then set its category to 'Family':
# in this case user 'gdpython' has requested to be our contact #so the original contact status is 'pending' updated_contact = yt_service.UpdateContact('gdpython', 'accepted', 'Family') if isinstance(updated_contact, gdata.youtube.YouTubeContactEntry) print 'New contact added'
Deleting a contact
response = yt_service.DeleteContact(contact_username='gdpython') if response is True: print 'Contact deleted'
Questions? Feedback? Notice a typo in this doc? Let us know in the discussion forum. Happy coding!