The YouTube Data API allows applications to perform functions normally executed on the YouTube website. The API enables your application to search for YouTube videos and to retrieve standard video feeds, comments and video responses. In addition, the API lets your application upload videos to YouTube or update existing videos. Your application can also retrieve playlists, subscriptions, user profiles and more. Finally, your application can submit authorized requests to enable users to create playlists, subscriptions, contacts and other account-specific entities.
Contents
Audience
This documentation is intended for programmers who are writing client applications that interact with YouTube. It provides examples of basic API operations using raw HTTP and XML. Java, .NET, PHP and Python developers may prefer to read the language-specific developer guides that explain how to use the client libraries for those languages to perform similar functions.
This documentation assumes that you understand the general principles behind the Google Data APIs protocol. Google Data APIs provide a simple, standard protocol for reading and writing data on the web. Google Data APIs are based on the Atom 1.0 and RSS 2.0 syndication formats as well as the Atom Publishing Protocol.
About this documentation
This documentation contains the following sections:
-
The Authentication and authorization section describes the different ways you can associate an API operation with a specific user account. Throughout this documentation, explanations of specific API functions will clearly indicate whether the function requires user authorization.
-
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 illustrates how the XML elements in a YouTube Data API response correspond to the video information typically displayed on YouTube's website. This section also explains the API request format for updating an individual 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 also explains how also to retrieve a list of videos uploaded by a specific user or a list of related videos, which are videos that YouTube has determined are similar to a particular video. 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 presents process flow diagrams for each upload method and explains how those methods work in conjunction with the authorization scheme that you are using.
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. However, 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 to an existing video.
-
The Updating and deleting videos section explains how to enable a user to update or delete his videos.
-
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.
Supported API feeds
The lists below identify the different types of feeds and feed entries that you can retrieve (GET) using the YouTube Data API. The API also supports methods to add (POST), update (PUT), or delete (DELETE) entries from many of these feeds.
-
Video feeds contain a list of videos.
- Video search feeds list videos that match parameter values, such as a query term or video duration.
- Standard video feeds list videos that either reflect YouTube user behavior or that were selected by YouTube staff. Examples include top-rated, most viewed, and recently featured videos. Movie charts are standard feeds that only contain videos that appear in YouTube's Movies category.
- A user uploads feed identifies videos uploaded by a specified user.
- A favorite videos identifies videos that a specified user has flagged as a favorite.
- A playlist feed lists the videos in a specified playlist.
- A watch later feed lists videos that a specified user has flagged to watch at a later time.
- A watch history feed lists videos that the user has watched on the YouTube website.
- A video recommendations feed contains videos that may appeal to a specified user.
- A related videos feed identifies videos related to a specified video.
- A video responses feed identifies videos that have been explicitly designated as responses to a specified video.
- A new subscription videos feed identifies videos that were recently uploaded by users that a specified user subscribes to.
-
Channel feeds contain a list of channels.
- Channel search feeds list channels that match a specified search term.
- Standard channel feeds list channels that reflect YouTube user preferences, such as most viewed and most subscribed channels.
-
Playlists feeds contain a list of playlists. Note that a playlists feed is different than a playlist feed, which is a type of video feed.
- Playlist search feeds list playlists that match a specified search term.
- A user playlists feed identifies playlists created by a specified user.
-
Event feeds contain a list of events.
- Live event charts contain standard feeds of events, such as featured events, upcoming events, or currently live events.
- A user events feed lists a specific user's live events.
-
Comment feeds list comments that users have submitted about a specified video.
-
Subscription and activity feeds
- A user subscription feed lists channels or users that a specified user has subscribed to.
- User activity feeds list different actions performed by one or more specified users. Actions include rating a video, marking a video as a favorite, uploading a video, and more.
-
Inbox and contact feeds
- A user inbox feed lists messages in the logged-in user's inbox.
- A user contacts feed lists a specified user's contacts.
-
A user profile entry contains information about a specified user. Any personal information that appears in a user profile feed will have been entered by that user for publication on YouTube.
In addition, the API supports methods for adding ratings and complaints, though neither of those can be retrieved via the API.
Handling usernames and display names in your application
The API uses several different elements to identify users. With that in mind, the following rules explain how to properly handle usernames and display names in your application:
-
For any API request that requires you to specify a YouTube username, you can use the term
defaultto identify the currently logged-in user as long as you also send an authentication token with the request. For example, the URLhttps://gdata.youtube.com/feeds/api/users/default?v=2will retrieve the currently authenticated user's profile. -
If you need to manually generate a feed URL that is not for the currently authenticated user, we recommend that you use the value of the
<yt:userId>tag as the username in the feed URL. For backward compatibility purposes, you can also use the<yt:username>tag's value as the username in the feed URL. However, going forward, you should use the<yt:userId>value to uniquely identify a user.The
<yt:userId>tag always contains a globally unique identifier that is not intended for display. The<yt:username>tag, on the other hand, could contain either the same globally unique identifier or a traditional YouTube username, which also serves as a channel name. Both elements are included in user profile entries, subscription feed entries, and numerous other feeds. -
If your code displays a username, use the value of the
<yt:username>tag'sdisplayattribute as the display value. That value will always be a meaningful value that is suitable for display.- For a YouTube account that is connected to a Google+ profile, the
displayattribute value will be set to the user's full public display name. - For accounts that are not connected to Google+, the
displayvalue will be set to the YouTube account name.
The
<name>tag, which appears inside the<author>tag, also contains the correct value to display for a user in a user interface. Like the<yt:username>tag value, the<name>tag value is not intended to uniquely identify the user. - For a YouTube account that is connected to a Google+ profile, the
-
In cases where the
<media:credit>tag identifies the YouTube user that uploaded a video, that tag will also have ayt:displayattribute that specifies the appropriate name to display for that user, while the tag's value will uniquely identify the user.When the
<media:credit>tag communicates other information, such as the name of an actor or director associated with a video, the tag will specify a value for display.
API versioning
An API request can specify the version of the API that YouTube should use to handle the request. Your request can specify an API version using either the v parameter or the GData-Version HTTP request header.
YouTube actively supports API versions 2 and 2.1, and you must use either the v parameter or the GData-Version request header to specify one of these two versions. The list below briefly explains the two API versions:
-
API version
2allows access to all currently supported API features to users who have YouTube accounts. A YouTube account provisions a YouTube channel name, enabling the user to upload videos. Users with YouTube accounts can access many other YouTube features that require user authorization, such as the ability to create playlists, create subscriptions, rate videos, add comments, and more. -
API version
2.1enables users who have a Google Account but who do not have a YouTube channel to also access many features that are dependent on user authorization. While a user still needs a YouTube channel to upload videos, she does not need a YouTube channel to rate videos, add videos to a 'Watch Later' playlist, or access several other site features.On YouTube.com, and in API version
2.1, the latter group of features is available to users who have a Google Account (but not a YouTube channel). In this documentation, such accounts are referred to as unlinked Google Accounts. For example, a user who has a Gmail account or an Android device is certain to have a Google Account but may not have already linked that Google Account to a YouTube channel.By specifying API version
2.1in your application, you are indicating that your application has been upgraded to properly handle requests from users with unlinked Google Accounts. The Comparing API versions 2 and 2.1 section provides a detailed list of the features that are supported in API version2.1for users with unlinked Google Accounts. It also explains how API responses in version2.1are different from the same responses in version2for users with unlinked Google Accounts.
Note: Unless otherwise noted, all of the sample requests in this documentation use the GData-Version request header and demonstrate how to use version 2 of the API. Using the most current version of the API may allow your application to access API features that are not available in older versions of the API. For example, captions, partial responses, and partial updates are all supported in version 2 of the API but are not supported in the now-deprecated version 1.
If a request does not specify an API version, then YouTube will use API version 1 to handle that request. (Note, however, that requests to the API staging server use API version 2 by default.)
Please note the following characteristics of API version numbers:
-
YouTube may release updates to a specific API version for which the release is not assigned a new version number. These backward-compatible updates can include optional API features, bug fixes or both.
-
An increment of the API version number identifies a release that contains changes that are incompatible with previous API versions.
For more information, see the Backward Compatibility Guidelines, which identify API behaviors that may change even if you do not modify the API version that should be used to handle your API requests. The guidelines also define API behaviors that YouTube does not intend to change for a particular API version.
Comparing API versions 2 and 2.1
As discussed in the previous section, YouTube supports API versions 2 and 2.1. The following list shows the differences between the two versions.
-
The versions return different HTTP response codes and error messages for requests that require authorization and are made on behalf of users with unlinked Google Accounts.
-
API version
2returns an HTTP401response code and the messageNoLinkedYouTubeAccountif a user with an unlinked Google Account attempts any operation that requires authorization. -
API version
2.1returns an HTTP200response code for a subset of the requests that cause a401 NoLinkedYouTubeAccountresponse in API version2.This version also returns an HTTP
403 Forbiddenresponse with ayoutube_signup_requirederror for the remaining unsupported requests. The following XML shows a sample response with this error:<?xml version='1.0' encoding='UTF-8'?> <errors> <error> <domain>yt:service</domain> <code>youtube_signup_required</code> </error> </errors>
If you want to modify your application to support users with unlinked Google Accounts, we recommend that you focus on gracefully handling this error. Since the list of features supported for unlinked Google Accounts is likely to grow, hardcoding your application to only display certain features to users with those accounts would likely prevent users from accessing supported features until you could update your application.
If an API response specifies the
youtube_signup_requirederror, your application should indicate that the requested operation requires the user to have a YouTube channel and should display an option to link to https://www.youtube.com/create_channel. If you are building a mobile application, you can bypass a redirect by presenting a link to https://m.youtube.com/create_channel instead.
-
-
API version
2.1lets users with unlinked Google Accounts access some, but not all, API features that require user authorization. In API version2, those features are only available to users with YouTube accounts.Specifically, API version
2.1supports the features listed below for users with authorized Google Accounts and should return an HTTP200response code for API requests related to these features:- Rating a video
- Flagging a video for inappropriate content (adding a complaint)
- Subscribing to a channel or user activity feed
- Adding videos to a "watch_later" playlist
As such, users with unlinked Google Accounts must add a YouTube channel to be able to use the following API features. (The API will return a
403 Forbiddenresponse, as described above, for requests related to these features.)- Uploading videos (or video responses)
- Adding comments
- Identifying favorite videos
- Creating playlists (other than the
watch_laterplaylist) - Retrieving personalized video recommendations
- Adding or retrieving contacts
- Sending messages to other YouTube users
- Retrieving their own activity feed
-
In version
2.1, a YouTube user profile entry for a user with an unlinked Google Account will contain a<yt:incomplete>tag. This tag is useful if you prefer to modify your application so that it does not display unsupported features (or provides a different display for those features) to users with unlinked Google Accounts.In addition, in version
2.1, a profile entry for a user with an unlinked Google Account only contains a few of the tags that can be included in a profile entry for a user with a YouTube account. The<entry>tag definition lists the tags that may appear within a profile entry for both YouTube accounts and unlinked Google Accounts.
Authentication and authorization
Authentication and authorization protocols allow a user to access YouTube features that link content or information to a particular YouTube account.
-
Authentication pertains to the idea of user identity. So, for example, a user authenticates when entering an account username and password.
-
Authorization refers to the ability to retrieve, insert, update, and delete data. An authenticated user can authorize a third-party application to perform API operations on that user's behalf.
The API supports numerous functions that require user authorization, including all of the API functions for creating, updating or deleting content. For example, suppose an application allows users to capture videos and upload them to YouTube. To upload a video through the application, a user would need to authenticate by logging into a Google Account and then authorize the application to upload videos to the user's account.
Note: If you implement any functionality that requires user authorization, we recommend that you include the proper authorization headers in all of your API requests even if those requests do not explicitly require user authorization.
A request must include the following information to be properly authorized:
-
An
Authorizationheader that specifies a token that you obtain for each user. -
The
X-GData-Keyheader or the key parameter, which specifies your developer key, a value that uniquely identifies your application(s). Using theX-GData-Keyheader is the preferred approach since it is more secure than the URL parameter.
We recommend that you use OAuth 2.0 authorization for your application, and the sample API requests throughout this documentation use the OAuth 2.0 syntax for their Authorization HTTP header values. The OAuth 2.0 protocol provides a standard way to access protected data on different websites and it is the recommended authorization mechanism for Google APIs. OAuth is an open protocol that may be implemented for many APIs, including Google APIs. All Google APIs, including the YouTube API, support the OAuth 2.0 authorization protocol. OAuth 2.0 relies on SSL for security instead of requiring your application to do cryptographic signing directly.
The OAuth 1.0, AuthSub, and ClientLogin authorization schemes also still work with the YouTube API. The APIs for those schemes have all been officially deprecated as of April 20, 2012. They will continue to work as per our deprecation policy, but we encourage you to migrate to OAuth 2.0 authorization as soon as possible. Similarly, if you are building a new application, you should use OAuth 2.0 authorization.
Using a developer key
A developer key uniquely identifies a product that is submitting an API request. Please visit http://code.google.com/apis/youtube/dashboard/ to obtain a developer key.
YouTube provides two ways to specify your developer key in an API request. The first option provides greater security and is the recommended approach.
-
When you make an API request, use the
X-GData-Keyrequest header to specify your developer key as shown in the following example:X-GData-Key: key=<developer_key> -
Include the key query parameter in the request URL.
https://gdata.youtube.com/feeds/api/videos?q=SEARCH_TERM&key=DEVELOPER_KEY
Note: Specifying your developer key is very simple if you are using one of our client libraries. In the client libraries, you provide your developer key when initializing the YouTube service object, and all subsequent requests sent using that object will contain the key.
OAuth 2.0
The YouTube Data API supports the OAuth 2.0 protocol for authorizing access to private user data. The list below explains some core OAuth 2.0 concepts:
-
When a user first attempts to use functionality in your application that requires the user to be logged in to a Google Account or YouTube account, your application initiates the OAuth2 authorization process.
-
Your application directs the user to Google's authorization server. The link to that page specifies the scope of access that your application is requesting for the user's account. The scope specifies the resources that your application can retrieve, insert, update, or delete when acting as the authenticated user.
-
If the user consents to authorize your application to access those resources, Google will return a token to your application. Depending on your application's type, it will either validate the token or exchange it for a different type of token.
For example, a server-side web application would exchange the returned token for an access token and a refresh token. The access token would let the application authorize requests on the user's behalf, and the refresh token would let the application retrieve a new access token when the original access token expires.
This section of the API documentation covers the following topics:
-
The Register your application with Google section walks you through the registration process, which is a prerequisite to using OAuth 2.0 authorization.
-
The OAuth 2.0 flows section explains different flows for obtaining OAuth 2.0 access tokens for either server-side web applications, client-side web applications, installed applications, or devices.
-
The Calling the YouTube Data API section explains how to use the OAuth 2.0 tokens that your application obtains to make authorized API requests on a user's behalf.
-
The Client libraries section describes client library support for OAuth 2.0.
Register your application with Google
You need to register your application with Google to be able to use OAuth 2.0 authorization. The following steps explain how to register your application and create an OAuth 2.0 client ID to use in that application.
Create your project and select API services
-
Create a project in the Google APIs Console.
-
If you have not created a project before, the Console page displays a big
Create projectbutton.
-
If you have created a project before, you can create a new project via the Console menu shown below.

-
-
The console displays the Services pane, which shows a list of the Google API services that your application could use. Toggle the status for the YouTube Data API v3 service to
ON. (You may need to read and accept a license agreement to complete this step for certain services.)
OAuth 2.0 flows
Google supports several OAuth 2.0 use cases:
- The server-side flow supports web applications that can securely store persistent information.
- The client-side flow supports JavaScript applications running in a browser.
- The installed application flow supports applications installed on a device, such as a phone or computer.
- The device flow supports devices with limited input capabilities, such as game consoles and video cameras.
Server-side web applications
This flow is designed for web applications with servers that can store information and maintain state. While this section walks through the steps your code would go through to use OAuth 2.0 in a server-side web application, you could also use one of several client libraries in your OAuth 2.0 implementation.
The following steps explain the server-side flow:
-
Obtain an access token
Note: Requests to Google's authorization server must use
httpsinstead ofhttpbecause the server is only accessible over SSL (HTTPs) and will refuse HTTP connections.When a user first tries to perform an action that requires API authentication, direct the user to Google's authorization server at
https://accounts.google.com/o/oauth2/auth. It supports the following URL parameters:Parameter Description client_idRequired. The OAuth 2.0 client ID for your application. redirect_uriRequired. A registered redirect_urifor that client ID.response_typeRequired. Set this parameter's value to code.scopeRequired. A space-delimited list of scopes that identify the resources that your application could access on the user's behalf. approval_promptOptional. This parameter indicates whether the user should be prompted to grant account access to your application each time she tries to complete a particular action. The default value is auto, which indicates that a user would only need to grant access the first time she tried to access a protected resource.
Set the parameter value toforceto direct the user to a consent page even if she has already granted access to your application for a particular set of scopes.access_typeRecommended. This parameter indicates whether your application can refresh access tokens when the user is not present at the browser. Valid parameter values are onlineandoffline. Set this parameter value toofflineto allow the application to refresh access tokens when the user is not present. (This is the method of refreshing access tokens described later in this document.)stateOptional. Any string that your application would use to maintain state between the request and redirect response. Your application will receive the same value that it sends for this parameter. For example, you could use this parameter to redirect the user to a particular resource in your application. The sample URL below shows a redirect to Google's authorization server for an application requesting permission to submit YouTube Data API requests on the user's behalf:
https://accounts.google.com/o/oauth2/auth? client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com& redirect_uri=http://localhost/oauth2callback& scope=https://gdata.youtube.com& response_type=code& access_type=offline
-
User decides whether to grant access to your application
Google's authorization server will display the name of your application and the Google services that it is requesting permission to access on the user's behalf. The user can then consent or refuse to grant access to your application.
You can test this flow by clicking on the sample URL in step 1. If you also place a file on your server at
http://localhost/oauth2callback, you will also be able to see how the user's response appears in the redirect URI. (See step 3 for more details.) -
Google redirects user to your application
After the user consents or refuses to grant access to your application, Google will redirect the user to the
redirect_urithat you specified in step 1.-
If the user granted access to your application, Google will have appended a
codeparameter to theredirect_uri. This value is a temporary authorization code that you can exchange for an access token as discussed in step 4.http://localhost/oauth2callback?code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf
-
If the user refused to grant access to your application, Google will have included the
access_deniederror message in the hash fragment of theredirect_uri:http://localhost/oauth2callback#error=access_denied
-
-
Exchange authorization code for refresh and access tokens
Assuming the user has granted access to your application, exchange the authorization code obtained in step 3 for a refresh token and access token. To do so, send a
POSTrequest tohttps://accounts.google.com/o/oauth2/tokenthat includes the following key-value pairs in the request body:Key Value codeThe authorization code that Google returned to your redirect_uriin step 3.client_idThe OAuth 2.0 client ID for your application. client_secretThe client secret associated with your client ID. This value is displayed in the Google APIs console. redirect_uriA registered redirect_urifor your client ID.grant_typeSet this value to authorization_code.A sample request is displayed below:
POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-Type: application/x-www-form-urlencoded code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf& client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com& client_secret=hDBmMRhz7eJRsM9Z2q1oFBSe& redirect_uri=http://localhost/oauth2callback& grant_type=authorization_code
-
Process response and store tokens
Google will respond to your
POSTrequest by returning a JSON object that contains a short-lived access token and a refresh token.{ "access_token" : "ya29.AHES6ZTtm7SuokEB-RGtbBty9IIlNiP9-eNMMQKtXdMP3sfjL1Fc", "token_type" : "Bearer", "expires_in" : 3600, "refresh_token" : "1/HKSmLFXzqP0leUihZp2xUt3-5wkU7Gmu2Os_eBnzw74" }Important: Your application should store both values.
-
The Calling the YouTube Data API section explains how to submit an authorized request using the access token.
-
The Refreshing an access token section explains how to use the refresh token to obtain a new access token if the one that you have expires.
-
Client-side web applications
This flow is designed for JavaScript-based web applications that cannot maintain state over time.
The following steps explain the client-side flow:
-
Obtain an access token
Note: Requests to Google's authorization server must use
httpsinstead ofhttpbecause the server is only accessible over SSL (HTTPs) and will refuse HTTP connections.When a user first tries to perform an action that requires API authentication, direct the user to Google's authorization server at
https://accounts.google.com/o/oauth2/auth. It supports the following URL parameters:Parameter Description client_idRequired. The OAuth 2.0 client ID for your application. redirect_uriRequired. A registered redirect_urifor that client ID.response_typeRequired. Set this parameter's value to token.scopeRequired. A space-delimited list of scopes that identify the resources that your application could access on the user's behalf. approval_promptOptional. This parameter indicates whether the user should be prompted to grant account access to your application each time she tries to complete a particular action. The default value is auto, which indicates that a user would only need to grant access the first time she tried to access a protected resource.
Set the parameter value toforceto direct the user to a consent page even if she has already granted access to your application for a particular set of scopes.stateOptional. A string used to maintain state between the request and redirect. This value will be appended to your redirect_uriafter the user consents to or denies your application's access request.The sample URL below shows a redirect to Google's authorization server for an application requesting permission to submit YouTube Data API requests on the user's behalf:
https://accounts.google.com/o/oauth2/auth? client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com& redirect_uri=http://localhost/oauth2callback& scope=https://gdata.youtube.com& response_type=token
-
User decides whether to grant access to your application
Google's authorization server will display the name of your application and the Google services that it is requesting permission to access on the user's behalf. The user can then consent or refuse to grant access to your application.
You can test this flow by clicking on the sample URL in step 1. If you also place a file on your server at
http://localhost/oauth2callback, you will also be able to see how the user's response appears in the redirect URI. (See step 3 for more details.) -
Google redirects user to your application
After the user consents or refuses to grant access to your application, Google will redirect the user to the
redirect_urithat you specified in step 1.-
If the user granted access to your application, Google will have appended a short-lived access token in the hash fragment of the redirect URI. The response will also include the
expires_inandtoken_typeparameters. These parameters describe the lifetime of the token in seconds and the kind of token that is being returned, respectively. Finally, the response will include thestateparameter if astateparameter was included in the original request to the authorization server.http://localhost/oauth2callback#access_token=1/QbIbRMWW&token_type=Bearer&expires_in=3600
Note: Your application should also allow other fields to be returned in the response. The list provided above identifies the minimum set of fields that will be appended to the
redirect_uri.JavaScript code running on your page can capture the access token from the
window.location.hashvalue and either store the token in a cookie orPOSTit to a server. -
If the user refused to grant access to your application, Google will have included the
access_deniederror message in the hash fragment of theredirect_uri:http://localhost/oauth2callback#error=access_denied
-
-
Validate the user's token
Assuming the user has granted access to your application, you need to explicitly validate the token returned in the
redirect_uri. You validate the token by specifying the token as the value of theaccess_tokenparameter in a web service request tohttps://www.googleapis.com/oauth2/v1/tokeninfo. That URL accepts an access token and returns information about that token, including the application that the token was issued to, the user associated with the token, the scopes that the user granted access to, and the remaining life of the token.The sample URL below demonstrates where you would send a token validation request:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=1/fFBGRNJru1FQd44AzqT3Zg
-
Process the token validation response
In response to a token validation request, the Google authorization server will return either a JSON object that describes the token or an error message.
-
If the token is still valid, the JSON object will include the following values:
Field Description audienceThe application that is the intended user of the access token.
Important: Before using the token, you need to verify that this field's value exactly matches yourclient_idin the Google APIs console. This verification ensures that your application will not be vulnerable to the confused deputy problem.expires_inThe number of seconds left before the token will become invalid. scopeA space-delimited list of scopes that the user granted access to. The list should match the scopes you specified in your authorization request in step 1. useridThis value lets you correlate profile information from multiple Google APIs. It is only present in the response if you included the https://www.googleapis.com/auth/userinfo.profilescope in your request in step 1. The field value is an immutable identifier for the logged-in user that can be used to create and manage user sessions in your application.A sample response is shown below:
{ "audience":"8819981768.apps.googleusercontent.com", "user_id":"123456789", "scope":"https://gdata.youtube.com", "expires_in":436 } -
If the token has expired, been tampered with, or had its permissions revoked, Google's authorization server will return an error message in the JSON object. The error surfaces as a 400 error, and a JSON body in the format shown below:
{"error":"invalid_token"}By design, no additional information is given as to the reason for the failure.
-
Installed applications
This flow is designed for applications that are installed on a device, such as a mobile phone or computer. These applications could access the YouTube Data API while the user is interacting with the application or when the application is running in the background for an extended period of time without direct user interaction.
This flow assumes that the application cannot securely store tokens that would enable a user to interact with YouTube Data API. It also requires that the application has access to the system browser or has the ability to embed a browser control. If the application does not meet either of these conditions, refer to the OAuth 2.0 instructions for devices by clicking the Devices tab above.
The following steps explain this flow:
-
Register your application as an installed application
When registering your application, make sure that you specify that it is an installed application. This results in a different default value for the
redirect_uriparameter. -
Obtain an access token
Note: Requests to Google's authorization server must use
httpsinstead ofhttpbecause the server is only accessible over SSL (HTTPs) and will refuse HTTP connections.When a user first tries to perform an action that requires API authentication, direct the user to Google's authorization server at
https://accounts.google.com/o/oauth2/auth. It supports the following URL parameters:Parameter Description client_idRequired. The OAuth 2.0 client ID for your application. redirect_uriRequired. A registered
redirect_urifor that client ID. For installed applications, you can choose between anhttp://localhost:portorurn:ietf:wg:oauth:2.0:oobas described below:http://localhost:port- This value indicates that Google's authorization server should return the authorization code as a query string parameter to the client device's web server. You may specify a port number without changing the configuration in the Google APIs console.
To receive the authorization code on this URL, your application must be listening on the local web server. If your platform supports it, this is the recommended mechanism for obtaining the authorization code. However, note that not all platforms support this approach and that even if a platform does support it, other software (e.g. Windows firewall) may prevent delivery of the message. urn:ietf:wg:oauth:2.0:oob- This value indicates that Google's authorization server should return the authorization code in the browser's title bar. This option is useful if the client cannot listen on an HTTP port without significant modifications to the client. Windows applications possess this characteristic.
If your application uses this value, it needs to determine when the browser has loaded a response from the authorization server. It will then need to extract the authorization code from the title of the page served in the browser. See step 4 for specific instructions for parsing the token from the page title.
Your application should also close the browser window if you want to prevent the user from seeing the page with the authorization code. The mechanism for closing that window varies from platform to platform.
response_typeRequired. Set this parameter's value to code.scopeRequired. A space-delimited list of scopes that identify the resources that your application could access on the user's behalf. stateOptional. Any string that your application would use to maintain state between the request and redirect response. Your application will receive the same value that it sends for this parameter. For example, you could use this parameter to redirect the user to a particular resource in your application. The sample URL below shows a redirect to Google's authorization server for an application requesting permission to submit YouTube Data API requests on the user's behalf:
https://accounts.google.com/o/oauth2/auth? client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com& redirect_uri=http://localhost/oauth2callback& scope=https://gdata.youtube.com& response_type=code& access_type=offline
-
User decides whether to grant access to your application
Google's authorization server will display the name of your application and the Google services that it is requesting permission to access on the user's behalf. The user can then consent or refuse to grant access to your application.
You can test this flow by clicking on the sample URL in step 2. If you also place a file on your server at
http://localhost/oauth2callback, you will also be able to see how the user's response appears in the redirect URI. (See step 4 for more details.) -
Google redirects user to your application
After the user consents or refuses to grant access to your application, Google will either redirect the user to the
redirect_urithat you specified in step 2 or return a page to the user's browser.-
If you set the
redirect_uritohttp://localhost(or some path on the local web server), then one of the following two scenarios will apply:-
If the user granted access to your application, Google will have appended a
codeparameter to theredirect_uri. This value is a temporary authorization code that you can exchange for an access token as discussed in step 5.http://localhost/oauth2callback?code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf
-
If the user refused to grant access to your application, Google will have included the
access_deniederror message in the hash fragment of theredirect_uri:http://localhost/oauth2callback#error=access_denied
-
-
If you set the
redirect_uritourn:ietf:wg:oauth:2.0:oob, Google's authorization server will return a page to the browser like the one shown below. Your application can then extract the authorization code from the page title.To extract the token, your application should assume that everything that follows the last space character in the page title is a parameter string in the format
x=a&y=b. Your code should parse the parameters from that substring, looking for acode=orerror=assignment to indicate that the page contains the final title string and the sign-in flow is complete. If the page title assigns a value to thecodeparameter, then that value is the token. However, your application should not make assumptions about the token length or the number of parameters in the parameter string.For example, the screenshot below shows a page with the following attributes:
- Page title:
Success code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu - Parameter string:
code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu - Authorization token:
4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu

- Page title:
-
-
Exchange authorization code for refresh and access tokens
Assuming the user has granted access to your application, exchange the authorization code obtained in step 4 for a refresh token and access token. To do so, send a
POSTrequest tohttps://accounts.google.com/o/oauth2/tokenthat includes the following key-value pairs in the request body:Key Value codeThe authorization code that Google returned to your redirect_uriin step 4.client_idThe OAuth 2.0 client ID for your application. client_secretThe client secret associated with your client ID. This value is displayed in the Google APIs console. redirect_uriA registered redirect_urifor your client ID.grant_typeSet this value to authorization_code.A sample request is displayed below:
POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-Type: application/x-www-form-urlencoded code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf& client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com& client_secret=hDBmMRhz7eJRsM9Z2q1oFBSe& redirect_uri=http://localhost/oauth2callback& grant_type=authorization_code
-
Process response and store tokens
Google will respond to your
POSTrequest by returning a JSON object that contains a short-lived access token and a refresh token.{ "access_token" : "ya29.AHES6ZTtm7SuokEB-RGtbBty9IIlNiP9-eNMMQKtXdMP3sfjL1Fc", "token_type" : "Bearer", "expires_in" : 3600, "refresh_token" : "1/HKSmLFXzqP0leUihZp2xUt3-5wkU7Gmu2Os_eBnzw74" }Important:Your application should store both values.
-
The Calling the YouTube Data API section explains how to submit an authorized request using the access token.
-
The Refreshing an access token section explains how to use the refresh token to obtain a new access token if the one that you have expires.
-
Devices
This flow is designed for applications that run on devices with limited input capabilities, such as game consoles or video cameras. In this flow, the user interacts with an application on the device to obtain a URL and a device code. The user then switches to another device, such as a computer or smartphone, that has richer input capabilities to authorize the device code.
The following steps explain this flow:
-
Embed your
client_idandclient_secretin your applicationYou need to register your application with Google and embed the
client_idandclient_secretcreated during the registration process into your application. -
Request a device code
Your device sends a
POSTrequest to Google's authorization server athttps://accounts.google.com/o/oauth2/device/code. The request specifies the following parameters:Parameter Description client_idRequired. The OAuth 2.0 client ID for your application. scopeRequired. A space-delimited list of scopes that identify the resources that your application could access on the user's behalf. The following sample request shows how to retrieve a device code:
POST /o/oauth2/device/code HTTP/1.1 Host: accounts.google.com Content-Type: application/x-www-form-urlencoded client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com& scope=https://gdata.youtube.com
-
Handle the response
Google will respond to your request by returning a JSON object to your device. A sample response is shown below:
{ "device_code" : "4/L9fTtLrhY96442SEuf1Rl3KLFg3y", "user_code" : "a9xfwk9c", "verification_url" : "http://www.google.com/device", "expires_in" : "1800" "interval" : 5, }The application on your device should display the
user_codeandverification_urlto the user. It should store thedevice_code,expires_in, andintervalvalues for use in step 4. -
Begin polling Google's authorization server
Your application can begin polling Google's authorization server using the
device_codereturned in the JSON response in step 3. To do so, your application sends aPOSTrequest tohttps://accounts.google.com/o/oauth2/tokenthat specifies the following key-value pairs:Key Value client_idThe OAuth 2.0 client ID for your application. client_secretThe client secret associated with your client ID. This value is displayed in the Google APIs console. codeThe device code obtained in step 3. grant_typeSet this value to http://oauth.net/grant_type/device/1.0.A sample polling request is shown below. The
intervalreturned in the JSON response in step 3 specifies the minimum amount of time, in seconds, that your application should wait between polling requests.POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-Type: application/x-www-form-urlencoded client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com& client_secret=hDBmMRhz7eJRsM9Z2q1oFBSem& code=4/YMSlR3fSCC1NtUh073DuZKTJJ3ss& grant_type=http://oauth.net/grant_type/device/1.0
Until the user completes steps 5 through 7, your application will receive one of the following responses to each polling request:
-
The following response indicates that the user has not yet completed the steps to grant API access to the device:
{ "error" : "authorization_pending" } -
The following response indicates that your application is sending polling requests too frequently:
{ "error" : "slow_down" }
-
-
User enters
user_codein separate browserThe user launches a browser on another device, such as a computer or mobile phone, and navigates to the
verification_url. That URL will display a page where the user can enter theuser_codeobtained in step 3.
Note: The
user_codeis case-sensitive, so the user will need to enter it exactly as it appears in the response. -
User logs in to Google Account that will be used on your device
After entering the
user_code, the user will be asked to log in to the Google Account that will be used to authenticate YouTube Data API requests from your device. (If the user is already logged in, she will proceed directly to the next step.) -
User decides whether to grant access to your application
After the user logs in, Google's authorization server will display a page that shows the name of your application and the Google services that it is requesting permission to access on the user's behalf. The user can then consent or refuse to grant access to your application.
-
Process response from polling server to obtain tokens
If the user grants access to your application, the next polling request that your device sends will return a JSON object that contains an access token and a refresh token.
{ "access_token":"1/fFAGRNJru1FTz70BzhT3Zg", "expires_in":3920, "token_type":"Bearer", "refresh_token":"1/6BMfW9j53gdGImsixUH6kU5RsR4zwI9lUVX-tqf8JXQ" }Important: Your application should store both values.
-
The Calling the YouTube Data API section explains how to submit an authorized request using the access token.
-
The Refreshing an access token section explains how to use the refresh token to obtain a new access token if the one that you have expires.
-
Calling the YouTube Data API
After obtaining an access token for a user, your application can use that token to submit authorized API requests on that user's behalf. The API supports two ways to specify an access token. The first option provides greater security and is the recommended approach.
-
Specify the access token as the value of the
Authorization: BearerHTTP request header:POST /feeds/api/users/default/uploads HTTP/1.1 Host: gdata.youtube.com Authorization: Bearer ACCESS_TOKEN ...
You can test this using cURL with the following command:
curl -H "Authorization: Bearer ACCESS_TOKEN" gdata.youtube.com/feeds/api/users/default/uploads
-
Specify the access token as the value of the
access_tokenquery parameter:https://gdata.youtube.com/feeds/api/users/default/uploads?access_token=ACCESS_TOKEN
You can test this using cURL with the following command:
curl gdata.youtube.com/feeds/api/users/default/uploads?access_token=YOUR_ACCESS_TOKEN
The API will return an HTTP 401 response code (Unauthorized) if you submit a request to access a protected resource with an expired access token. The following section explains how to refresh an access token.
Refreshing an access token
If your application obtains a refresh token during the authorization process, then you will need to periodically use that token to obtain a new, valid access token. Server-side web applications, installed applications, and devices all obtain refresh tokens.
At any time, your application can send a POST request to Google's authorization server that specifies your client ID, your client secret, and the refresh token for the user. The request should also set the grant_type parameter value to refresh_token. The following example demonstrates this request:
POST /o/oauth2/token HTTP/1.1 Host: accounts.google.com Content-Type: application/x-www-form-urlencoded client_id=21302922996.apps.googleusercontent.com& client_secret=XTHhXh1SlUNgvyWGwDk1EjXB& refresh_token=1/6BMfW9j53gdGImsixUH6kU5RsR4zwI9lUVX-tqf8JXQ& grant_type=refresh_token
The authorization server will return a JSON object that contains a new access token:
{
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in":3920,
"token_type":"Bearer"
}
Client libraries
The Google Data client libraries that support the YouTube Data API do not currently support OAuth 2.0. However, a newer set of Google API client libraries, which do not support the YouTube Data API, do provide OAuth 2.0 support.
As such, it is an option to use these newer libraries, which are listed below, for their OAuth 2.0 capabilities and then force the Google Data client library to use the OAuth 2.0 token(s) that you have obtained.
- Google APIs Client Library for Java
- Google APIs Client Library for Python
- Google APIs Client Library for .NET
- Google APIs Client Library for Ruby
- Google APIs Client Library for PHP
- OAuth 2.0 Library for Google Web Toolkit
- Google Toolbox for Mac OAuth 2.0 Controllers
You can also follow the instructions in the Calling the YouTube Data API section to modify your code to properly set the OAuth 2.0 token values.
Authorizing requests from Flash applications
As shown in the examples throughout this documentation, different API operations are executed using either GET, POST, PUT, PATCH, or DELETE requests. However, Flash applications must send a POST request in order to set an Authorization header.
To send an authorized GET, PUT, PATCH, or DELETE request from a Flash application, set the X-HTTP-Method-Override header in that request. If your application is sending a GET request, it should set the body of the request to the query parameters associated with that request as shown in the following example:
POST /feeds/api/videos HTTP/1.1 X-HTTP-Method-Override: GET Host: gdata.youtube.com Content-Type: application/atom+xml Content-Length: CONTENT_LENGTH Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY vq=jesse+ventura&category=News
If your application is submitting a POST or PUT request, it should set the body of the request to an XML document. The XML formats for different types of requests are defined later in this document.
Understanding video feeds and entries
When you retrieve a video feed or list of search results, YouTube returns an Atom feed that contains one <entry> tag for each video in the result set. The root XML tag in the response will be the <feed> tag. In addition to the information about the individual videos in the result set, the feed will also contain the total number of results in the list, the index of the first item in the list, the number of items in the list and other metadata about the feed.
The following XML shows the format of a YouTube Data API response containing a video feed:
<?xml version='1.0' encoding='UTF-8'?> <feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gml='http://www.opengis.net/gml' xmlns:georss='http://www.georss.org/georss' xmlns:media='http://search.yahoo.com/mrss/' xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/"CE4EQH47eCp7ImA9WxRQGEQ."'> <id>tag:youtube,2008:standardfeed:us:top_rated</id> <updated>2008-07-18T05:00:49.000-07:00</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/> <title>Top Rated</title> <logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo> <link rel='alternate' type='text/html' href='https://www.youtube.com/browse?s=tr'/> <link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/standardfeeds/top_rated?v=2'/> <link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/standardfeeds/top_rated/batch?v=2'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/standardfeeds/top_rated?...'/> <link rel='service' type='application/atomsvc+xml' href='https://gdata.youtube.com/feeds/api/standardfeeds/top_rated?...'/> <link rel='next' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/standardfeeds/top_rated?...'/> <author> <name>YouTube</name> <uri>http://www.youtube.com/</uri> </author> <generator version='2.0' uri='http://gdata.youtube.com/'>YouTube data API</generator> <openSearch:totalResults>100</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>25</openSearch:itemsPerPage> <entry gd:etag='W/"C0AMRn47eCp7ImA9WxRQGUw."'> <id>tag:youtube,2008:video:ZTUVgYoeN_b</id> <published>2008-07-05T19:56:35.000-07:00</published> <updated>2008-07-18T07:21:59.000-07:00</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/> <category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='Shopping'/> <category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='parkas'/> <category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='People' label='People'/> <title>Shopping for Coats</title> <content type='application/x-shockwave-flash' src='http://www.youtube.com/v/ZTUVgYoeN_b?f=gdata_standard...'/> <link rel='alternate' type='text/html' href='https://www.youtube.com/watch?v=ZTUVgYoeN_b'/> <link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/ZTUVgYoeN_b/responses?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#video.ratings' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/ZTUVgYoeN_b/ratings?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#video.complaints' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/ZTUVgYoeN_b/complaints?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/ZTUVgYoeN_b/related?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#mobile' type='text/html' href='https://m.youtube.com/details?v=ZTUVgYoeN_b'/> <link rel='http://gdata.youtube.com/schemas/2007#uploader' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/users/_x5XG1OV2P6uZZ5FSM9Ttw?v=2'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/standardfeeds/top_rated/v/ZTUVgYoeN_b?v=2'/> <author> <name>GoogleDevelopers</name> <uri>https://gdata.youtube.com/feeds/api/users/GoogleDevelopers</uri> <yt:userId>_x5XG1OV2P6uZZ5FSM9Ttw<</yt:userId> </author> <yt:accessControl action='comment' permission='allowed'/> <yt:accessControl action='commentVote' permission='allowed'/> <yt:accessControl action='videoRespond' permission='moderated'/> <yt:accessControl action='rate' permission='allowed'/> <yt:accessControl action='embed' permission='allowed'/> <yt:accessControl action='list' permission='allowed'/> <yt:accessControl action='autoPlay' permission='allowed'/> <yt:accessControl action='syndicate' permission='allowed'/> <gd:comments> <gd:feedLink href='https://gdata.youtube.com/feeds/api/videos/ZTUVgYoeN_b/comments' countHint='9416'/> </gd:comments> <georss:where> <gml:Point> <gml:pos>21.37124437061831 -157.87353515625</gml:pos> </gml:Point> </georss:where> <yt:hd/> <media:group> <media:category label='People' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>People </media:category> <media:content url='http://www.youtube.com/v/ZTUVgYoeN_b?f=gdata_standard...' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='215' yt:format='5'/> <media:content url='rtsp://rtsp2.youtube.com/ChoLENy73bIAEQ1kgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='215' yt:format='1'/> <media:content url='rtsp://rtsp2.youtube.com/ChoLENy73bIDRQ1kgGDA==/0/0/0/video.3gp' type='video/3gpp' medium='video' expression='full' duration='215' yt:format='6'/> <media:credit role='uploader' scheme='urn:youtube' yt:display='GoogleDevelopers'>GoogleDevelopers</media:credit> <media:description type='plain'> What could make for more exciting video? </media:description> <media:keywords>Shopping, parkas</media:keywords> <media:license type='text/html' href='http://www.youtube.com/t/terms'>youtube</media:license> <media:player url='https://www.youtube.com/watch?v=ZTUVgYoeN_b'/> <media:thumbnail url='http://img.youtube.com/vi/ZTUVgYoeN_b/2.jpg' height='90' width='120' time='00:00:03.500'/> <media:thumbnail url='http://img.youtube.com/vi/ZTUVgYoeN_b/1.jpg' height='90' width='120' time='00:00:01.750'/> <media:thumbnail url='http://img.youtube.com/vi/ZTUVgYoeN_b/3.jpg' height='90' width='120' time='00:00:05.250'/> <media:thumbnail url='http://img.youtube.com/vi/ZTUVgYoeN_b/0.jpg' height='360' width='480' time='00:00:03.500'/> <media:title type='plain'>Shopping for Coats</media:title> <yt:aspectRatio>widescreen</yt:aspectRatio> <yt:duration seconds='79'/> <yt:uploaded>2008-07-05T19:56:35.000-07:00</yt:uploaded> <yt:uploaderId>UC_x5XG1OV2P6uZZ5FSM9Ttw</yt:uploaderId> <yt:videoid>ZTUVgYoeN_b</yt:videoid> </media:group> <gd:rating min='1' max='5' numRaters='14763' average='4.93'/> <yt:recorded>2008-07-04</yt:recorded> <yt:statistics viewCount='383290' favoriteCount='7022'/> <yt:rating numDislikes='19257' numLikes='106000'/> </entry> </feed>
Displaying a list of videos
The following screenshot demonstrates how YouTube displays information in a video list. The screenshot is annotated, and the list following the screenshot explains how the display elements correspond to the information in an API response.

The screenshot displays the following information:
-
This element displays a title for the result set. In your application, this value could be the value of the
<title>tag or you could select other text appropriate to the requested feed or search result set. -
In this text, the number 15 would be taken from the
<openSearch:totalResults>tag. Please note that the value of this tag is an approximation of the total number of results and not necessarily an exact figure.If you wanted to also identify which items from the feed were being displayed – e.g. items 1 to 10 – you would also use the values of the
<openSearch:startIndex>and<openSearch:itemsPerPage>tags. -
The Sort by menu lets the user select a value for the
orderbyquery parameter. A pulldown menu showing how results are sorted also appears on the right side of the image, below the result count.The Filter options let the user set values for a number of other search parameters, including the
time,3d,caption,duration,hd,license,paid-content, anduploaderparameters. It also displays options to display either channel or playlist search results.The API Query Parameters section provides a complete list of the query parameters that the YouTube Data API supports and explains the types of queries for which each parameter applies.
-
This sorting menu also lets the user select a value for the
orderbyquery parameter. -
This element displays a thumbnail image of the video. YouTube API responses may contain multiple thumbnail images for a video, each of which is identified by a
<media:thumbnail>tag. The video duration also displays in the bottom right corner of the thumbnail image. The<yt:duration>specifies this value.On the YouTube website, the thumbnail image links to the watch page for the video. That page displays more information about the video as well as comments and rating information. In a video entry, the
<link>tag that has arelattribute value ofalternateidentifies the URL for the YouTube page where the user could watch the video. You could also use the video's<yt:videoid>to construct the URL or to play the video using an embedded (or chromeless) YouTube player. -
The title next to the thumbnail image is the value of the
<media:title>tag for that video. -
The snippet below the title shows parts of the video description, which is the value of the
<media:description>tag. -
The text and buttons below the video description show values from a number of tags:
- The byline, which identifies the video uploader, shows the value of the
<name>tag. - The time indicated in each result is calculated based on the value of the
<published>tag for the video. - The view count is taken from the
<yt:statistics>tag'sviewCountattribute. - In the third result, the HD text indicates that the
<yt:hd>is in the video entry.
- The byline, which identifies the video uploader, shows the value of the
To retrieve a feed entry for a single video in the result set, send a GET request to the edit URL for that entry, as explained in the following section. For example, you might issue this request if the user links from a set of search results to a video watch page that only displays information about the selected video.
Identifying feeds related to a feed entry
Each entry in a YouTube Data API response identifies several API URLs related to the video. For example, the entry identifies URLs that let you request comments for the video, video responses for the video or the video owner's YouTube public user profile. Some URLs may be used not only for retrieving information but also for creating, updating or deleting information. For example, you send a GET request to a URL to retrieve comments for that video and a POST request to the same URL to add a comment to that video.
Several API functions in this document refer to the edit URL for a video or other type of entry. (In a playlists feed, for example, an entry corresponds to a playlist rather than to a video.) Within a feed <entry>, the edit URL is the value of the href attribute in the <link> tag that has a rel attribute value of edit.
The following XML sample demonstrates how <link> tags appear in a YouTube Data API response. The edit URL in the example is shown in bold text.
<entry gd:etag='W/"C0AMRn47eCp7ImA9WxRQGUw."'> <id>tag:youtube,2008:video:dMH0bHeiRN</id> <link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/dmH0bHeiRN/responses'/> <link rel='http://gdata.youtube.com/schemas/2007#video.ratings' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/dmH0bHeiRN/ratings'/> <link rel='http://gdata.youtube.com/schemas/2007#video.complaints' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/dmH0bHeiRN/complaints'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/users/GoogleDevelopers/dmH0bHeiRN/uploads'/> <link rel='edit' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/users/GoogleDevelopers/dmH0bHeiRN/uploads'/> ... </entry>
The Using community features, Saving and collecting videos and Enabling user interaction sections of this document all present use cases describing situations when you might use a particular function to request, create, update or delete resources using the YouTube API. Each use case explains the API requests that you would send as well as the values that you would need to parse from the API responses to allow a user to progress through the use case. Frequently, these steps require you to send an API request to a URL identified within a <link> tag in an API response. The use cases identify the URLs for API requests using the value of the <link> tag's rel attribute.
For example, to retrieve a list of video responses for a video, you would send a GET request to the URL associated with the <link> tag with the rel attribute value http://gdata.youtube.com/schemas/2007#video.responses. To add a rating to a video, you would send a POST request to the URL associated with the <link> tag with the rel attribute value http://gdata.youtube.com/schemas/2007#video.ratings.
Displaying information about a video
The annotated screenshot below shows a YouTube video watch page, which primarily displays information about a single video. The list following the screenshot explains how to use the YouTube API to retrieve the information. Note that you would need to synthesize content from several API responses to reproduce this page using the API.

To display this page, you would first retrieve the feed for the video entry. The XML in a video entry feed is identical to the content that appears for that video in a feed or search result set. As shown above, this page also includes information from the video's comments feed and related videos feed. In addition, the pulldown menu below the video title shows information from the video owner's uploaded videos feed.
The screenshot displays the following information:
-
This item shows the title of the video. In a video entry, the
<media:title>tag contains the video's title. -
The Subscribe button next to the video owner's name (or channel icon) allows a user to subscribe to the video owner's activity feed.
The pulldown menu next to the button shows information from the video owner's uploaded videos feed. The pulldown shows the number of videos that the video owner has uploaded. This value is specified in the
<openSearch:totalResults>tag.When a user clicks on the pulldown, the pane shown below appears, displaying other videos uploaded by the video owner. Each video corresponds to an entry in the uploaded videos feed. For each video, the pane shows a thumbnail image (
<media:thumbnail>), the video duration (<yt:duration>), the video title (<media:title>, the video owner (<name>), and the video's view count (<yt:statistics>).
-
This item shows a video player. The Embedded player parameters document explains how to customize a YouTube embedded player in your own application. In addition, the <iframe> Player API Reference, the ActionScript 3.0 Player API Reference, and the JavaScript Player API Reference all explain how to build a chromeless player that uses your own custom controls.
-
This section displays the video's upload date (
<published>), description (<media:description>), view count (<yt:statistics>), and rating (<gd:rating>).This section also displays buttons for the user to rate the video, add the video to a playlist or "watch later" list, mark the video as a favorite, or flag the video for inappropriate content.
-
This section displays a list of comments for the video. In the video entry, the
<gd:feedLink>tag that has arelattribute value ofhttp://gdata.youtube.com/schemas/2007#commentsspecifies the number of comments on the video as well as the URL for the video's comments feed. You would need to retrieve that feed to actually display the comments.Your application could also display a link for a user to upload a video response or select a previously uploaded video as a video response. If the user then opted to upload a new video, your application would need to support either the browser-based uploading or direct uploading method for adding new videos to YouTube. After the user had uploaded the new video using one of those two methods, your application would retrieve the new video's ID and subsequently add the video as a video response.
-
This section displays a list of videos that YouTube considers similar to the video featured on the page. The related videos feed allows you to retrieve this list using the API.
Retrieving and searching for videos
Standard video feeds
This section explains how to retrieve standard YouTube feeds. Standard feeds contain lists of videos that either reflect YouTube user behavior, such as top-rated and most viewed video feeds, or were selected by YouTube staff, such as recently featured and mobile video feeds. Many of these feeds are shown on the Videos tab of the YouTube website.
Standard feeds are updated periodically, with the update frequency varying from feed to feed. Many feeds are updated every 30 to 40 minutes but other feeds – such as those that capture daily, weekly or monthly results – may only be updated hourly or even daily.
To retrieve a standard feed, send a GET request to the URL associated with that feed. The following table identifies the URL associated with each standard feed:
| Name | Feed Id | URL and Description |
|---|---|---|
| Top rated | top_rated | URL: https://gdata.youtube.com/feeds/api/standardfeeds/top_rated Description: This feed contains the most highly rated YouTube videos. |
| Top favorites | top_favorites | URL: https://gdata.youtube.com/feeds/api/standardfeeds/top_favorites Description: This feed contains videos most frequently flagged as favorite videos. |
| Most shared | most_shared | URL: https://gdata.youtube.com/feeds/api/standardfeeds/most_shared Description: This feed lists the YouTube videos most frequently shared on Facebook and Twitter. |
| Most popular | most_popular | URL: https://gdata.youtube.com/feeds/api/standardfeeds/most_popular Description: This feed contains the most popular YouTube videos, selected using an algorithm that combines many different signals to determine overall popularity. |
| Most recent | most_recent | URL: https://gdata.youtube.com/feeds/api/standardfeeds/most_recent Description: This feed contains the videos most recently submitted to YouTube. |
| Most discussed | most_discussed | URL: https://gdata.youtube.com/feeds/api/standardfeeds/most_discussed Description: This feed contains the YouTube videos that have received the most comments. |
| Most responded | most_responded | URL: https://gdata.youtube.com/feeds/api/standardfeeds/most_responded Description: This feed contains YouTube videos that receive the most video responses. |
| Recently featured | recently_featured | URL: https://gdata.youtube.com/feeds/api/standardfeeds/recently_featured Description: This feed contains videos recently featured on the YouTube home page or featured videos tab. |
| Trending videos | on_the_web | URL: https://gdata.youtube.com/feeds/api/standardfeeds/on_the_web Description: This feed lists trending videos as seen on YouTube Trends, which surfaces popular videos as their popularity is increasing and also analyzes broader trends developing within the YouTube community. |
| Most viewed | most_viewed | URL: https://gdata.youtube.com/feeds/api/standardfeeds/most_viewed Description: Deprecated on July 23, 2012. This feed actually returns the same content as the most_popular feed. As such, we recommend that you update your code to use the most_popular feed instead. |
In addition, please note that many of these feeds support the time query parameter, which allows you to restrict the feed to only contain relevant results from the previous day, week or month. For example, to retrieve top-rated videos from the previous day, you would send a GET request to the following URL:
https://gdata.youtube.com/feeds/api/standardfeeds/top_rated?time=today
Note: The top_rated, top_favorites, most_discussed, and most_responded standard feeds support the time parameter. The deprecated most_viewed feed also supported that parameter.
Retrieving region-specific standard video feeds
The API enables you to retrieve region-specific standard feeds by inserting a region ID in the feed URL. The following URL demonstrates the format of the URLs that you would use to retrieve region-specific standard feeds:
http://gdata.youtube.com/feeds/api/standardfeeds/regionID/feedID?v=2
For example, to retrieve a list of the top-rated videos in Japan, you would send a GET request to the following URL:
http://gdata.youtube.com/feeds/api/standardfeeds/JP/top_rated?v=2
The following tables identify the countries for which the YouTube Data API supports localized feeds and the regionID associated with each country:
|
|
Retrieving category-specific standard video feeds
The API also enables you to retrieve category-specific standard feeds by appending an underscore and a category name to the standard feed URL. The following URL demonstrates the format of the URLs that you would use to retrieve category-specific standard feeds:
https://gdata.youtube.com/feeds/api/standardfeeds/regionID/feedID_CATEGORY_NAME?v=2
For example, to retrieve a list of the top-rated comedies in Japan, you would send a GET request to the following URL:
https://gdata.youtube.com/feeds/api/standardfeeds/JP/top_rated_Comedy?v=2
Please note the following guidelines when generating URLs for category-based standard feeds:
-
The Category list for uploaded videos section explains how to retrieve the categories that could be used to classify video content. That section also explains how to identify the regions where each category is browsable.
-
If you retrieve a localized category list, the category name that you append to the URL is still the English word that is the value of the <atom:category> tag's term attribute in the category list.
Category listing: <atom:category term='Entertainment' label='Divertissement' xml:lang='fr-FR'> URL for feed of top-rated entertainment videos in France: https://gdata.youtube.com/feeds/api/standardfeeds/FR/top_rated_Entertainment
-
The regionID in the feed URL is optional. If you do not specify a region ID, the API response will contain a category-based standard feed that is not restricted to a particular locale.
-
If your request does specify a regionID, then the specified category must be browsable in the specified region. For example, you can request a feed of the top-rated nonprofit videos in the United States because "Nonprofit" is a browsable category in the United States. However, you cannot request the top-rated nonprofit videos in France since "Nonprofit" is not a browsable category there.
Videos uploaded by a specific user
This section explains how to retrieve a feed containing all of the videos uploaded by a specific user. You should not include search parameters in requests to retrieve an uploaded videos feed. The parameters will generate a feed from YouTube's search index, effectively restricting the result set to indexed, public videos, rather than returning a complete list of the user's uploaded videos.
-
To request a feed of all videos uploaded by the currently logged-in user, send a GET request to the following URL. This request requires an authentication token, which enables YouTube to identify the user.
https://gdata.youtube.com/feeds/api/users/default/uploads
To ensure that the API response contains the most up-to-date information available for the user's videos, do not use any parameters other than start-index and max-results in your request. Requests using other parameters, such as orderby, will return cached results.
Note: In the URL, the value default signifies that you are requesting videos uploaded by the currently logged-in user. The user is identified by the authentication token that you submit with the request. The default value is also used to identify the currently logged-in user in other API commands.
-
To request a feed of all videos uploaded by another user, send a GET request to the following URL. This request does not require authentication.
https://gdata.youtube.com/feeds/api/users/userId/uploads
In the URL above, you should replace the text
userIdwith the user's YouTube user ID. For backward compatibility purposes, the API also supports having the user's YouTube username specified instead. You can extract the user ID from the<yt:userId>tag and the username from either the<name>or the<yt:username>tag in an API response. The XML excerpt below shows both values:<author> <name>GoogleDevelopers</name> <uri>https://gdata.youtube.com/feeds/api/users/GoogleDevelopers</uri> <yt:userId>_x5XG1OV2P6uZZ5FSM9Ttw<</yt:userId> </author>
The API response for this query has exactly the same format as the sample response in the Understanding video feeds and entries section of this document.
Related videos
This section explains how to retrieve a feed containing a list of videos that are related to another video. YouTube algorithmically selects the set of related videos.
Each video entry in an API response contains a series of <link> tags. The <link> tag that has a rel attribute value of http://gdata.youtube.com/schemas/2007/#video.related identifies the URL for retrieving other videos related to that video entry. (The <link> tag's href attribute identifies the URL.)
<link rel="http://gdata.youtube.com/schemas/2007#video.related"
type="application/atom+xml"
href="https://gdata.youtube.com/feeds/api/videos/ZTUVgYoeN_b/related?v=2"/>
The API response for this query has exactly the same format as the sample response in the Understanding video feeds and entries section of this documentation.
Browsing with categories and keywords
This section explains how to retrieve a feed of all of the videos that are in a particular category or that are associated with a particular keyword. (YouTube uses the term "tag" to identify a keyword relevant to a video.) The examples also demonstrate how you can retrieve videos that are associated with a category and one or more keywords as well as videos that are not associated with particular categories or keywords.
Each video entry in an API response contains a series of <category> elements. Each <category> element identifies a category or keyword with which the corresponding video is associated. The element's scheme attribute indicates whether the element identifies a category or a keyword. The element's term attribute specifies the category or keyword term that you would use to locate videos as described in this section.
The YouTube Data API supports two different methods for retrieving videos that are in a particular category or that are labeled with a specific keyword or developer tag.
-
Use the following URL to retrieve videos that are in a specific category or that are labeled with a specific keyword or developer tag. The hyphen (-) in the URL is a standard Google Data API notation that indicates that the rest of the URL consists of a series of one or more tags.
https://gdata.youtube.com/feeds/api/videos/-/category_or_tag
The following example shows the URL that you would use to request videos in the "Comedy" category:
https://gdata.youtube.com/feeds/api/videos/-/Comedy
-
Specify the category, keyword or developer tags using the category parameter in the request URL. The following example shows the URL that you would use to request videos in the "Comedy" category:
https://gdata.youtube.com/feeds/api/videos?category=Comedy
The following guidelines provide more detail about requesting videos associated with particular categories or tags:
-
If your request specifies a category and one or more keywords or if your request does not specify a category but does specify multiple keywords, separate each individual category and keyword name with a forward slash. (If you are using the category parameter, separate the different category and tag names with a comma. (The comma must be URL-encoded in your request.) For example, you could use either of the following URLs to request videos related to the keywords "bass" and "fishing":
URL notation: https://gdata.youtube.com/feeds/api/videos/-/bass/fishing?v=2 category parameter: https://gdata.youtube.com/feeds/api/videos?category=bass%2Cfishing&v=2
-
Your request can use the Boolean NOT (-) and OR (|) operators to exclude videos or to find videos that are associated with one of several keywords or categories. For example, if you wanted to display videos related to "bass" and "music", the most effective search might be for videos associated with the keyword "bass" but not associated with the keywords "fish" or "fishing" as shown in the example below. (Searching for videos associated with the "Music" category and the keyword "bass" might exclude instructional videos about how to play bass.)
URL notation: https://gdata.youtube.com/feeds/api/videos/-/bass/-fish/-fishing?v=2 category parameter: https://gdata.youtube.com/feeds/api/videos?
category=bass%2C%2Dfish%2Dfishing&v=2The following example shows how to search for videos that are tagged with the keywords "Jesse" and "Ventura" and that are in either the "News" or "Sports" categories. The category names are separated by the value "%7C", which represents a URL-encoded pipe (|) character specifying that the video must be associated with one of the two categories:
URL notation: https://gdata.youtube.com/feeds/api/videos/-/jesse/ventura/News%7CSports?v=2 category parameter: https://gdata.youtube.com/feeds/api/videos?category=jesse%2Cventura%2CNews%7CSports&v=2
-
Capitalize the names of categories and lowercase the names of keywords. For example, the following query identifies videos associated with the keyword "comedy" that are not in the "Comedy" category:
URL notation: https://gdata.youtube.com/feeds/api/videos/-/comedy/-Comedy?v=2 category parameter: https://gdata.youtube.com/feeds/api/videos?category=comedy%2C%2DComedy&v=2
-
If you are generating category or keyword searches automatically based on the information in an API response, specify the schema as part of the category name to clearly differentiate YouTube categories from keyword tags or developer tags. The following URLs demonstrate how to specify the schema in the category name. (Note that each URL should actually appear on one line but has been split into multiple lines for printing purposes.)
Categories: URL notation: https://gdata.youtube.com/feeds/api/videos/-/ %7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007 %2Fcategories.cat%7DNews?v=2 category parameter: https://gdata.youtube.com/feeds/api/videos?category= %7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007 %2Fcategories.cat%7DNews&v=2 Keywords: URL notation: https://gdata.youtube.com/feeds/api/videos/-/ %7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007 %2Fkeywords.cat%7Ddog?v=2 category parameter: https://gdata.youtube.com/feeds/api/videos?category= %7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007 %2Fkeywords.cat%7Ddog&v=2 Developer tags: URL notation: https://gdata.youtube.com/feeds/api/videos/-/ %7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007 %2Fdevelopertags.cat%7Dexample.com?v=2 category parameter: https://gdata.youtube.com/feeds/api/videos?category= %7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007 %2Fdevelopertags.cat%7Dexample.com&v=2
-
Always specify the schema, as explained in the previous item, if you are requesting videos associated with a particular developer tag.
Searching for videos
This section explains how to use the API to retrieve a list of videos matching a user-specified search term. To search for videos, send a GET request to the following URL, appending the appropriate query parameters to your request:
https://gdata.youtube.com/feeds/api/videos
For example, a request to the following URL searches for the second set of 10 recently uploaded videos matching the query term "football" but not matching the query term "soccer":
https://gdata.youtube.com/feeds/api/videos?
q=football+-soccer
&orderby=published
&start-index=11
&max-results=10
&v=2
Standard Google Data API query parameters
The YouTube Data API supports the following standard Google Data query parameters.
| Name | Definition |
|---|---|
| alt | The alt parameter specifies the format of the feed to be returned. Valid values for this parameter are atom, rss, json, json-in-script, and jsonc. The default value is atom and this document only explains the format of Atom responses. For more information about using API responses in JavaScript, please see Using JSON with Google Data APIs. If you set the parameter value to json-in-script, then you must also set the callback parameter value to identify the callback function to which the API response will be sent. |
| author | In a search request, the author parameter restricts the search to videos uploaded by a particular YouTube user. Note that if you use this parameter when requesting a standard feed, then YouTube will retrieve the standard feed and then filter the response to only include videos uploaded by the specified author. For example, if you request the "Top Rated" feed for user GoogleDevelopers, the API will retrieve the top-rated feed and return a response containing videos in that feed uploaded by user GoogleDevelopers. The API will not return a list of that user's videos ordered by rating.
In a request for a user activity feed, the author parameter contains a comma-separated list of up to 20 YouTube usernames. The API response will contain activities performed by any of those users. |
| callback | The callback parameter identifies the callback function to which the API response will be sent. If the value of the alt parameter is jsonc or json-in-script, and you specify a value for the callback parameter, then the API response will be wrapped in a call to the specified function. This parameter is required if the value of the alt parameter is json-in-script. |
| fields | The fields parameter serves one or both of the following purposes:
|
| fields-language | The fields-language parameter is being used temporarily to force the API server to apply new syntax rules affecting requests to retrieve partial API responses. The rules determine whether a tag's text content is returned in a partial response. They also let you filter results based on the presence of an element that does not contain text content. For example, you could retrieve all entries containing the <app:control> tag, which has subtags but does not contain text content. The new rules are explained in detail in the release notes for August 31, 2010.To use the new syntax rules for partial API responses, or to filter results based on the presence of an element that does not contain text content, set the fields-language parameter value to r2. (This is the only valid value for this parameter.)Note: Following a testing period, the new syntax rules will apply to all requests for partial API responses, and the API server will ignore the fields-language parameter. |
| max-results | The max-results parameter specifies the maximum number of results that should be included in the result set. This parameter works in conjunction with the start-index parameter to determine which results to return. For example, to request the second set of 10 results – i.e. results 11-20 – set the max-results parameter to 10 and the start-index parameter to 11. The default value of this parameter is 25, and the maximum value is 50. However, for displaying lists of videos, we recommend that you set the max-results parameter to 10. |
| prettyprint | The prettyprint parameter lets you request an XML response formatted with indentations and line breaks. Set the parameter's value to true to have the response formatted as such. The default parameter value is false. |
| start-index | The start-index parameter specifies the index of the first matching result that should be included in the result set. This parameter uses a one-based index, meaning the first result is 1, the second result is 2 and so forth. This parameter works in conjunction with the max-results parameter to determine which results to return. For example, to request the second set of 10 results – i.e. results 11-20 – set the start-index parameter to 11 and the max-results parameter to 10. |
| strict | The strict parameter can be used to instruct YouTube to reject an API request if the request contains invalid request parameters. The default API behavior is to ignore invalid request parameters. If you want YouTube to reject API requests that contain invalid parameters, set the strict parameter value to true. For example, YouTube would reject the following request because "foo" is not a valid request parameter.https://gdata.youtube.com/feeds/api/videos?foo=nonono&strict=true |
| v | The v parameter specifies the version of the API that YouTube should use to handle the API request. Your request can specify the desired API version using either the v parameter or the GData-Version HTTP request header. All Google-provided client libraries always select a major API version. If your request does not specify an API version, YouTube will handle your request using API version 1. Please see the API versioning section for more information about specifying an API version. The current API version is 2. Setting the v parameter value (or the GData-Version HTTP request header value) to 2 allows your application to access features that may not be available in previous API versions. For example, captions are only supported in API version 2, and the API supports some different parameters in version 2 than it did in version 1.
|
Please see the Google Data APIs Protocol Reference for more information about standard Google Data API functionality or about these specific parameters.
Custom query parameters for the YouTube Data API
In addition to the standard Google Data query parameters, the YouTube Data API defines the following API-specific query parameters:
|
Parameters for all API requests: key Search parameters: 3d caption category duration format hd license location location-radius lr orderby q safeSearch time uploader Additional parameters for all video feeds: restriction Additional parameters for caption track feeds: fmt lang Additional parameters for user activity feeds: inline |
Additional parameters for movie charts: hl movie-genre paid-content region Additional parameters for show charts: genre region Additional parameters for YouTube EDU feeds: category course Additional parameters for live event feeds: ends-after ends-before inline starts-after starts-before status time Additional parameters for username suggestion feeds: hint |
In general, parameters that are used for filtering and ordering results are only supported for search requests, though there are several exceptions listed above. The API also supports the time parameter for many standard feeds, the author parameter for user activity feeds, and the restriction parameter for video feeds. Please see the Testing and troubleshooting section for tips on how to filter API response feeds that do not support these parameters.
In particular, you should not include search parameters in requests to retrieve an uploaded videos feed. By doing so, you are instructing the API to generate a feed from YouTube's search index, effectively restricting the result set to indexed, public videos rather than retrieving a complete list of the user's uploaded videos.
The following table defines the API's custom search parameters:
| Name | Definition | ||||||||
|---|---|---|---|---|---|---|---|---|---|
3d |
The 3d parameter lets you restrict a search to only retrieve 3D videos. This parameter is supported for video search requests, related videos feeds, and standard feeds. It is also only supported in API version 2.To only retrieve 3D videos, set the 3d parameter value to true or include the parameter in your request but do not specify a parameter value. Note that false is not a valid parameter value, and you cannot restrict search results to exclude 3D videos. The API's default behavior is to include both 3D and non-3D videos in returned results. In a video feed entry, the <yt:threed> tag indicates that a video contains 3D content.Note: The API will return an HTTP 400 response if you specify any parameter value other than true. |
||||||||
caption |
The caption parameter enables you to restrict a search to videos that have or do not have caption tracks:
true or false. |
||||||||
category |
The category parameter has two uses:
|
||||||||
client |
Deprecated on March 22, 2010. API requests no longer need to specify a client ID. The client parameter specifies an alphanumeric string that identifies the developer or distributor of an application. The client parameter is an alternate way of specifying your client ID. You can also use the X-GData-Client request header to specify your client ID. |
||||||||
course |
The course parameter lets you retrieve a list of lectures (videos) associated with the specified course. The parameter's value is a YouTube playlist ID that uniquely identifies a course that is accessible via YouTube EDU. |
||||||||
duration |
The duration parameter lets you filter search results based on video length. The following parameter values are valid:
<yt:duration> tag specifies a video's length. |
||||||||
ends-after |
The ends-after parameter restricts a live events feed to only include events that ended or are scheduled to end at or after the specified date and time. The parameter value must be a date or a date and time in ISO 8601 format.
|
||||||||
ends-before |
The ends-before parameter restricts a live events feed to only include events that ended or are scheduled to end at or before the specified date and time. The parameter value must be a date or a date and time in ISO 8601 format.
|
||||||||
fmt |
The fmt parameter specifies the return format for a caption track that you are retrieving via the API. Set the parameter value to one of the following values:
sbv) format. The API will return an HTTP 400 response code if YouTube cannot convert the original caption track to the requested format. |
||||||||
format |
The format parameter, which is supported for video search requests, specifies that videos must be available in at least one of the video formats listed in the parameter value. Your request can specify one or more of the following formats:
To specify multiple formats, separate format values with a comma. For example, format=1,5 indicates that the API should return videos that are available in at least one of those two formats.
|
||||||||
genre |
The genre parameter restricts a show chart to only include shows in a particular genre. The parameter value is an integer that corresponds to a particular genre. The following values are valid:
|
||||||||
hd |
The hd parameter lets you restrict a search to only include HD videos, meaning videos that are available for playback in at least 720p. Higher resolutions, like 1080p, might be available for HD videos as well. This parameter is supported for video search requests, related videos feeds, and standard feeds. It is also only supported in API version 2.To only retrieve HD videos, set the hd parameter value to true or include the parameter in your request but do not specify a parameter value. Note that false is not a valid parameter value, and you cannot restrict search results to exclude HD videos. The API's default behavior is to return all videos, regardless of their resolution. In a video feed entry, the <yt:hd> tag indicates that a video contains HD content.Note: The API will return an HTTP 400 response if you specify any parameter value other than true. |
||||||||
hint |
Deprecated. The hint parameter, which is now deprecated, was specified in a request to retrieve a list of unused YouTube channel names similar to that hint. |
||||||||
hl |
The hl parameter specifies the primary language of the movies in a movie chart. The parameter value is an ISO 639-1 two-letter language code. |
||||||||
inline |
The inline parameter is only supported for activity feeds and live event feeds.
false.
|
||||||||
key |
The key parameter specifies your developer key, an alphanumeric string that uniquely identifies the application making an API request. You can also use the X-GData-Key request header to specify your developer key. Your application does not need to specify your developer key twice by using both the key parameter and the X-GData-Key request header, but it should provide your developer key using at least one of those two methods. |
||||||||
lang |
The lang parameter specifies the language into which you want a caption track to be translated. Set the parameter value to the ISO 639-1 two-letter language code that identifies the desired caption language.YouTube supports this parameter for requests to retrieve a caption track. The API will return an HTTP 400 response code if YouTube cannot translate the caption track to the requested language or if the language code that you specified is not valid. |
||||||||
license |
The license parameter lets you filter search results to only include videos with a particular license. YouTube lets video uploaders choose to attach either the Creative Commons license or the standard YouTube license to each of their videos, and the license parameter supports the following values:
<media:license> tag identifies the license that is associated with a video. |
||||||||
location |
Not working. This API parameter is temporarily disabled. See the API issue tracker for more information. The location parameter restricts the search to videos that have a geographical location specified in their metadata.
The parameter can be used in either of the following contexts:
YouTube supports this parameter for video search requests. |
||||||||
location-radius |
Not working. This API parameter is temporarily disabled. See the API issue tracker for more information. The location-radius parameter, in conjunction with the location parameter, defines a geographic area. If the geographic coordinates associated with a video fall within that area, then the video may be included in search results.The location-radius parameter value must be a floating point number followed by a measurement unit. Valid measurement units are m, km, ft and mi. For example, valid parameter values include "1500m", "5km", "10000ft" and "0.75mi". The API will return an error if the radius is greater than 1000 kilometers.YouTube supports this parameter for video search requests. |
||||||||
lr |
In a video search request, the lr parameter restricts the search to videos that have a title, description or keywords in a specific language. This parameter can be used when requesting any video feeds other than standard feeds.In a request to retrieve a list of the caption tracks available for a video, the lr parameter filters the list of caption tracks to only include the specified language. Valid values for the lr parameter are ISO 639-1 two-letter language codes. You can also use the values zh-Hans for simplified Chinese and zh-Hant for traditional Chinese.
|
||||||||
movie-genre |
The movie-genre parameter restricts a movie chart to only include movies in a particular genre. The parameter value is an integer that corresponds to a particular genre. The following values are valid:
|
||||||||
orderby |
The orderby parameter, which is supported for video feeds and playlist feeds, specifies the method that will be used to order entries in the API response. The parameter is used differently for video and playlist feeds:
|
||||||||
paid-content |
The paid-content parameter can be used to restrict a search or a movie chart to only include either paid content or free content. By default, search results and movie charts include both paid and free content.
paid_content parameter for movie chartsFor paid content, the video uploader will define offers that specify the country where a video can be rented. For example, a movie may be available for rental in the United States before it can be rented in other countries. As such, you must also specify a value for the region parameter if you want any paid content to be included in the API results. |
||||||||
q |
The q parameter specifies a search query term. YouTube will search all video metadata for videos matching the term. Video metadata includes titles, keywords, descriptions, authors' usernames, and categories.Note that any spaces, quotes or other punctuation in the parameter value must be URL-escaped. To search for an exact phrase, enclose the phrase in quotation marks. For example, to search for videos matching the phrase "spy plane", set the q parameter to %22spy+plane%22.Your request can also use the Boolean NOT (-) and OR (|) operators to exclude videos or to find videos that are associated with one of several search terms. For example, to search for videos matching either "boating" or "sailing", set the q parameter to boating%7Csailing. (Note that the pipe character must be URL-escaped.) Similarly, to search for videos matching either "boating" or "sailing" but not "fishing", set the q parameter to boating&7Csailing+-fishing. |
||||||||
region |
The region parameter restricts a movie or show chart to only list content that is viewable in a specified region. If set, the parameter value must be an ISO 3166-1 alpha-2 country code. The default behavior is to return content that is viewable worldwide.Important: You must specify a region parameter value if you want a movie chart to include rental (paid-content) videos. If you do not specify a value for this parameter, the chart will only contain movies that are viewable worldwide. Since each video rental offer specifies the country where the offer is valid, YouTube can only determine whether a user could potentially view a rental video if an API request specifies the country where the user is located. Since there are no rental videos that are accessible worldwide, a chart will be empty if you set the paid-content parameter to true for a movie chart and do not also specify a region parameter value. |
||||||||
restriction |
The restriction parameter lets the API server apply country restrictions that are based on the end user's location for videos that can only be played in specific countries. The parameter value identifies the end user's IP address to the API server. We recommend that you always use this parameter to specify the end user's IP address. However, it is particularly important to set this parameter when a server or middle layer in your application stack uses the API on the end user's behalf and also sends all of the API requests on the user's behalf. This case usually applies to website applications that use the API.If you do not set the restriction parameter value, then the API server might apply country restrictions incorrectly. For example, it might base restrictions on your middle-layer server's location rather than on the end user's actual location. Note that the API's Terms of Service prohibit lying about an end user's location to circumvent these restrictions.There are two ways to use this parameter:
<entry> for that tag will not contain a <media:content> tag. However, it will contain a <yt:state> tag that indicates that the video is restricted.
|
||||||||
safeSearch |
The safeSearch parameter indicates whether the search results should include restricted content as well as standard content. YouTube will determine whether content is restricted based on the user's IP address or location, which you specify in your API request using the restriction parameter. If you do request restricted content, then feed entries for videos that contain restricted content will contain the <media:rating> element.The following values are valid for this parameter:
Note: The safeSearch parameter was introduced in version 2 of the YouTube Data API and replaced the racy parameter, which was used in version 1.YouTube supports this parameter for video search requests. |
||||||||
starts-after |
The starts-after parameter restricts a live events feed to only include events that began or are scheduled to begin at or after the specified date and time. The parameter value must be a date or a date and time in ISO 8601 format.
|
||||||||
starts-before |
The starts-before parameter restricts a live events feed to only include events that began or are scheduled to begin at or before the specified date and time. The parameter value must be a date or a date and time in ISO 8601 format.
|
||||||||
status |
The status parameter restricts a live event feed to only list events with the specified status. The following values are valid:
|
||||||||
time |
The time parameter is supported for search feeds and for a number of standard feeds and live event charts as well. Valid values for this parameter are today (1 day), this_week (7 days), this_month (1 month) and all_time. The default value for this parameter is all_time.
|
||||||||
uploader |
The uploader parameter, which is only supported for search requests, lets you restrict a query to YouTube partner videos. A YouTube partner is a person or organization that has been accepted into and participates in the YouTube Partner Program. The uploader parameter's value must be partner.In an API response, a feed entry contains a partner video if the entry contains a <media:credit> tag for which the value of the yt:type attribute is partner.<media:credit role='uploader' scheme='urn:youtube' yt:display='partner_name' yt:type='partner'>partner_name</media:credit> YouTube supports this parameter for video search requests. |
Retrieving information about a single video
To retrieve information about a single video, you can send a GET request to the following URL. (You need to replace the text videoid with the video's actual video ID.)
https://gdata.youtube.com/feeds/api/videos/videoid?v=2
Note: The video ID for a video is identified in feed entries by the <yt:videoid> tag. This tag appears in video feed entries – including standard feeds, search results, user-uploaded video feeds, etc. – as well as in favorite video feed entries, playlist feed entries, inbox feed entries and several types of activity feed entries.
The API response to a request for a single video feed entry is an Atom entry that contains information about the video. The root tag of the response is <entry>. The entry itself contains the same tags as the sample feed entry in the Understanding video feeds and entries section.
Retrieving information about the currently logged-in user's videos
To retrieve the most up-to-date information for a video uploaded by the currently logged-in user, send an authenticated GET request to the following URL. Note that your request can use the start-index or max-results parameters but cannot use any other request parameters.
https://gdata.youtube.com/feeds/api/users/default/uploads/videoid?v=2
For more information, please see the Checking the status of an uploaded video section.
Retrieving and searching for channels
The following sections explain how to use the API to retrieve a list of channels matching a user-specified search term or to retrieve standard feeds of the channels with the most video views or subscribers:
Searching for channels
You can search for channels matching a user-specified search term by sending a GET request to the following URL and using the q query parameter to specify a search term. YouTube could match the search term to the channel name, description or other channel-related fields.
https://gdata.youtube.com/feeds/api/channels
YouTube supports the following API query parameters for channel search:
Note: Since the query term could be matched against the channel description, the q parameter value could contain multiple words. You can also search for an exact phrase as described in the q parameter definition. However, for channel search requests, the q parameter does not support the Boolean NOT (-) and OR (|) operators.
Sample channel search request
The following API request searches for the second set of 10 channels matching the query term "soccer":
https://gdata.youtube.com/feeds/api/channels?
q=soccer
&start-index=11
&max-results=10
&v=2
This request yields the following response:
<?xml version='1.0' encoding='UTF-8'?> <feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/"CEEERnk_fCp7ImA9WxRUEU4."'> <id>tag:youtube.com,2008:channels</id> <updated>2008-11-19T14:10:07.744-08:00</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#channel'/> <title>YouTube Channels matching query: soccer</title> <logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo> <link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/channels?v=2'/> <link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/channels/batch?v=2'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/channels?q=soccer&start-index=11&max-results=10&v=2'/> <link rel='service' type='application/atomsvc+xml' href='https://gdata.youtube.com/feeds/api/channels?alt=atom-service&v=2'/> <link rel='next' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/channels?q=soccer&start-index=21&max-results=10&v=2'/> <author> <name>YouTube</name> <uri>http://www.youtube.com/</uri> </author> <generator version='2.0' uri='http://gdata.youtube.com/'>YouTube data API</generator> <openSearch:totalResults>6141</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>25</openSearch:itemsPerPage> <entry gd:etag='W/"CEEERnk_fCp7ImA9WxRUEU4."'> <id>tag:youtube.com,2008:channel:dXNzb2NjZXJkb3Rjb20</id> <updated>2008-11-19T14:10:07.744-08:00</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#channel'/> <category scheme='http://gdata.youtube.com/schemas/2007/channeltypes.cat' term='director'/> <title>U.S. Soccer</title> <summary> ussoccer.com's comprehensive coverage of the U.S. National Teams welcomes fans to our YouTube channel - including interviews, press conferences... </summary> <link rel='http://gdata.youtube.com/schemas/2007#featured-video' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/bYKugypF8HA?v=2'/> <link rel='alternate' type='text/html' href='https://www.youtube.com/profile?user=ussoccerdotcom'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/channels/dXNzb2NjZXJkb3Rjb20?v=2'/> <author> <name>ussoccerdotcom</name> <uri>https://gdata.youtube.com/feeds/api/users/ussoccerdotcom</uri> <yt:userId>k1pcWQ5E19g0Cgp4c1eI1w</yt:userId> </author> <yt:channelId>UCk1pcWQ5E19g0Cgp4c1eI1w</yt:userId> <yt:channelStatistics subscriberCount='29317' viewCount='1737927'/> <gd:feedLink rel='http://gdata.youtube.com/schemas/2007#channel.content' href='https://gdata.youtube.com/feeds/api/users/ussoccerdotcom/uploads?v=2' countHint='513'/> <media:thumbnail url='http://i.ytimg.com/i/k1pcWQ5E19g0Cgp4c1eI1w/1.jpg'/> </entry> <entry> ... </entry> ... </feed>
Each entry in the response contains information about a YouTube channel that matches the search request. Entries contain the following information:
-
The <title> and <summary> tags specify a name and description of the channel, respectively.
-
The <author> tag identifies the owner of the channel, and the <uri> tag within the <author> tag specifies the feed URL that you would use to retrieve more information about the channel owner.
-
The <gd:feedLink> tag, which has a
relattribute value ofhttp://gdata.youtube.com/schemas/2007#channel.content, identifies the URL that you would use to retrieve a feed of the videos in the channel. -
The <link> tags contain links relevant to the channel, including a link to the channel's featured video and a link to the channel owner's profile page.
-
One <category> tag specifies that the entry contains information about a channel. An additional <category> tag may be present indicating that the type of channel that the entry describes. Channel types include
director,guruandmusician. See http://gdata.youtube.com/schemas/2007/channeltypes.cat for a complete list of channel types.
Standard feeds for channels
The API also lets you retrieve standard feeds that list the most viewed or most subscribed YouTube channels. Standard channel feeds are only supported in version 2 of the API. To retrieve a standard channel feed, send a GET request to the URL associated with that feed.
The following table identifies the URL associated with each standard feed:
| Name | Feed Id | URL and Description |
|---|---|---|
| Most viewed | most_viewed | URL: https://gdata.youtube.com/feeds/api/channelstandardfeeds/most_viewed?v=2 Description: This feed lists the most frequently watched YouTube channels. This metric accounts for all views of videos uploaded to a channel. |
| Most subscribed | most_subscribed | URL: https://gdata.youtube.com/feeds/api/channelstandardfeeds/most_subscribed?v=2 Description: This feed lists the channels with the most subscribers or the most new subscribers during a given time period. |
The XML excerpt below shows the format of a standard channel feed entry:
<entry> <id>tag:youtube.com,2008:standardchannel:expertvillage</id> <updated>2010-10-28T19:07:55.377Z</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#channelstandard'/> <title>Expert Village - Watch and Learn</title> <summary>Welcome to the official YouTube channel of Expert Village. We are known for our largest choice of informative videos from trusted sources to provide answers to your everyday questions.</summary> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/channelstandardfeeds/most_viewed/c/expertvillage?v=2'/> <author> <name>expertvillage</name> <uri>https://gdata.youtube.com/feeds/api/users/expertvillage</uri> <yt:userId>QlGBspQdj17WOPBQMT1k9A</yt:userId> </author> <yt:channelId>UCQlGBspQdj17WOPBQMT1k9A</yt:channelId> <yt:channelStatistics commentCount='887' totalUploadViewCount='1481786054' videoCount='138756' viewCount='22295173'/> <media:group> <media:thumbnail url='http://i2.ytimg.com/i/QlGBspQdj17WOPBQMT1k9A/1.jpg?v=89e277'/> <media:title>Expert Village - Watch and Learn</media:title> </media:group> </entry>
Both standard channel feeds support the time query parameter, which lets you restrict the feed to only contain relevant results from the previous day, week or month. For example, to retrieve the most viewed channels from the previous day, you would send a GET request to the following URL:
https://gdata.youtube.com/feeds/api/channelstandardfeeds/most_viewed?time=today&v=2
Note: YouTube does not generate a feed of the most subscribed channels from the previous day. As such, the only supported values of the time parameter for the most_subscribed feed are this_week, this_month, and all_time.
Retrieving region-specific standard channel feeds
The API enables you to retrieve region-specific standard channel feeds by inserting a region ID in the feed URL. (You would also use a region ID to retrieve a region-specific video feed.) The following URL shows the format of the request URL for retrieving region-specific standard channel feeds:
https://gdata.youtube.com/feeds/api/channelstandardfeeds/regionID/feedID?v=2
For example, to retrieve a list of the most-viewed channels in Sweden, you would send a GET request to the following URL:
https://gdata.youtube.com/feeds/api/channelstandardfeeds/SE/most_viewed?v=2
See the Retrieving region-specific standard video feeds section for a list of supported countries and their associated regionID values.
Retrieving standard channel feeds by user type
You can retrieve standard channel feeds for specific types of users by appending an underscore and a user type to the feed type in the feed URL. For example, the following URL retrieves a feed of the most viewed musician channels in the United States:
https://gdata.youtube.com/feeds/api/channelstandardfeeds/US/most_viewed_Musicians?v=2
Valid user types that can be appended to the feed URL are Comedians, Directors, Gurus, Musicians, Non-profit, Partners, Politicians, Reporters, and Sponsors. These values are case-sensitive and can be found in the channeltypes.cat XML document.
Note: If you request a standard channel feed for a specific user type, you can also specify a region.
Searching for playlists
This section explains how to use the API to retrieve a list of playlists matching a user-specified search term. YouTube tries to match the search term to playlist names and descriptions as well as to the metadata fields for videos in each playlist. To search for playlists, send a GET request to the following URL:
https://gdata.youtube.com/feeds/api/playlists/snippets
YouTube supports the following API query parameters for playlist search:
altqmax-resultsstart-indexstrictv– this feed is only available in API version 2 (v=2)
Note: The q parameter value can contain multiple words, and it can also use the Boolean NOT (-) and OR (|) operators. However, playlist search requests do not support searches for an exact phrase, as described in the q parameter definition.
Sample playlist search request
The following API request searches for the second set of 10 playlists matching the query term "GoogleDevelopers":
https://gdata.youtube.com/feeds/api/playlists/snippets?
q=GoogleDevelopers
&start-index=11
&max-results=10
&v=2
This request yields the following response:
<?xml version='1.0' encoding='UTF-8'?> <feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:media='http://search.yahoo.com/mrss/' xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:yt='http://gdata.youtube.com/schemas/2007' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/"DEAAQH44eip7ImA9WxVUGUQ."'> <id>tag:youtube.com,2008:playlists:snippets</id> <updated>2009-03-25T15:59:01.032Z</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlistLink'/> <title>YouTube Playlists matching query: GoogleDevelopers</title> <logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo> <link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/playlists/snippets?v=2'/> <link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/playlists/snippets/batch?v=2'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/playlists/snippets?q=GoogleDevelopers&start-index=1&max-results=25&v=2'/> <link rel='service' type='application/atomsvc+xml' href='https://gdata.youtube.com/feeds/api/playlists/snippets?alt=atom-service&v=2'/> <link rel='next' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/playlists/snippets?q=GoogleDevelopers&start-index=26&max-results=25&v=2'/> <author> <name>YouTube</name> <uri>http://www.youtube.com/</uri> </author> <generator version='2.0' uri='http://gdata.youtube.com/'>YouTube data API</generator> <openSearch:totalResults>5590</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>25</openSearch:itemsPerPage> <entry gd:etag='W/"D0ANRn47eCp7ImA9WxVUF04."'> <id>tag:youtube.com,2008:playlist:snippet: PL5D286BD1D14EAF40</id> <published>2008-05-26T23:39:53.000Z</published> <updated>2009-03-21T12:45:57.000Z</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlistLink'/> <title>Google Data <b>APIs</b></title> <summary/> <content type='application/atom+xml;type=feed' src='https://gdata.youtube.com/feeds/api/playlists/PL5D286BD1D14EAF40?v=2'/> <link rel='related' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/users/GoogleDevelopers?v=2'/> <link rel='alternate' type='text/html' href='https://www.youtube.com/view_play_list?p= PL5D286BD1D14EAF40'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/playlists/snippets/PL5D286BD1D14EAF40?v=2'/> <link rel='edit' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/playlists/snippets/PL5D286BD1D14EAF40?v=2'/> <author> <name>GoogleDevelopers</name> <uri>https://gdata.youtube.com/feeds/api/users/GoogleDevelopers</uri> </author> <yt:countHint>4</yt:countHint> <media:group> <media:thumbnail url="http://i.ytimg.com/vi/OOE9l23P7jg/default.jpg" height="90" width="120" yt:name="default"/> <media:thumbnail url="http://i.ytimg.com/vi/OOE9l23P7jg/mqdefault.jpg" height="180" width="320" yt:name="mqdefault"/> <media:thumbnail url="http://i.ytimg.com/vi/OOE9l23P7jg/hqdefault.jpg" height="360" width="480" yt:name="hqdefault"/> </media:group> <yt:playlistId> PL5D286BD1D14EAF40</yt:playlistId> </entry> <entry> ... </entry> </feed>
Each entry in the response contains information about a YouTube playlist that matches the search request. Entries contain the following information:
-
The <title> and <summary> tags specify a name and description of the playlist, respectively. (Note that some playlists may not have a description, in which case the <summary> tag will be empty.)
-
The <author> tag identifies the owner of the playlist.
-
The <content> tag identifies the URL that you would use to retrieve a feed of the videos in the playlist.
-
The <link> tags contain links relevant to the playlist, including a link to retrieve the playlist owner's profile data through the API and a link to view the playlist on the YouTube website.
-
The <yt:playlistId> tag contains a value that YouTube uses to uniquely identify a playlist. You could use this value to add a subscription to the playlist.
-
The <yt:countHint> tag specifies the number of videos in the playlist.
Uploading videos
The YouTube Data API provides two methods for uploading videos to YouTube. A newly uploaded video will be included in a user's uploaded videos feed a few minutes after the upload completes and YouTube finishes processing the video. In addition, a newly uploaded video will typically be included in search results a couple of hours after the upload completes and YouTube finishes processing the video. However, this delay may be longer during periods of heavy API server loads.
-
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.
-
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.
The API also supports a direct, resumable uploading process, which can be restarted from the point of interruption if the connection between your application and YouTube is lost at any point during the uploading process.
In addition to choosing an uploading method, you must also choose the authentication scheme appropriate for your application. The following sections provide additional information about the video uploading process:
- Technical requirements for uploaded videos
- Setting access controls for a video
- Assigning developer tags
- Browser-based uploading
- Direct uploading
- Resumable uploads
- Checking the status of an uploaded video
Technical requirements for uploaded videos
Legal requirements
You must be either the copyright holder or the authorized representative of the copyright owner for all video files that you deliver to YouTube. Similarly, users who upload videos to YouTube from your site must be either the copyright holder or the authorized representative of the copyright owner for all videos that they upload.
Technical requirements
We encourage you and your users to provide the highest quality video possible. YouTube's recommended video specifications can be found online in YouTube's Help Center and we recommend that you convey these guidelines to your users.
In addition to these guidelines, please note that video files must be 64 GB or smaller. All users can upload videos up to 15 minutes long, and many users with a history of complying with the YouTube Community Guidelines can upload videos longer than that. You may compress API requests using gzip transfer-encoding. However, please note that the 64 GB size restriction still applies to the uncompressed video file.
Metadata requirements
Each uploaded video must have a title and must also be associated with a category. You can choose any of the following methods to set these values:
-
You can specify the title and category for an uploaded video using the
<media:title>and<media:category>elements. -
You can include the
<yt:incomplete>element in the uploaded video's metadata. This element instructs YouTube to automatically generate certain metadata values if they are not otherwise specified. YouTube uses the following rules to generate metadata if the<yt:incomplete>element is included in the metadata for the uploaded video:- If the entry does not contain a
<media:title>element, YouTube sets the video's filename as the video title. If you use browser-based uploading, the filename is passed in thefileinput field. If you use direct uploading, including resumable uploading, the filename is the value of theSlugHTTP request header. - If the entry does not contain a
<media:keywords>element, YouTube sets the video's filename as the video's keyword tag. - If the entry does not contain a
<media:category>element, YouTube sets the video's category to the category of the last video that the user uploaded. If no prior upload exists, YouTube sets the video's category toPeople.
For example, the sample direct uploading request below would upload a video with the title
summer_vacation.mp4and keywordsummer_vacation.mp4in theTravel & Eventscategory.POST /feeds/api/users/default/uploads HTTP/1.1 Host: uploads.gdata.youtube.com Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=adf15ee97731bca89da876c...a8dc Slug: summer_vacation.mp4 Content-Type: multipart/related; boundary="f93dcbA3" Content-Length: 1941255 Connection: close --f93dcbA3 Content-Type: application/atom+xml; charset=UTF-8 <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007"> <media:group> <yt:incomplete/> <media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">Travel </media:category> </media:group> </entry> --f93dcbA3 Content-Type: video/mp4 Content-Transfer-Encoding: binary <Binary File Data> --f93dcbA3-- - If the entry does not contain a
-
If you are uploading videos via the resumable uploading process, you can upload a video without any metadata whatsoever. See the Uploading a video without metadata section for details about this option for resumable uploads. In this case, YouTube will handle the absence of metadata as if the upload request consisted of an
<entry>that only contained a<yt:incomplete>element.
You can only include the <yt:incomplete> element in a video entry at the time that you upload the video. When you retrieve a video entry for a video uploaded with incomplete metadata, the entry will contain the <yt:incomplete> element. If you choose to update the video, you must at least remove the <yt:incomplete> element from the entry before submitting your update request.
Note that videos uploaded with the <yt:incomplete> element will not be included in YouTube's search index, and therefore will not appear in search results, until their metadata has been updated. After the video's metadata is updated, and the <yt:incomplete> element is removed from the metadata, then the video will be eligible for inclusion in YouTube's search index.
Setting access controls for a video
When uploading (or updating) a video, you can specify access controls for that video. The table below defines the access controls that you can set for each video and lists the permissions that you can set for each control. The default setting for each control is marked with an asterisk.
| Control | Permissions | Definition |
|---|---|---|
| rate | allowed* denied |
This control indicates whether users can rate the video. |
| comment | allowed* moderated denied |
This control indicates whether users can add comments about the video. If you moderate comments, then you must approve new comments before they will be visible to other users. |
| commentVote | allowed* denied |
This setting indicates whether users can rate comments about the video. |
| videoRespond | allowed moderated* denied |
This setting indicates whether users can add video responses to the video. If you moderate video responses, then you must approve new responses before they will be visible to other users. |
| list | allowed* denied |
This setting indicates whether a video can be listed in YouTube search results or displayed in any other way unless the user has a URL that links directly to the video. The permission for this setting will be denied if the video is either unlisted or private. If you set the value to denied for a public video, then that video will become an unlisted video. |
| embed | allowed* denied |
This setting indicates whether users can embed the video on third-party websites. |
| syndicate | allowed* denied |
This setting indicates whether YouTube can show the video on non-web platforms, such as mobile phones and televisions. |
To set access controls for a video, include one <yt:accessControl> tag for each control that you want to set as shown in the following example:
<item> ... <yt:accessControl action='videoRespond' permission='allowed'/> </item>
If you do not specify access control settings when you upload (or update) a video, YouTube will apply the default access controls for that video. If you only specify some access controls, then default settings will be applied for the unspecified controls. Finally, the API will return an error if you specify multiple permissions for the same access control, with the exception of the special use case for comments described below.
Note: If a user has uploaded content, such as a music video, that is owned by another user, then the actual content owner may override the access control settings that the uploader provided. See the <yt:accessControl> tag definition for a list of exceptions.
Assigning developer tags
When you upload a video, you can associate that video with one of YouTube's video categories. You can also associate the video with additional keywords, or developer tags, that you use to identify the video. By using developer tags, you can identify all of the videos uploaded through your website or even through specific areas of your website. YouTube will not display developer tags to YouTube users; however, you can retrieve or update videos that match a specific developer tag.
Note: You can only associate developer tags 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.
To associate developer tags with a video, include one <media:category> tag in your Upload API request for each developer tag. Set the value of the scheme attribute to http://gdata.youtube.com/schemas/2007/developertags.cat and the tag value to the keyword you want to associate with the video. When choosing values to use for developer tags, remember that developer tag searches are not case-sensitive. In addition, note the following restrictions:
- Each developer tag must be at least three bytes long.
- Each developer tag cannot be longer than 25 bytes.
- The total length of all developer tags cannot exceed 240 bytes.
The following XML shows a sample developer tag as it would appear in an Upload API request. (You would need to replace the string TagName with the actual keyword or label you wanted to associate with the video.)
<media:category scheme="http://gdata.youtube.com/schemas/2007/developertags.cat">TagName </media:category>
In an API response, developer tags are specified in both <category> and <media:category> tags.
Note: Each developer tag that you assign will be associated with the developer key in your request. To search for videos matching that developer tag, your application would need to specify the same developer key in the search request.
Searching for videos that match a developer tag
To search for videos associated with a specific developer tag, send an API search request that specifies the developertags.cat category scheme and the developer tag that videos must match. Developer tag searches are not case-sensitive. The URLs below demonstrate how you would modify the standard API URL to match a developer tag. (You would need to replace the string TagName at the end of the URL with the name of your developer tag.)
Standard URL:
https://gdata.youtube.com/feeds/api/videos/
Retrieving videos associated with a developer tag:
https://gdata.youtube.com/feeds/api/videos/-/
%7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007
%2Fdevelopertags.cat%7DTagName
Note: When you search for videos that match a developer tag, your request must specify the same developer key that you used to assign that developer tag.
Browser-based uploading
Step 1 - Uploading video metadata
The example below shows the format of an API request that uses the OAuth 2.0 authentication scheme for browser-based uploading:
POST /action/GetUploadToken HTTP/1.1 Host: gdata.youtube.com Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY Content-Length: CONTENT_LENGTH Content-Type: application/atom+xml; charset=UTF-8 API_XML_request
Variables in the upload request
You must provide several values in the POST request. Those values are highlighted in bold text in the example above. The following list explains how to populate each value:
-
ACCESS_TOKEN - This value contains the authentication token for your request. The token will either be an OAuth 2.0 access token, an OAuth 1.0 access token, a ClientLogin token, an AuthSub single-use token, or an AuthSub session token.
-
DEVELOPER_KEY - This value uniquely identifies the application that is submitting the request to upload the video. Please visit http://code.google.com/apis/youtube/dashboard/ to get a developer key.
-
CONTENT_LENGTH - This value contains the length, in bytes, of the entire body of the POST request.
-
API_XML_Request - This value contains information about the uploaded video file in the form of an Atom XML entry. The example below shows a sample XML request. The XML tags used in the entry are defined in the Reference Guide.
The following example shows a POST request that has all of these values populated with the exception of the access (authentication) token:
POST /action/GetUploadToken HTTP/1.1 Host: gdata.youtube.com Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=adf15ee97731bca89da876c...a8dc Content-Length: 1941255 Content-Type: application/atom+xml; charset=UTF-8 <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007"> <media:group> <media:title type="plain">Bad Wedding Toast</media:title> <media:description type="plain"> I gave a bad toast at my friend's wedding. </media:description> <media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People </media:category> <media:keywords>toast, wedding</media:keywords> </media:group> </entry>
Step 2 - Extracting values from the API response
When you submit an Upload API request, the API returns an XML response that contains an upload URL and upload token that enable the user to upload the actual video file. You will need to extract the URL and token from the response and include these values in the form on your web page where the user submits the video file.
The example below shows a sample API response to a request for browser-based uploading:
<?xml version='1.0' encoding='UTF-8'?> <response> <url>http://uploads.gdata.youtube.com/action/FormDataUpload/AEF3087AUD<url> <token>AEwbFAQEvf3xox...</token> </response>
Step 3 - Uploading the video file
After extracting the upload URL and upload token from the API response, you need to display a form so that the user can upload the actual video file. The form must use the upload URL as the value of the <form> tag's action attribute and have a hidden input field containing the upload token. In addition, the form should verify that the user has selected a file to upload before allowing the user to actually submit the form.
The following JavaScript and HTML show a sample form as it might appear on your site. The JavaScript function, which executes when the user tries to submit the form, confirms that the user has selected a file to upload. If the user has not selected a file, then the function displays an error message below the file field.
<script type="text/javascript">
function checkForFile() {
if (document.getElementById('file').value) {
return true;
}
document.getElementById('errMsg').style.display = '';
return false;
}
</script>
<form action="URL?nexturl=http%3A%2F%2Fwww.example.com" method="post"
enctype="multipart/form-data" onsubmit="return checkForFile();">
<input id="file" type="file" name="file"/>
<div id="errMsg" style="display:none;color:red">
You need to specify a file.
</div>
<input type="hidden" name="token" value="TOKEN"/>
<input type="submit" value="go" />
</form>
Please note that the form must follow these guidelines:
-
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 when the user uploads his video file. After the video is uploaded in the browser, the user will be redirected to the nexturl URL. See the reference guide for more information about additional parameters that will be appended to the URL.
-
You must set the value of the <form> tag's enctype attribute to multipart/form-data.
-
The <input> tag that identifies the file must be named file.
-
The <input> tag that contains the token must be named token.
-
Your application should verify that the user has selected a file to upload before allowing the user to submit the form to upload the file.
Process Flow Diagram
The following diagram illustrates the browser-based uploading process. Your application might have already completed the authentication process before these steps occur. However, you could also choose to have the user provide the video metadata before completing the authentication process.

The image shows the following steps:
-
Your site displays a form in which the user will enter details about the video being uploaded.
-
The user enters the video details, such as the title, description and category for the video.
-
Your site sends a POST request to YouTube that contains the authentication token and the video details that the user submitted in the previous step. The Uploading video metadata section explains how to submit video details to YouTube.
-
YouTube returns a one-time upload token, an encrypted value containing authentication information and video details for the video being uploaded. The Extracting values from the API response section identifies the upload token and URL in the API response.
-
Your site displays a form where the user can select his video file and upload it to YouTube. The form will submit directly to YouTube and must contain a hidden input field that specifies the upload token obtained in the previous step. The Uploading the video file section defines the guidelines for this form.
-
The user selects his video and submits the form, sending his video and the upload token directly to YouTube. YouTube verifies the token is valid and adds the video to the user's YouTube channel. During this process, YouTube assigns the video a unique ID, which will be used to identify the video on YouTube.
-
YouTube redirects the user back to your site.
Direct uploading
Sending an Upload API Request
To upload a video, send a POST request containing the video and associated metadata to http://uploads.gdata.youtube.com/feeds/api/users/default/uploads. Your request will upload the video to the currently logged-in user's account. The authentication token that you upload with the request identifies that user.
The Upload API request must have the following format:
POST /feeds/api/users/default/uploads HTTP/1.1 Host: uploads.gdata.youtube.com Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY Slug: VIDEO_FILENAME Content-Type: multipart/related; boundary="BOUNDARY_STRING" Content-Length: CONTENT_LENGTH Connection: close --<boundary_string> Content-Type: application/atom+xml; charset=UTF-8 API_XML_request --BOUNDARY_STRING Content-Type: VIDEO_CONTENT_TYPE Content-Transfer-Encoding: binary <Binary File Data> --BOUNDARY_STRING--
Note: The hostname for uploading a video via the API, uploads.gdata.youtube.com, is different than the hostname used for all other API functions. However, you can use the same authentication token for uploading as for other API functions.
Variables in the upload request
You must provide several values in the POST request. Those values are highlighted in bold text in the example above. The following list explains how to populate each value:
-
YOUTUBE_USERNAME - Note that this variable is only relevant for requests that use ClientLogin authentication. This value contains the username for the user's YouTube account. The uploaded video will be associated with this account.
-
ACCESS_TOKEN - This value contains the authentication token for your request. The token will either be an OAuth 2.0 access token, an OAuth 1.0 access token, a ClientLogin token, an AuthSub single-use token, or an AuthSub session token.
-
DEVELOPER_KEY - This value uniquely identifies the application that is submitting the request to upload the video. Please visit http://code.google.com/apis/youtube/dashboard/ to get a developer key.
-
VIDEO_FILENAME - This value contains the name of the video file that the content creator is uploading.
-
BOUNDARY_STRING - This value contains a string of non-space characters. Typically, the string is a series of hyphens followed by a random set of alphanumeric characters. Note: This value appears multiple times in the POST request.
-
CONTENT_LENGTH - This value contains the length, in bytes, of the entire body of the POST request.
-
API_XML_Request - This value contains information about the uploaded video file in the form of an Atom XML entry. The example below shows a sample XML request. The XML tags used in the entry are defined in the Reference Guide.
-
VIDEO_CONTENT_TYPE - This value contains the MIME type of the uploaded video file. The MIME type can be a video media type, such as
video/mpegorvideo/mp4, or it can beapplication/octet-stream. -
Binary File Data - This value contains the binary code for the video file that is being uploaded.
The following example shows a POST request that has all of these values populated with the exception of the access (authentication) token and the binary file data:
POST /feeds/api/users/default/uploads HTTP/1.1 Host: uploads.gdata.youtube.com Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=adf15ee97731bca89da876c...a8dc Slug: video-test.mp4 Content-Type: multipart/related; boundary="f93dcbA3" Content-Length: 1941255 Connection: close --f93dcbA3 Content-Type: application/atom+xml; charset=UTF-8 <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007"> <media:group> <media:title type="plain">Bad Wedding Toast</media:title> <media:description type="plain"> I gave a bad toast at my friend's wedding. </media:description> <media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People </media:category> <media:keywords>toast, wedding</media:keywords> </media:group> </entry> --f93dcbA3 Content-Type: video/mp4 Content-Transfer-Encoding: binary <Binary File Data> --f93dcbA3--
Handling the Upload API Response
When you submit an Upload API request, the API returns an Atom entry that contains information about the uploaded video. The entry has the same format as an entry that would appear in a user's uploaded videos feed. The response may contain properly escaped HTML tags.
The entry will contain one <link> tag for which the value of the rel attribute is self. To check the status of the uploaded video, send a GET request to the URL identified in this <link> tag. See the following section, Checking the status of an uploaded video, for more information.
Process Flow Diagram
The following diagram illustrates the direct uploading process. Your application might have already completed the authentication process before these steps occur. However, you could also choose to have the user provide the video metadata before completing the authentication process.

The image shows the following steps:
-
Your site displays a form in which the user will enter details about the video being uploaded and select the actual video file to upload.
-
The user selects the video file and enters the video details, such as the title, description and category for the video.
-
Your site sends a POST request to YouTube that contains the authentication token as well as the video file and the video details that the user submitted in the previous step.
-
YouTube returns an API response describing the new video.
-
You display a confirmation to the user that the video was uploaded successfully.
Resumable uploads
This section explains how to upload videos using YouTube's direct, resumable uploading process. Direct uploading lets you add videos to YouTube from your video library. In addition, resumable uploads can be restarted from the point of interruption if the connection between your application and YouTube is lost at any point during the uploading process.
You should choose a direct-upload implementation if either of the following conditions is true:
- You have a collection of videos that want to upload to YouTube.
- You want to host or store videos uploaded through your site and also add those videos to YouTube.
- You want to upload videos from a device with a low-bandwidth or unstable Internet connection, such as a mobile device.
If you implement direct uploading for a website, then when a user uploads a video to 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.
This page contains the following sections:
Step 1 - Uploading video metadata
To begin a resumable upload, send a POST request that contains the video filename and the metadata for the video to the following URL. The authentication token that you submit with the request needs to identify the currently logged-in user. Note that this URL is almost the same one that you would use for non-resumable direct uploading, with the difference being the addition of the resumable path prefix in the URL.
http://uploads.gdata.youtube.com/resumable/feeds/api/users/default/uploads
The example below shows the format of an API request that uses the OAuth 2.0 authentication scheme for resumable uploading:
POST /resumable/feeds/api/users/default/uploads HTTP/1.1 Host: uploads.gdata.youtube.com Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY Content-Length: CONTENT_LENGTH Content-Type: application/atom+xml; charset=UTF-8 Slug: VIDEO_FILENAME API_XML_request
Variables in the upload request
You must provide several values in the POST request. Those values are highlighted in bold text in the example above. The following list explains how to populate each value:
-
ACCESS_TOKEN - This value contains the authentication token for your request. The token will either be an OAuth 2.0 access token, an OAuth 1.0 access token, a ClientLogin token, an AuthSub single-use token, or an AuthSub session token.
-
DEVELOPER_KEY - This value uniquely identifies the application that is submitting the request to upload the video. Please visit http://code.google.com/apis/youtube/dashboard/ to get a developer key.
-
CONTENT_LENGTH - This value contains the length, in bytes, of the entire body of the POST request.
-
VIDEO_FILENAME - This value contains the file name of the source video that you are uploading.
-
API_XML_Request - This value contains information about the uploaded video file in the form of an Atom XML entry. The example below shows a sample XML request. The XML tags used in the entry are defined in the Reference Guide.
The following example shows a POST request that has all of these values populated with the exception of the access (authentication) token:
POST /resumable/feeds/api/users/default/uploads HTTP/1.1 Host: uploads.gdata.youtube.com Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=adf15ee97731bca89da876c...a8dc Content-Length: 1941255 Slug: my_file.mp4 Content-Type: application/atom+xml; charset=UTF-8 <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007"> <media:group> <media:title type="plain">Bad Wedding Toast</media:title> <media:description type="plain"> I gave a bad toast at my friend's wedding. </media:description> <media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People </media:category> <media:keywords>toast, wedding</media:keywords> </media:group> </entry>
Uploading a video without metadata
When using the resumable uploading process, you can upload a video without specifying any metadata at all. In such cases, YouTube will handle the request as if it contained an entry that only included a <yt:incomplete> element. YouTube would then generate certain metadata values for the video as discussed in the metadata requirements for uploaded videos.
A resumable upload request that does not specify any metadata differs from the sample resumable upload request shown above in three ways:
- The
Content-LengthHTTP request header value must be0. - The
Content-TypeHTTP request header must be omitted from the request. - The Atom XML entry is omitted from the request.
The example below shows an API request to upload a video without metadata using the resumable uploading process:
POST /resumable/feeds/api/users/default/uploads HTTP/1.1 Host: uploads.gdata.youtube.com Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=adf15ee97731bca89da876c...a8dc Content-Length: 0 Slug: my_file.mp4
Step 2 - Extracting the upload URL from the API response
When you submit an API request to upload video metadata, the API response will contain a Location header, which identifies the URL that you will use to upload the actual video file. You need to extract this URL and use it to upload the video file.
The example below shows a sample API response to a request to upload video metadata for a resumable upload:
HTTP/1.1 200 OK Location: http://uploads.gdata.youtube.com/resumableupload/AF8GKF...0Glpk0Aw Date: Fri, 04 Dec 2009 16:14:30 GMT Pragma: no-cache Expires: Fri, 01 Jan 1990 00:00:00 GMT Cache-Control: no-cache, no-store, must-revalidate Content-Length: 0 Content-Type: text/html
Step 3 - Uploading the video file
After extracting the upload URL from the API response, you need to upload the actual video file content. You will upload the video content to the URL extracted in step 2. The example below demonstrates the format of the video upload request. Note that you do not need to provide any authentication headers in this step.
PUT <upload_url> HTTP/1.1 Host: uploads.gdata.youtube.com Content-Type: <video_content_type> Content-Length: <content_length> <Binary_file_data>
Variables in the upload request
You must provide several values in the PUT request. Those values are highlighted in bold text in the example above. The following list explains how to populate each value:
-
upload_url – This value is the URL that you extracted in step 2 from the
Locationheader of the API response for the metadata upload request. -
video_content_type – This value specifies the MIME type of the uploaded video file. The MIME type can be a video media type, such as
video/mpegorvideo/mp4, or it can beapplication/octet-stream. -
content_length – This value specifies the length, in bytes, of the entire body of the PUT request.
-
Binary File Data – This value contains the binary code for the video file that you are uploading.
The following example shows a PUT request that has all of these values populated with the exception of the binary file data:
PUT /resumableupload/AF8GKF...0Glpk0Aw HTTP/1.1 Host: uploads.gdata.youtube.com Content-Type: video/mpeg Content-Length: 124905 <Binary File Data>
Step 4 - Completing the upload process
When you submit a request to upload the video content for a resumable upload, one of two scenarios could occur:
-
If the upload completes, then the API returns a response indicating whether the upload succeeded or failed.
-
For a successful upload, the API returns an Atom entry that contains information about the uploaded video. The entry has the same format as an entry in a user's uploaded videos feed, and the response may contain properly escaped HTML tags. The Checking the status of an uploaded video section explains how to check the status of the uploaded video.
-
For an unsuccessful upload, the response contains an error response that helps to explain the cause of the upload failure.
-
-
If the upload fails because the connection between the YouTube server and your application is lost, then your application will not receive an API response. In this case, you may be able to resume the upload from the point of the interruption. The following steps explain how to resume a video upload:
Checking the status of a resumable upload
To query the status of an interrupted resumable upload, send a PUT request to the upload URL that you retrieved in step 2 and also used in step 3. In your request, you need to set the
Content-Rangeheader value tobytes */*as shown in the following example:PUT <upload_url> HTTP/1.1 Host: uploads.gdata.youtube.com Content-Range: bytes */*If the upload URL refers to an upload that completed, regardless of whether the upload succeeded or failed, the API will return the same response that it sent when the upload originally completed. As discussed above, if the upload succeeded, the response will contain an Atom entry. If the upload failed, the response will contain the original error response.
However, if the upload was interrupted by a lost connection, the API will return a 308 HTTP response code (Resume Incomplete). The sample response below shows the format of an API response for an upload that can still be completed:
308 Resume Incomplete content-length: 0 expires: Fri, 01 Jan 1990 00:00:00 GMT range: bytes=0-408 pragma: no-cache cache-control: no-cache, no-store, must-revalidate date: Fri, 04 Dec 2009 13:45:41 GMT content-type: text/html
In the response, the
rangeheader indicates how many bytes from the video file have already been successfully uploaded to YouTube. The bytes are indexed from 0. Thus, the sample response above indicates that the first 409 bytes of the file were received. If nothing has been uploaded yet, therangeheader will be absent from the response.Note: The API response for an upload that can still be completed may use the
Locationheader to specify a new unique upload URI that your application should use to complete the upload. Your client should check the API response for an updated location and, if one is present, use it to upload the remaining data.Resuming an upload
To resume the upload, you will send a new PUT request to the upload URL captured in step 2. The resumed upload request has the following format:
PUT <upload_url> HTTP/1.1 Host: uploads.gdata.youtube.com Content-Type: <video_content_type> Content-Length: <content_length> Content-Range: bytes <first_byte>-<last_byte>/<total_content_length> <Partial Binary File Data>
Variables in the resumed upload request
You must provide several values in the PUT request. Those values are highlighted in bold text in the example above. The following list explains how to populate each value:
-
upload_url – This value is the upload URL that you extracted in step 2.
-
video_content_type – This value specifies the MIME type of the uploaded video file. The MIME type can be a video media type, such as
video/mpegorvideo/mp4, or it can beapplication/octet-stream. -
content_length – This value specifies the length, in bytes, of the entire body of the PUT request. If you are uploading the remainder of a video file, you can calculate this value by subtracting the
first_bytefrom thetotal_content_length. (Both of these values are defined below.) -
The
Content-Rangeheader specifies the part of the video file that you are uploading. The header specifies three values:-
The first_byte specifies the 0-based numeric index of the byte number from which you are resuming the upload. This value will be one number higher than the second number in the
rangeheader retrieved in the previous step. In the previous example, therangeheader value was0-408. The first byte in a subsequent resumed upload would be409. -
The last_byte specifies the 0-based numeric index of the last byte included in the binary file that you are uploading. Typically, this will be the last byte in the file. In step 3, the
Content-Lengthheader value was124905. Thus, the last byte in the file would be number124904. -
The total_content_length specifies the total size of the video file in bytes. This value is the same as the
Content-Lengthsubmitted in the original upload request.
-
-
Binary File Data – This value contains the binary code for the portion of the video file that you are uploading.
The example below shows a sample request to resume an upload:
PUT /resumableupload/AF8GKF...0Glpk0Aw HTTP/1.1 Host: uploads.gdata.youtube.com Content-Type: video/mpeg Content-Length: 124496 Content-Range: bytes 409-124904/124905 Partial Binary File Data
Note: You cannot upload a noncontinuous block of the binary file. If you try to upload a noncontinuous block, none of the remaining binary content will be uploaded. As such, the first byte in the upload request must be the next byte after the last byte successfully uploaded to YouTube as identified in the
rangeheader of the 308 HTTP response. Thus, if the last byte in therangeheader is408, the first byte in the request to resume the upload must be byte 409 (using a 0-based index). If you try to resume the upload from byte 408 or lower (overlapping bytes) or byte 410 or higher (skipping bytes), none of the binary content will be uploaded. -
Checking the status of an uploaded video
An uploaded video will immediately be visible in an authenticated user's uploaded videos feed. However, the video will not be visible on YouTube until it has been processed and indexed. The length of time between when the video is uploaded and when the video is publicly visible on YouTube varies. However, videos are usually indexed within one day and may be indexed in several hours or even less than an hour.
The following list explains two ways to check the status of an uploaded video:
-
You can check the status of a user's unpublished videos by retrieving the user's uploaded videos feed. Entries in that feed that have not been published will contain the <app:control> tag. Please note that unpublished videos include videos that are still being processed, that failed to upload or that were rejected after being uploaded.
-
If you upload a video using the direct upload method, then the Upload API response will contain a <link> tag for which the value of the rel attribute is self. To check the status of the uploaded video, send a GET request to the URL identified in this <link> tag.
<link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/users/default/uploads/Video_ID'/>
When you check the status of an uploaded video, the status information will be contained in the <app:control> tag and its subtags, <app:draft> and <yt:state>. The following XML excerpt shows how these tags appear in an entry in an API response:
<entry gd:etag='W/"Ak4ER347eCp7ImA9WxRRF0k."'> <id>tag:youtube,2008:video:b5bbb2beb5a7d9ca</id> <app:control> <app:draft>yes</app:draft> <yt:state name='rejected' reasonCode='tooLong' helpUrl='http://www.youtube.com/t/community_guidelines'> Video is too long. </yt:state> </app:control> <yt:private/> </entry>
Note: We recommend that you check the value of the <yt:state> tag and communicate to video owners whether an unpublished video is still being processed or if an error caused the upload to fail or be rejected. The Java, .NET, PHP and Python developer's guides all provide some sample code for checking the values of these tags.
Updating and deleting videos
Updating a video entry
To update a video, retrieve the video entry from the video owner's uploaded videos feed and send a PUT request to the entry's edit URL:
<link rel='edit' type='application/atom+xml'
href='https://gdata.youtube.com/feeds/api/users/default/uploads/VIDEO_ID'>
The body of the PUT request is an Atom XML entry that contains information about the video. You can include any of the following elements and their subtags in your request. Required elements are marked with an asterisk (*).
- media:title*
- media:description*
- media:category*
- media:keywords*
- yt:accessControl
- yt:location
- yt:private
- georss:where
Note that excluding an element will delete the information that already exists for that video. For example, if a video is marked as private and your request does not include the <yt:private> tag, the video will become public. Similarly, if you do not specify access control settings when updating a video, YouTube will restore the default access control settings for that video. If you only specify some access control settings in an update, the unspecified controls will be restored to their default settings.
The following XML shows a sample request to update a video:
PUT /feeds/api/users/default/uploads/VIDEO_ID HTTP/1.1 Host: gdata.youtube.com Content-Type: application/atom+xml Content-Length: CONTENT_LENGTH Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY <?xml version="1.0"?> <entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007"> <media:group> <media:title type="plain">Yippee Skippy</media:title> <media:description type="plain">I am updating this video.</media:description> <media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People</media:category> <media:keywords>blastoff,rodeo,whiteboards</media:keywords> </media:group> <yt:accessControl action="comment" permission="allowed"/> <yt:accessControl action="commentVote" permission="allowed"/> <yt:accessControl action="videoRespond" permission="allowed"/> <yt:accessControl action="rate" permission="allowed"/> <yt:accessControl action="list" permission="allowed"/> <yt:accessControl action="embed" permission="allowed"/> <yt:accessControl action="syndicate" permission="allowed"/> </entry>
Note: You can also submit a partial update using a PATCH request to only update specific metadata fields for an entry.
Updating a video with incomplete metadata
If a video entry contains a <yt:incomplete> element, you must remove that element before updating the entry. The element's presence indicates that when the video was uploaded, it was flagged as having incomplete metadata. Consequently, YouTube may have automatically generated some of the video's metadata values, such as its title, category, or keywords.
A video that was uploaded with incomplete metadata will not be included in YouTube's search index and, therefore, will not appear in search results. After the video's metadata has been updated, and the <yt:incomplete> element has been removed, the video will subsequently be eligible to be included in YouTube's search index.
Deleting a video
To delete a video, send a DELETE request to the edit URL for that video as shown in the following example:
DELETE /feeds/api/users/default/uploads/VIDEO_ID HTTP/1.1 Host: gdata.youtube.com Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY
Deleted videos are typically removed from a user's public uploaded videos feed within a couple of hours.
Providing captions for a video
Adding captions to your video files can help users to locate and understand your videos. You can add captions to a video via the API by creating a caption track and uploading it. YouTube supports a variety of caption file formats, including plain text transcripts.
YouTube may also use automatic speech recognition (ASR) to generate a caption track for a video.
This section discusses the caption file formats that YouTube supports. It also explains how to use the API to create, retrieve, update and delete caption files. These issues are explained in the following subsections:
- Requirements for caption operations
- Supported formats for caption files
- Retrieving a list of available caption tracks
- Creating a caption track
- Retrieving a caption track
- Updating a caption track
- Deleting a caption track
Requirements for caption operations
Please note the following requirements for executing caption-related API operations:
-
Captions are only available for API version 2.
-
Captions for a video can only be created, retrieved, modified and deleted by the owner of that video. To perform these operations for a video, you must submit authenticated API requests for which the video's owner is the logged-in user. Accordingly, API requests for caption operations must contain a properly formatted Authorization header.
-
Requests to create (POST), update (PUT) or delete (DELETE) captions must identify your developer key using either the X-GData-Key request header or the key request parameter.
Supported formats for caption files
YouTube supports many different formats for caption files, including RealText (.rt), SAMI (.smi) and Media RSS. If you already have captions available, we recommend that you upload them in their original format, whatever that may be. If you do not have formatted caption data, such as a transcript that does not have timing data, we recommend using SubRip (*.SRT) or SubViewer (*.SUB) for generating formatted captions.
YouTube also supports a simple format that is compatible with both the SubRip and SubViewer formats. In this simple format, each caption is divided into three segments that appear in the following order:
-
Timecodes specify the time and duration that YouTube should display a caption in HH:MM:SS.FS format. Timecodes, which are measured from the beginning of the video, contain the following units
- HH – Hours (00, 01, etc.)
- MM – Minutes (00-59)
- SS – Seconds (00-59)
- FS – Fractional seconds (.000-.999)
YouTube supports the following time constructs:
- HH:MM:SS.FS,HH:MM:SS.FS – A caption appears at the first time offset and stops displaying at the second time offset. This format is compatible with the SubViewer format.
- HH:MM:SS.FS --> HH:MM:SS.FS – A caption appears at the first time offset and stops displaying at the second time offset. To make this format completely compatible with the SubRip format, you can insert a "subtitle number" before the timecodes.
- HH:MM:SS.FS – A caption appears at the designated time offset. Since no stop time is specified, YouTube will try to determine an appropriate stop time. For example, the caption might stop displaying just before the next caption is scheduled to appear.
-
The caption text consists of one or more lines of text that will be displayed on the screen during the time offsets. You must use UTF-8 encoding for the caption text.
-
A blank line marks the end of each caption.
The following example demonstrates this simple caption format:
0:01:23.000,0:01:25.000 This text displays for two seconds starting 1 minute and 23 seconds into the video. 0:02:20.250,0:02:23.8 This text displays from 2 minutes and 20.25 seconds after the start of the video until 2 minutes and 23.8 seconds after the start of the video. 0:03:14.159 This text displays beginning 3 minutes and 14.159 seconds after the start of the video for an undefined length of time.
Retrieving a list of available caption tracks
Each video entry contains a <link> tag for which the rel attribute value is http://gdata.youtube.com/schemas/2007#video.captionTracks. (Note that this link is only visible to the owner of a video.) The tag's href attribute identifies the captions URL for the video.
<link rel="http://gdata.youtube.com/schemas/2007#video.captionTracks"
type="application/atom+xml"
href="https://gdata.youtube.com/feeds/api/videos/ZTUVgYoeN_b/captions"
yt:hasEntries="true|false"/>
Caption tracks are available for a video if the <link> tag's yt:hasEntries attribute has a value of true. If caption tracks are available for the video, you can retrieve the list of tracks by sending a GET request to the URL in the link tag. You can use any of the following input parameters in a request to retrieve caption tracks:
- lr – This parameter filters the list of caption tracks by language. For example, if you include lr=de in your request, the API response will only list caption tracks in the German language. The parameter value must be an ISO 639-1 two-letter language code. By default, the API response will include tracks for all languages.
- max-results – This parameter specifies the maximum number of caption tracks to include in the results set.
- start-index – This parameter specifies the index of the first caption track that should be included in the result set. The parameter uses a one-based index, meaning the first track is 1, the second track is 2 and so forth.
Sample caption tracks feed
The following sample API response shows a caption tracks feed with two entries. The first entry contains a <yt:derived> tag that indicates that the track was generated using automatic speech recognition.
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:app='http://www.w3.org/2007/app' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:yt='http://gdata.youtube.com/schemas/2007' gd:etag='W/"DkcNRH4zfSp7ImA9WxJXEUk."'> <id>tag:youtube.com,2008:videos:EdDc7sWjCL4:captions</id> <updated>2010-08-18T22:42:42.179Z</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#captionTrack'/> <title> Caption Tracks for Learn about HTML5 and the Future of the Web </title> <logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo> <link rel='related' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4?v=2'/> <link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captions?v=2'/> <link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captions/batch?v=2'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captions?...'/> <link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captions?v=2'/> <link rel='service' type='application/atomsvc+xml' href='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captions?alt=...'/> <author> <name>GoogleDevelopers</name> <uri>https://gdata.youtube.com/feeds/api/users/googledevelopers</uri> </author> <generator version='2.0' uri='http://gdata.youtube.com/'>YouTube data API</generator> <openSearch:totalResults>1</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>25</openSearch:itemsPerPage> <entry gd:etag='W/"DkECQHk5cSp7ImA9WxJSGEw."'> <id>tag:youtube.com,2008:captions:ChkLEO3ZhwUaEAi-kYyt7J236BESAmVuGgAM</id> <published>2010-06-09T06:31:35.256-07:00</published> <updated>2010-06-09T06:31:35.256-07:00</updated> <app:edited>2010-06-09T06:31:35.256-07:00</app:edited> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#captionTrack'/> <title/> <content type='application/vnd.youtube.timedtext' src='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captiondata/ChkLEO...' xml:lang='en'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captions/ChkLEO...'/> <link rel='edit' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captions/ChkLEO...'/> <link rel='edit-media' type='application/vnd.youtube.timedtext' href='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captiondata/ChkLEO...'/> <yt:derived>speechRecognition</yt:derived> </entry> <entry gd:etag='W/"DkECQHk5cSp7ImA9WxJSGEw."'> <id>tag:youtube.com,2008:captions:CiMLEO3ZhwUaGgi-kYyt7J236B...</id> <published>2010-06-20T23:46:22.156-07:00</published> <updated>2010-06-20T23:46:22.156-07:00</updated> <app:edited>2010-06-20T23:46:22.156-07:00</app:edited> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#captionTrack'/> <title>auto-timed</title> <content type='application/vnd.youtube.timedtext' src='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captiondata/CiMLEO...' xml:lang='en'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captions/CiMLEO...'/> <link rel='edit' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captions/CiMLEO...'/> <link rel='edit-media' type='application/vnd.youtube.timedtext' href='https://gdata.youtube.com/feeds/api/videos/EdDc7sWjCL4/captiondata/CiMLEO...'/> </entry> </feed>
Creating a caption track
To create a caption track, post a caption file or transcript to the http://schemas.google.com/g/2005#post link for the captions track feed. The following guidelines explain how to format your API request:
-
You must set the Content-Type header value to the following value:
application/vnd.youtube.timedtext
-
You should use the Content-Language header to specify the language of the caption track. If you do not specify a language, the API server will attempt to identify the language. However, if the identification fails, then your API request will also fail.
If you do specify the caption track language, then you must also specify the character set used so that YouTube can decode the file. We recommend that you use UTF-8 encoding whenever possible. To specify the character set, add the charset parameter to the Content-Type header value as shown below:
application/vnd.youtube.timedtext; charset=UTF-8
-
You can use the Slug header to specify a title for the caption track. The header value should be URL-escaped. In addition, to specify non-ASCII characters in a track title, you need to ensure that the title is a UTF-8 string and then URL-escape it. For example, the string
El mejor día(the best day) would be specified in a Slug header asEl%20mejor%20d%C3%ADa. -
The caption file must be 1MB or smaller.
The following sample API request demonstrates how to create a caption track:
POST /feeds/api/videos/VIDEO_ID/captions HTTP/1.1 Host: gdata.youtube.com Content-Type: application/vnd.youtube.timedtext; charset=UTF-8 Content-Language: en Slug: Title of caption track Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY <Caption File Data>
Uploading a video transcript without caption timecodes
If YouTube's Text-to-Speech (TTS) server does not recognize your caption file format, YouTube will try to automatically sync the caption track to the audio track in your video. This functionality enables you to upload a video transcript without any caption timecodes at all and have YouTube generate a caption track from the transcript. The transcript does not have to be formatted in any particular way and could just be paragraphs of text.
Sample API response for uploaded caption track
If YouTube successfully handles your request, the API will return a 201 HTTP response code. The Location header in the API response will contain the self link of the caption track entry, which can be used for later retrieval of the entry. The body of the XML response will be the caption track entry.
The XML below shows a successful response to a request to create a caption track:
HTTP 201 Content-Type: application/atom+xml; charset=UTF-8; type=entry Location: https://gdata.youtube.com/feeds/api/captions/VIDEO_ID/captions/caption_track_id <entry xmlns='http://www.w3.org/2005/Atom' xmlns:app='http://www.w3.org/2007/app' xmlns:gd='http://schemas.google.com/g/2005' xmlns:xml='http://www.w3.org/XML/1998/namespace' gd:etag='W/"DEMCSXc7fip7ImA9WxJXEk4."'> <id>tag:youtube.com,2008:captions:CiULE...</id> <published>2009-06-05T14:14:28.906-07:00</published> <updated>2009-06-05T14:14:28.906-07:00</updated> <app:edited>2009-06-05T14:14:28.906-07:00</app:edited> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#captionTrack'/> <title>API captions</title> <content type='application/vnd.youtube.timedtext' src='https://gdata.youtube.com/feeds/api/videos/PjLv88-zqkI/captiondata/CiULE...' xml:lang='en'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/PjLv88-zqkI/captions/CiULE...'/> <link rel='edit' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/PjLv88-zqkI/captions/CiULE...'/> <link rel='edit-media' type='application/vnd.youtube.timedtext' href='https://gdata.youtube.com/feeds/api/videos/PjLv88-zqkI/captiondata/CiULE...'/> </entry>
If your request is properly formatted, but YouTube cannot process the captions file you are sending, YouTube will still create an <entry> in the captions feed for the new caption track. The entry will contain an <app:control> tag, which indicates that YouTube did not successfully handle the captions file. That tag, in turn, will contain a <yt:state> tag that contains more information about the failure and an <app:draft> tag that contains a value of yes, which indicates that the track is not publicly visible.
<app:control> <app:draft>yes</app:draft> <yt:state name="failed" reasonCode="invalidFormat"/> </app:control>
Retrieving a caption track
Caption tracks are served automatically to the YouTube video players, which means that anyone watching a video can opt to view any caption track for that video. However, you can still retrieve a caption track if you want to modify the caption data or the timecodes that specify when the captions display.
To retrieve a caption track, send a GET request to the src URL specified in the <content> tag of the caption track entry:
<content type="text/xml" xml:lang="zh-HK" src="https://gdata.youtube.com/api/captiondata/caption-id"/>
The request below demonstrates how to retrieve a caption track:
GET /feeds/api/videos/VIDEO_ID/captiondata/TRACK_ID HTTP/1.1 Host: gdata.youtube.com Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY
Note that the API does not return an Atom feed in response to a request for a caption track. Instead, the response contains your caption track in the same format that you uploaded it to YouTube. See the Supported formats for caption files section for details about valid caption file formats or the instructions for retrieving a caption track in an alternate format.
In addition, the following rules apply to generated caption tracks:
-
If you are retrieving a track that YouTube generated using automatic speech recognition (ASR), then you can also use the
fmtparameter to specify that the track should be returned in Subviewer-compatible (sbv) or Subrip-compatible (srt) format. (In a caption tracks feed, the <yt:derived> tag indicates whether a track was generated using ASR.) If you do not specify a format when retrieving an ASR track, the API server will automatically return the track in Subviewer-compatible format. -
If you are retrieving a track that YouTube automatically synchronized to your video, you can use the
fmtparameter to specify the format in which which the track should be returned. If you do not specify afmtparameter value, then the API will return the original transcript that you uploaded. Thus, you must specify afmtparameter value to retrieve the track's timecodes.
The API supports two other options for retrieving caption tracks:
Note: YouTube does not save translated or reformatted caption tracks that you request through the API, and those tracks will not appear in the list of caption tracks available for a video. You can upload a translated or reformatted track, however, to make it available to viewers.
Retrieving a translation of a caption track
To retrieve a translation of a caption track, append the lang parameter to the src URL specified in the <content> tag of the caption track entry. Set the parameter value to the ISO 639-1 two-letter language code that identifies the desired caption language.
The request below demonstrates how to retrieve a translated caption track:
GET /feeds/api/videos/VIDEO_ID/captiondata/TRACK_ID?lang=ISO_639_CODE HTTP/1.1 Host: gdata.youtube.com Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY
If your request is successful, the response will contain the translated caption track in the same format that you uploaded the original track to YouTube. If a translation cannot be generated, or if the language code that you specified is not a valid value, the API will return an HTTP 400 response code.
Retrieving a caption track in an alternate format
To retrieve a caption track in a different format than the one you originally uploaded, append the fmt parameter to the src URL specified in the <content> tag of the caption track entry. Set the parameter value to one of the following values:
sbv– Subviewer-compatiblesrt– Subrip-compatible
The request below demonstrates how to retrieve a caption track in an alternate format:
GET /feeds/api/videos/VIDEO_ID/captiondata/TRACK_ID?fmt=TARGET_FORMAT HTTP/1.1 Host: gdata.youtube.com Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY
You can specify a target language and a target format by specifying values for both the lang and fmt parameters.
If YouTube cannot convert the original caption track to the requested format, the API will return an HTTP 400 response code.
Updating a caption track
The API enables you to update the captions and timecodes for a caption track. However, you cannot update metadata about the track. So, for example, you cannot update the title or language of a caption track. If the title and/or language of a caption track is incorrect, you need to delete the track with the incorrect information and create a new track with the corrected title and language.
To update a caption track, send a PUT request to the edit-media link in the caption track entry:
<link rel="edit-media" type="application/atml+xml" href="https:/gdata.youtube.com/feeds/api/videos/VIDEO_ID/captiondata/CAPTION_ID" />
Your API request must set the Content-Type header value as described in the Creating a caption track section. In addition, your caption file must be 1MB or smaller. The request below demonstrates how to update a caption track:
PUT /feeds/api/videos/VIDEO_ID/captiondata/CAPTION_TRACK_ID HTTP/1.1 Host: gdata.youtube.com Content-Type: application/vnd.youtube.timedtext; charset=UTF-8 Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY <Binary Caption File Data>
The updated caption track must be in a supported format for caption files.
Deleting a caption track
To delete a caption track, send a DELETE request to the edit link in the caption track entry. The following sample API request demonstrates how to delete a caption track:
DELETE /feeds/api/videos/VIDEO_ID/captions/CAPTION_TRACK_ID HTTP/1.1 Host: gdata.youtube.com Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY
Live events
Important: This is an experimental feature, which means that it might change unexpectedly.
A live-streaming event is an event that is broadcast on YouTube as it occurs. The API uses the following feeds and entries to return information about live-streaming events:
-
An event feed contains a list of live-streaming events created by a specific user. An event feed comprises a series of event entries.
-
An event entry contains metadata about a single live-streaming event, such as the event's name, description, start time, and status. An event entry is currently associated with a single live video entry; however, a single event may eventually be associated with multiple live video entries.
-
A live video entry contains information about a live video stream of an event. A live video entry is an extension of the video entry, which is used in other types of video feeds, including search feeds, uploads, and so forth. A live video entry may also contain additional tags that would be used to convey information about a live video stream but that would not be relevant to other videos, such as information about the content delivery network used to stream the content.
If a video entry refers to a live video, the entry will contain a
<category>tag with aschemeattribute value ofhttp://schemas.google.com/g/2005#kindand atermattribute value ofhttp://gdata.youtube.com/schemas/2007#liveVideo.
Retrieving live events
The following sections explain different options for retrieving live-streaming events:
- Live event charts
- Retrieving a user's events feed
- Special query parameters for retrieving live events
- Retrieving a single live event
Live event charts
You can retrieve several different standard feeds, or charts, listing live events on YouTube.
To retrieve a live event chart, send a GET request to the URL associated with that chart. Note that you must be using version 2 of the YouTube API to retrieve any of these charts. You can specify the API version using either the v parameter or the GData-Version HTTP request header.
The following table describes the charts that you can retrieve and identifies the URL associated with each chart:
| Chart name | Feed ID | URL and Description |
|---|---|---|
| Featured live events | featured | URL: https://gdata.youtube.com/feeds/api/charts/live/events/featured Description: This feed lists promoted live events that are currently happening or will soon take place. |
| Current live events | live_now | URL: https://gdata.youtube.com/feeds/api/charts/live/events/live_now Description: This feed lists live events that are currently active. |
| Upcoming live events | upcoming | URL: https://gdata.youtube.com/feeds/api/charts/live/events/upcoming Description: This feed lists events that will take place within the time frame specified for the time parameter. Valid parameter values are today (one day), this_week (seven days), this_month (one month), and all_time, and all_time is the default value. |
| Recently broadcast | recently_broadcasted | URL: https://gdata.youtube.com/feeds/api/charts/live/events/recently_broadcasted Description: This feed lists events that recently ended. |
API requests to retrieve live event charts can specify any of the following parameters:
- The
regionparameter filters a chart to only include live events that are featured within the specified region.
Retrieving a user's events feed
This section explains how to retrieve a feed listing a specific user's live-streaming events. Note that YouTube has not enabled all user accounts to create and stream live events. If a user has not created any live-streaming events or is not allowed to create live-streaming events, that user's events feed will not contain any entries.
-
To request a feed of the currently logged-in user's live-streaming events, send an HTTP GET request to the following URL. Note: For this request, you must provide an authentication token in the Authorization HTTP request header. The authentication token enables YouTube to identify the user.
https://gdata.youtube.com/feeds/api/users/default/live/events?v=2
-
To request a feed of another user's live-streaming events, send an HTTP GET request to the following URL. Note that this request does not require authentication.
https://gdata.youtube.com/feeds/api/users/
userId/live/events?v=2In the URL above, you should replace the text
userIdwith the user's YouTube user ID. For backward compatibility purposes, the API also supports having the user's YouTube username specified instead.
Determining whether a user can create live events
If a user can create live events, then the user's profile entry will contain a <gd:feedLink> that points to the user's events feed. The tag will have the following attributes:
- The
relattribute value will behttp://gdata.youtube.com/schemas/2007#user.live. - The
hrefattribute value will specify the URL of the user's events feed. - The
countHintattribute value will specify the number of events in the feed.
The XML below shows a sample <gd:feedLink> tag:
<gd:feedLink rel='http://gdata.youtube.com/schemas/2007#user.live'
href='https://gdata.youtube.com/feeds/api/users/userId/live/events?v=2'
countHint='11'/>
Special query parameters for retrieving live events
YouTube supports the following API query parameters specifically for requests to retrieve live event feeds:
status– The API response will only include events that are eitherpending(not yet started),active(in progress),completed,cancelled, orrejected.starts-before– The API response will only include events that started before (or will start before) the given date and time.starts-after– The API response will only include events that started after (or will start after) the given date and time.ends-before– The API response will only include events that ended before (or will end before) the given date and time.ends-after– The API response will only include events that ended after (or will end after) the given date and time.
In addition, you can use the inline parameter to indicate that each entry in a live events feed should, in turn, contain an entry that points to the actual video content associated with the event. For example, the live event entry could contain a video entry if there is a single video stream associated with the event, or it could contain a playlist entry if there are multiple videos associated with the event.
-
If you set the
inlineparameter totrue, the<content>tag in each event feed entry will encapsulate a video or playlist entry containing details about the video(s) associated with the event. -
If you do not set the
inlineparameter or you set the parameter's value tofalse, the<content>tag in each event feed entry will contain asrcattribute that points to the URL you would use to retrieve information about the video.If you do set the
inlineparameter totrue, you may find it helpful to use the partial response feature to limit the size of the API response.
Sample live events feed
The following API request retrieves the live events for the YouTube user ytatestuser. Since the inline parameter is set to true, each entry's <content> tag will encapsulate the video entry associated with the event.
https://gdata.youtube.com/feeds/api/users/ytatestuser/live/events?v=2&inline=true
The following XML shows the API response for this request. The feed contains a series of <entry> tags, with each entry describing a live event. Each entry contains the title, description, author, date, and status of an event, among other fields. (Note that only the first entry is displayed below.)
<?xml version='1.0' encoding='UTF-8'?> <feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/"CEMDSHwyeCp7ImA9WhZWF0s."'> <id>tag:youtube.com,2008:user:ytatestuser:live:events</id> <updated>2011-05-18T23:47:59.290Z</updated> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#liveEvent'/> <logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo> <link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/users/ytatestuser/live/events'/> <link rel='http://schemas.google.com/g/2005#post' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/users/ytatestuser/live/events'/> <link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/users/ytatestuser/live/events/batch'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/users/ytatestuser/live/events?start-index=1&max-results=25'/> <link rel='service' type='application/atomsvc+xml' href='https://gdata.youtube.com/feeds/api/users/ytatestuser/live/events?alt=atom-service'/> <author> <name>YouTube</name> <uri>http://www.youtube.com/</uri> </author> <generator version='2.0' uri='http://gdata.youtube.com/'>YouTube data API</generator> <openSearch:totalResults>4</openSearch:totalResults> <openSearch:startIndex>1</openSearch:startIndex> <openSearch:itemsPerPage>25</openSearch:itemsPerPage> <entry gd:etag='W/"C08MR347eCp7ImA9WhZWGUk."'> <id>tag:youtube.com,2008:live:event:ABF128AfLamNfZYVMiky</id> <published>2011-05-03T17:44:47.000Z</published> <updated>2011-05-21T01:38:06.000Z</updated> <app:edited>2011-05-21T01:38:06.000Z</app:edited> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#liveEvent'/> <title>Test Event</title> <summary>Testing live streaming.</summary> <content type='application/atom+xml'> <entry gd:etag='W/"DkEMRn47eCp7ImA9WhZXFEk."'> <id>tag:youtube.com,2008:video:BM7FWtADD0s</id> <published>2011-05-03T17:44:47.000Z</published> <updated>2011-05-03T17:44:47.000Z</updated> <app:edited>2011-05-03T17:44:47.000Z</app:edited> <app:control> <app:draft>yes</app:draft> <yt:state name='processing'/> </app:control> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/> <category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Entertainment' label='Entertainment'/> <category scheme='http://gdata.youtube.com/schemas/2007/keywords.cat' term='match'/> <title>Test Event</title> <link rel='alternate' type='text/html' href='https://www.youtube.com/watch?v=BM7FWtADD0s&feature=youtube_gdata'/> <link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/BM7FWtADD0s/responses?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#video.ratings' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/BM7FWtADD0s/ratings?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#video.complaints' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/BM7FWtADD0s/complaints?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/BM7FWtADD0s/related?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#video.captionTracks' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/BM7FWtADD0s/captions?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#insight.views' type='text/html' href='http://insight.youtube.com/video-analytics/csvreports?query=...'/> <author> <name>ytatestuser</name> <uri>https://gdata.youtube.com/feeds/api/users/ytatestuser</uri> <yt:userId>LKtfV8Wl406AI76bebMmnA</yt:userId> </author> <yt:accessControl action='comment' permission='allowed'/> <yt:accessControl action='commentVote' permission='allowed'/> <yt:accessControl action='videoRespond' permission='moderated'/> <yt:accessControl action='rate' permission='allowed'/> <yt:accessControl action='embed' permission='allowed'/> <yt:accessControl action='list' permission='allowed'/> <yt:accessControl action='syndicate' permission='allowed'/> <gd:comments> <gd:feedLink href='https://gdata.youtube.com/feeds/api/videos/BM7FWtADD0s/comments?v=2' countHint='0'/> </gd:comments> <media:group> <media:category label='Entertainment' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Entertainment</media:category> <media:content url='http://www.youtube.com/v/BM7FWtADD0s?f=videos&app=youtube_gdata' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='0' yt:format='5'/> <media:credit role='uploader' scheme='urn:youtube' yt:display='ytatestuser'>ytatestuser</media:credit> <media:description type='plain'>Testing live streaming.</media:description> <media:keywords>testing</media:keywords> <media:player url='https://www.youtube.com/watch?v=BM7FWtADD0s&feature=youtube_gdata_player'/> <media:restriction type='country' relationship='deny'>FR DE SE</media:restriction> <media:thumbnail url='http://i.ytimg.com/vi/BM7FWtADD0s/default.jpg' height='90' width='120' time='00:00:00' yt:name='default'/> <media:thumbnail url='http://i.ytimg.com/vi/BM7FWtADD0s/hqdefault.jpg' height='360' width='480' yt:name='hqdefault'/> <media:thumbnail url='http://i.ytimg.com/vi/BM7FWtADD0s/mqdefault.jpg' height='180' width='320' yt:name='mqdefault'/> <media:thumbnail url='http://i.ytimg.com/vi/BM7FWtADD0s/1.jpg' height='90' width='120' time='00:00:00' yt:name='start'/> <media:thumbnail url='http://i.ytimg.com/vi/BM7FWtADD0s/2.jpg' height='90' width='120' time='00:00:00' yt:name='middle'/> <media:thumbnail url='http://i.ytimg.com/vi/BM7FWtADD0s/3.jpg' height='90' width='120' time='00:00:00' yt:name='end'/> <media:title type='plain'>Test Event</media:title> <yt:duration seconds='0'/> <yt:uploaded>2011-05-03T17:44:47.000Z</yt:uploaded> <yt:videoid>BM7FWtADD0s</yt:videoid> </media:group> </entry> </content> <link rel='http://gdata.youtube.com/schemas/2007#video' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/values%3A+%22$2BM7FWtADD0s?v=2'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/users/ytatestuser/live/events/ABF128AfLamNfZYVMiky'/> <link rel='edit' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/users/ytatestuser/live/events/ABF128AfLamNfZYVMiky'/> <author> <name>ytatestuser</name> <uri>https://gdata.youtube.com/feeds/api/users/ytatestuser</uri> <yt:userId>LKtfV8Wl406AI76bebMmnA</yt:userId> </author> <media:group> <media:description type='plain'>Testing live streaming.</media:description> <media:title type='plain'>Test Event</media:title> </media:group> <yt:status>pending</yt:status> <yt:when start='2011-06-24T00:00:00.000Z'/> </entry> </feed>
Retrieving a single live event
There are two ways to obtain the API URL from which you would request information about a single live event:
-
In an event feed entry, the
<link>tag that has arelattribute value ofselfspecifies the URL from which you would retrieve that same entry via the API. When retrieving a live event entry, you can use theinlineparameter in the same way that you would use it when requesting a live events feed. -
If a video entry contains a
<link>tag for which therelattribute value ishttp://gdata.youtube.com/schemas/2007#live.event, then the video is associated with a live event. The tag'shrefattribute value will specify the API URL that you would use to retrieve information about the event itself.
Managing live events
Important: This is an experimental feature, which means that it might change unexpectedly.
This section describes the stages in the life of a live YouTube event and identifies the types of API requests that you will need to make as you manage the event from the time of its creation through its completion. It then explains the specific API calls that you will use to create, modify, and delete live events as well as the video metadata for those events.
All of the operations described in this section require you to send authenticated API requests and to specify the developer key assigned to your application. API requests can specify your developer key using either the X-GData-Key HTTP request header or the key query parameter. Please see http://code.google.com/apis/youtube/dashboard for instructions on how to register a YouTube API client application and obtain a developer key.
Prerequisites
Please note the following prerequisites for using the API functionality described in this section:
-
Developers need to sign an API Testing Agreement before their applications can successfully issue requests to manage live events. Please contact the YouTube developer relations team via a post to the YouTube APIs Developer Forum if you are interested in incorporating this functionality into your application.
-
The ability to create, update, and delete live events is only available to some YouTube users. The Determining whether a user can create live events section explains how to check a user's profile entry to see whether a user has access to these features.
Understanding the YouTube event lifecycle
The following steps explain the steps in the life of a YouTube event and identify the API operations associated with each step. In addition, please refer to YouTube's recommended encoding specifications for live video streams before planning your broadcasts.
-
You create the event by sending the event name, description, and approximate time in a POST request to add an event. If you know the CDN configuration details, you can specify them when adding the event. Otherwise, YouTube will return an ingestion (stream) URL in the default streaming format. The event is created with a status of
pending. -
You process the API response to capture the RTMP stream name and the RTMP stream URL for your event. If you are also broadcasting a backup video stream, capture the RTMP stream name and URL for the backup stream as well.
-
Prior to the event, you update the event as necessary to address any changes in the event details. For example, you might update the event's description or its expected start time.
-
Before you are ready to begin broadcasting, capture the RTMP stream URL and stream name for the event if you have not done so already. You can retrieve that information from the live video entry. The
<media:content>tag, which is a child of the<yt:cdn>tag, specifies both values. Also make sure you have the backup RTMP stream information if you are broadcasting a backup stream. -
You have the option of previewing your broadcast without making your live video stream visible to other users. Note that you do not need to send an API request to begin previewing your content.
The following steps explain how to preview your content:
-
Start streaming video to the RTMP URL for your event without updating the event to indicate that it has started.
-
Log in to your YouTube account.
-
Go to the
Livetab on your channel page, click the name of the event in the list of upcoming events, and then click theBroadcast Nowbutton in the video player area. You should see your stream appear on your channel within a few seconds.
-
You can stop the video stream and restart it when you are ready or proceed directly to step 7.
-
-
Start streaming video to the RTMP URL for your event. If you are also broadcasting to a backup URL, begin streaming to that URL as well. If you were previewing your stream and did not stop the stream, you will have already completed this action.
-
Start the event by sending an API request that updates the event and sets the
<yt:when>tag'sstartattribute tonow. This request will change the event's status frompendingtoactive.At this time, your video stream will be visible to other users who are tuned in and waiting for the event to be broadcast on your channel page.
-
End the event by sending an API request that updates the event and sets the
<yt:when>tag'sendattribute tonow. This request will change the event's status fromactivetocompleted.At this time, your video stream will stop being visible to users tuned in to watch your event.
Adding a live event
To create a live event, you must at least specify a minimal amount of information about the event itself, namely the event's title, description, and start time. You can also specify the CDN configuration for the event's video stream, other metadata about the video stream, or both. If you do not specify CDN details for the live video stream, YouTube will still create a live video with default CDN parameters and associate it with your event.
-
If you do not specify CDN configuration details for the event's video, YouTube will return an ingestion URL that expects to receive a 360p Flash video (FLV) stream.
-
If you do not specify video metadata for the event, YouTube will use the following default values:
-
The video title (
<media:title>) and the video description (<media:description>) will be the same as the event title and event description, respectively. (Currently, any title or description that you specify in the video metadata will be ignored, and the video title and description will be set to match the event title and description.) -
If the entry does not contain a
<media:category>element, YouTube sets the video's category to the category of the last video that the user uploaded. If no prior upload exists, YouTube sets the video's category toPeople.
-
When you create a live event, the API will return the live event entry. If you also set the inline parameter to true, then the entry's <content> tag will contain the live video entry for the video associated with the event.
The following sample requests demonstrate how to use the API to create new events:
Adding a live event with minimal details
The following example shows how to add a live event by only providing the minimum required amount of information about the event itself. The following event details are required in this request (and in any API request to add an event):
- The
<title>tag specifies the event's title. - The
<summary>tag contains a description of the event. - The
<yt:when>tag specifies the event's scheduled start time. You have the option of also specifying an (approximate) end time.
Sample XML
POST /feeds/api/users/default/live/events HTTP/1.1 Host: gdata.youtube.com Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY <?xml version='1.0' encoding='UTF-8'?> <entry xmlns='http://www.w3.org/2005/Atom' xmlns:yt='http://gdata.youtube.com/schemas/2007'> <title>Monster truck rally - Sunday June 26!</title> <summary>Sunday! Sunday! Sunday! Monster trucks at the county fairgrounds!</summary> <yt:when start='2011-06-26T20:00:00.000Z'/> </entry>
Adding a live event with CDN configuration
The example below shows how to add a live event and also specify the formats in which the live video will be streamed. The sample request specifies primary and secondary CDN information, though the secondary streaming is optional. YouTube will return one RTMP URL for each specified format. The client application that streams the video to YouTube will then send the video content to the appropriate URL for each format in which the video is streamed.
This example indicates that the video will be streamed in formats 18 (360p FLV) and 19 (480p FLV). It also indicates that secondary streams will be available for both formats. See the definition of the <media:content> tag's yt:format parameter for a list of valid parameter values.
Note: If you specify primary and secondary CDN information, then you should stream your content to the primary and secondary ingestion URLs simultaneously. YouTube will use the data from the primary ingestion stream but will switch to the secondary stream if the connection to the primary stream is disrupted.
Sample XML
POST /feeds/api/users/default/live/events HTTP/1.1 Host: gdata.youtube.com Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY <?xml version='1.0' encoding='UTF-8'?> <entry xmlns='http://www.w3.org/2005/Atom' xmlns:yt='http://gdata.youtube.com/schemas/2007'> <title>Monster truck rally - Sunday June 26!</title> <summary>Sunday! Sunday! Sunday! Monster trucks at the county fairgrounds!</summary> <content type='application/atom+xml'> <entry> <yt:cdn name='primary'> <media:content yt:format='18'/> <media:content yt:format='19'/> </yt:cdn> <yt:cdn name='secondary'> <media:content yt:format='18'/> <media:content yt:format='19'/> </yt:cdn> </entry> </content> <yt:when start='2011-06-26T20:00:00.000Z'/> </entry>
Updating a live event
You can update metadata for a live event or the live video stream associated with that event by submitting a PATCH request to the edit URL for the event. (In the event entry, this URL can be found in the <link> tag for which the rel attribute value is edit.)
https://gdata.youtube.com/feeds/api/users/default/live/events/EVENT_ID
You can update the title, description, and start time for an event. You can also update the CDN information for a video, by adding or removing streaming formats, for example. In addition, you can also update many of the video fields listed in the Updating a video entry section of the Developer's Guide.
The following sample request illustrates the XML format for modifying an event and its video.
PATCH /feeds/api/users/default/live/events/EVENT_ID HTTP/1.1 Host: gdata.youtube.com Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY <?xml version='1.0' encoding='UTF-8'?> <entry xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007' gd:fields='title,summary,yt:when,content/entry/yt:cdn'> <title>Monster Truck Rally - Monday, June 27</title> <summary>Moved to Monday! Monster trucks smash cars and burst into flame.</summary> <yt:when start='2011-06-27T20:00:00.000Z'/> <content type='application/atom+xml'> <entry> <yt:cdn name='primary'> <media:content yt:format='18'/> </yt:cdn> </entry> </content> </entry>
Starting a live event
To indicate that a live event is starting, update the event and set the <yt:when> tag's start attribute to now as shown in the example below:
PATCH /feeds/api/users/default/live/events/EVENT_ID HTTP/1.1 Host: gdata.youtube.com Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY <?xml version='1.0' encoding='UTF-8'?> <entry xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007' gd:fields='yt:when'> <yt:when start='now'/> </entry>
This update will also cause the event's status to change from pending to active.
Ending a live event
To indicate that a live event is ending, update the event and set the <yt:when> tag's end attribute to now as shown in the example below:
PATCH /feeds/api/users/default/live/events/EVENT_ID HTTP/1.1 Host: gdata.youtube.com Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY <?xml version='1.0' encoding='UTF-8'?> <entry xmlns='http://www.w3.org/2005/Atom' xmlns:media='http://search.yahoo.com/mrss/' xmlns:yt='http://gdata.youtube.com/schemas/2007' gd:fields='yt:when'> <yt:when end='now'/> </entry>
This update will also cause the event's status to change from active to completed.
Deleting a live event
Deleting a live event removes the event altogether. The following sample API request demonstrates how to delete a live event:
DELETE /feeds/api/users/default/live/events/EVENT_ID HTTP/1.1 Host: gdata.youtube.com Content-Type: application/atom+xml Authorization: Bearer ACCESS_TOKEN GData-Version: 2 X-GData-Key: key=DEVELOPER_KEY
Sample API response for adding or updating events
The sample XML entry below shows the format of an API response to a request to add or update a live event. The entry's <content> tag contains the live video entry, which indicates that the inline parameter would have been set to true in the corresponding API request.
<?xml version='1.0' encoding='UTF-8'?> <entry xmlns='http://www.w3.org/2005/Atom' xmlns:app='http://www.w3.org/2007/app' xmlns:media='http://search.yahoo.com/mrss/' xmlns:gd='http://schemas.google.com/g/2005' xmlns:yt='http://gdata.youtube.com/schemas/2007' gd:etag='W/"C0ICRn47eCp7ImA9WhZbEEU."'> <id>tag:youtube.com,2008:live:event:ABF128AfLanN-eatqP5dJAnnu0Xed0D_</id> <published>2011-06-14T19:59:27.000Z</published> <updated>2011-06-14T19:59:27.000Z</updated> <app:edited>2011-06-14T19:59:27.000Z</app:edited> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#liveEvent'/> <title>Big Truck Rally - Sunday, August 2</title> <summary>Monster trucks are made out of metal. </summary> <content type='application/atom+xml'> <entry gd:etag='W/"C0ICRn47eCp7ImA9WhZbEEU."'> <id>SpQXZYILnN0</id> <published>2011-06-14T19:59:27.000Z</published> <updated>2011-06-14T19:59:27.000Z</updated> <app:edited>2011-06-14T19:59:27.000Z</app:edited> <app:control> <app:draft>yes</app:draft> <yt:state name='processing'/> </app:control> <category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#video'/> <category scheme='http://gdata.youtube.com/schemas/2007/categories.cat' term='Entertainment' label='Entertainment'/> <title>Big Truck Rally - Sunday, August 2</title> <link rel='alternate' type='text/html' href='http://www.youtube.com/watch?v=SpQXZYILnN0&feature=youtube_gdata'/> <link rel='http://gdata.youtube.com/schemas/2007#video.responses' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/SpQXZYILnN0/responses?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#video.ratings' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/SpQXZYILnN0/ratings?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#video.complaints' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/SpQXZYILnN0/complaints?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#video.related' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/SpQXZYILnN0/related?v=2'/> <link rel='http://gdata.youtube.com/schemas/2007#video.captionTracks' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/SpQXZYILnN0/captions?v=2' yt:hasEntries='false'/> <link rel='http://gdata.youtube.com/schemas/2007#insight.views' type='text/html' href='http://insight.youtube.com/video-analytics/...'/> <author> <name>ytatestuser</name> <uri>https://gdata.youtube.com/feeds/api/users/ytatestuser</uri> <yt:userId>LKtfV8Wl406AI76bebMmnA</yt:userId> </author> <yt:accessControl action='comment' permission='allowed'/> <yt:accessControl action='commentVote' permission='allowed'/> <yt:accessControl action='videoRespond' permission='moderated'/> <yt:accessControl action='rate' permission='allowed'/> <yt:accessControl action='embed' permission='allowed'/> <yt:accessControl action='list' permission='allowed'/> <yt:accessControl action='syndicate' permission='allowed'/> <gd:comments> <gd:feedLink href='https://gdata.youtube.com/feeds/api/videos/SpQXZYILnN0/comments?v=2' countHint='0'/> </gd:comments> <media:group> <media:category label='Entertainment' scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>Entertainment</media:category> <media:content url='http://www.youtube.com/v/SpQXZYILnN0?f=videos&d=AYCLu96ijk1vhQNRODkbS5kO88HsQjpE1a8d1GxQnGDm&app=youtube_gdata' type='application/x-shockwave-flash' medium='video' isDefault='true' expression='full' duration='0' yt:format='5'/> <media:credit role='uploader' scheme='urn:youtube' yt:display='ytatestuser'>ytatestuser</media:credit> <media:description type='plain'>Monster trucks are made out of metal.</media:description> <media:keywords/> <media:player url='http://www.youtube.com/watch?v=SpQXZYILnN0&feature=youtube_gdata_player'/> <media:restriction type='country' relationship='deny'>FR DE SE</media:restriction> <media:thumbnail url='http://i.ytimg.com/vi/SpQXZYILnN0/default.jpg' height='90' width='120' time='00:00:00' yt:name='default'/> <media:thumbnail url='http://i.ytimg.com/vi/SpQXZYILnN0/hqdefault.jpg' height='360' width='480' yt:name='hqdefault'/> <media:thumbnail url='http://i.ytimg.com/vi/SpQXZYILnN0/mqdefault.jpg' height='180' width='320' yt:name='mqdefault'/> <media:thumbnail url='http://i.ytimg.com/vi/SpQXZYILnN0/1.jpg' height='90' width='120' time='00:00:00' yt:name='start'/> <media:thumbnail url='http://i.ytimg.com/vi/SpQXZYILnN0/2.jpg' height='90' width='120' time='00:00:00' yt:name='middle'/> <media:thumbnail url='http://i.ytimg.com/vi/SpQXZYILnN0/3.jpg' height='90' width='120' time='00:00:00' yt:name='end'/> <media:title type='plain'>Big Truck Rally - Sunday, August 2</media:title> <yt:duration seconds='0'/> <yt:uploaded>2011-06-1419:59:27.000Z</yt:uploaded> <yt:videoid>SpQXZYILnN0</yt:videoid> </media:group> <yt:cdn name='primary'> <media:content yt:format='19' yt:name='yt-live_SpQXZYILnN0_35' url='rtmp://rtmp1.youtube.com/videolive?...'/> </yt:cdn> </entry> </content> <link rel='http://gdata.youtube.com/schemas/2007#video' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/videos/value%3A+%22SpQXZYILnN0%22%0A?v=2'/> <link rel='self' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/users/ytatestuser/live/events/ABF128AfLanN-eatqP5dJAnnu0Xed0D_?v=2'/> <link rel='edit' type='application/atom+xml' href='https://gdata.youtube.com/feeds/api/users/ytatestuser/live/events/ABF128AfLanN-eatqP5dJAnnu0Xed0D_?v=2'/> <author> <name>ytatestuser</name> <uri>https://gdata.youtube.com/feeds/api/users/ytatestuser</uri> <yt:userId>LKtfV8Wl406AI76bebMmnA</yt:userId> </author> <media:group> <media:description type='plain'>Monster trucks are made out of metal.</media:description> <media:title type='plain'>Big Truck Rally - Sunday, August 2</media:title> </media:group> <yt:status>pending</yt:status> <yt:when start='2011-08-02T20:00:00.000Z'/> </entry>
Note that YouTube may use the <media:restriction> tag to identify countries where we do not support live video streams. As such, an API response might indicate that your live video cannot be viewed in certain countries even though you did not specify those restrictions when creating or updating your event.
Movies, trailers, and shows
Movies and trailers
Videos must meet special metadata requirements to be included in YouTube's Movies and Trailers categories. Feed entries for those videos accordingly contain several extra tags to reflect the enhanced metadata available for movies and trailers. Note, however, that movie and trailer entries are both types of video feed entries and could be returned in any feed that contains video entries, including search result feeds.
In addition, the YouTube API lets you retrieve several movie charts, which are standard feeds that only contain videos that appear in YouTube's Movies category.
The following subsections explain the special metadata fields included in movie and trailer entries as well as the movie charts that the API supports.
Special metadata fields in movie and trailer entries
Video and chart entries might contain several extra tags to reflect the enhanced metadata available for movies and trailers. These enhanced metadata fields are listed below:
-
The
<yt:availability>tag specifies the date range when the movie or trailer will be available on YouTube. -
The
<yt:firstReleased>tag specifies the movie's original release date. -
The entry may contain one or more additional
<media:category>tags in addition to the standard one that indicates that the video is in theMoviesorTrailerscategory:- A tag with a
schemeattribute value ofhttp://gdata.youtube.com/schemas/2007/mediatypes.catindicates whether a video is a feature film, a short film, or a trailer. The following values are valid for this scheme:1– Feature-length film2– Short film3– Full episode4– Show clip5– Trailer
- A tag with a
schemeattribute value ofhttp://gdata.youtube.com/schemas/2007/moviegenres.catspecifies a genre (e.g. "Action & Adventure" or "Comedy") that describes the movie. A movie may be associated with multiple genres. The following values are valid for this scheme:1– Action & Adventure2– Animation & Cartoons3– Classics4– Comedy5– Crime6– Drama7– Documentary & Biography8– Family9– Foreign10– Horror11– Mystery & Suspense12– Romance13– Science Fiction15– Sports18– Indian Cinema19– Nigerian Cinema
- A tag with a
schemeattribute value ofhttp://gdata.youtube.com/schemas/2007/releasemediums.catspecifies the original release medium for the movie. For example, a movie may have been originally released in theaters or on a premium cable channel. The following values are valid for this scheme:1– Theatrical or festival film releases2– Premium cable or satellite subscription channels, such as HBO3– Basic cable and satellite channels, such as Comedy Central or MTV4– Broadcast TV networks and local TV stations5– Promotional clips and trailers6– Original web content7– Direct-to-video release
- A tag with a
-
The
<media:credit>tag can identify a contributor (actor, director, producer, or writer) to the movie, and an entry can include multiple<media:credit>tags. -
The
<media:rating>tag can specify an MPAA (Motion Picture Association of America) or V-Chip rating for a movie. The tag'sschemeattribute identifies the type of rating, and the tag's value specifies the movie's rating under that scheme. -
A
<media:thumbnail>tag with ayt:nameattribute value ofposterspecifies the URL for an image of the movie's poster art. -
A trailer entry may contain a
<link>tag that specifies a link to the YouTube Data API feed for the movie featured in the trailer. The tag will have arelattribute value ofhttp://gdata.youtube.com/schemas/2007#video.trailer-for:
<link rel='http://gdata.youtube.com/schemas/2007#video.trailer-for' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/videos/lJD3ABBCSrc?v=2'/>
Retrieving a movie chart
To retrieve a movie chart, send a GET request to the URL associated with that chart. Note that you must be using version 2 of the YouTube API to retrieve any of these charts. You can specify the API version using either the v parameter or the GData-Version HTTP request header.
The following table identifies the URL associated with each chart:
| Chart name | Feed ID | URL and Description |
|---|---|---|
| Featured movies | featured | URL: https://gdata.youtube.com/feeds/api/charts/movies/featured?region=US Description: This feed lists movies that are featured on the YouTube Movies category home page or in the Google Play Store. This feed will be empty if you do not specify a value for the region parameter. In addition, this feed does not support the movie-genre parameter. |
| Most popular movies | most_popular | URL: https://gdata.youtube.com/feeds/api/charts/movies/most_popular?region=US Description: This feed lists the most popular videos in YouTube's Movies category. |
| Most recent movies | most_recent | URL: https://gdata.youtube.com/feeds/api/charts/movies/most_recent?region=US Description: This feed lists videos that were recently added to YouTube's Movies category. |
| Trending movies | trending | URL: https://gdata.youtube.com/feeds/api/charts/movies/trending?region=US Description: This feed lists videos that have recently experienced the greatest increases in popularity. You must specify a value for the region parameter to retrieve this feed. |
API requests to retrieve movie charts can specify any of the following parameters:
- The
hlparameter specifies the movie's primary language. - The
movie-genreparameter filters a chart to only include movies that are in a particular genre. The featured movie chart does not support this parameter. - The
paid-contentparameter filters a chart to only include either paid content or free content. If the parameter is not set, a chart can include both paid and free content. - The
regionparameter filters a chart to only include movies that are viewable in a particular territory. The parameter value is an ISO 3166-1 alpha-2 code that identifies the country where videos must be viewable to be included in search results. The featured movie chart returns an empty feed if you do not specify a value for this parameter.
You can use the following URL to retrieve the top selling or top free movies listed on http://www.youtube.com/movies. Set the paid-content parameter to true for movie rentals and to false for free movies. Note that you also need to provide the appropriate parameter values for the hl (e.g. en) and region (e.g. US) parameters.
http://gdata.youtube.com/feeds/api/charts/movies/trending?v=2
&max-results=10
&paid-content=(true|false)
&hl=<LANGUAGE>
®ion=<REGION_CODE>
Shows, seasons, and episodes
As for movies, videos must meet special metadata requirements to be included in YouTube's Shows category. Feed entries for those videos accordingly contain several extra tags to reflect the enhanced metadata available for shows content. However, these entries are still video feed entries and could be returned in any feed that contains video entries, including search result feeds.
Videos for shows can be either full episodes or clips from an episode. Each video is associated with a particular season of a particular show, and the API provides feeds for retrieving shows, seasons of a show, and episodes (and clips) associated with a season of a show. The API also lets you retrieve show-related charts, which are standard feeds that only contain lists of shows.
In addition, videos in YouTube's Shows category are each associated with a particular season of a specific show. The API provides feeds for retrieving shows, seasons of a show, and episodes (and clips) associated with a specific season of a show. While only the episode/clip feed is a video feed, the other feeds are also explained below.
The following subsections explain these topics in more detail:





).