Note: The YouTube Content ID API is intended for use by YouTube content partners and is not accessible to all developers or to all YouTube users. If you do not see the YouTube Content ID API as one of the services listed in the Google API Console, see the YouTube Help Center to learn more about the YouTube Partner Program.
This step-by-step tutorial explains how to build a script that connects to ContentOwnersService
and retrieves information about a given content owner. A complete code sample is provided at the end of the tutorial. While this code is written in Python, client libraries for other popular programming languages are also available.
Requirements
- Python 2.5 or higher
- google-api-python-client
Building a script to send API requests
The following steps explain how to construct a script to send a YouTube Content ID API request:
Step 1: Create the basic script
The following script accepts the following command-line parameters and sets values on the global FLAGS
variable:
- The
content_owner_id
parameter is required and identifies the CMS content owner that you are retrieving information about. - The
logging_level
parameter specifies the level of logging detail for the script. - The
help
parameter causes the script to output a list of the parameters that it understands.
#!/usr/bin/python2.6 # -*- coding: utf-8 -*- import gflags import logging import sys import os from datetime import * # Define flags. The gflags module makes it easy to define command-line params # for an application. Run this program with the '--help' argument to see all # of the flags that it understands. FLAGS = gflags.FLAGS gflags.DEFINE_string('content_owner_id', None, ('Required flag. ' 'Identifies the content owner whose details are printed out.')) gflags.MarkFlagAsRequired('content_owner_id') gflags.DEFINE_enum('logging_level', 'ERROR', ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], 'Set the level of logging detail.') def main(argv): # Let the gflags module process the command-line arguments try: argv = FLAGS(argv) except gflags.FlagsError, e: print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS) sys.exit(1) # Set the logging according to the command-line flag logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level)) if __name__ == '__main__': main(sys.argv)
Step 2: Enable user authentication and authorization
In this step, we'll incorporate OAuth 2.0 authorization into the script. This enables the user running the script to authorize the script to perform API requests attributed to the user's account.
Step 2a: Create a client_secrets.json file
The YouTube Content ID API requires a client_secrets.json
file, which contains information from the API Console, to perform authentication. You also need to register your application. For a more complete explanation of how authentication works see the authentication guide.
{ "web": { "client_id": "INSERT CLIENT ID HERE", "client_secret": "INSERT CLIENT SECRET HERE", "redirect_uris": [], "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token" } }
Step 2b: Add authentication code to your script
To enable user authentication and authorization, you need to add the following import
statements:
from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import run
Next, we'll create a FLOW
object using the client secrets configured in step 2a. If the user authorizes our application to submit API requests on the user's behalf, the resulting credentials are stored in a Storage
object for later use. The user will need to reauthorize our application if the credentials expire.
Add the following code to the end of the main
function:
# Set up a Flow object to be used if we need to authenticate. FLOW = flow_from_clientsecrets('client_secrets.json', scope='https://www.googleapis.com/auth/youtubepartner', message='error message') # The Storage object stores the credentials. If it doesn't exist, or if # the credentials are invalid or expired, run through the native client flow. storage = Storage('yt_partner_api.dat') credentials = storage.get() if (credentials is None or credentials.invalid or credentials.token_expiry <= datetime.now()): credentials = run(FLOW, storage)
Step 2c: Create httplib2
object and attach credentials
After the user authorizes our script, we create an httplib2.Http
object, which handles API requests, and attach the authorization credentials to that object.
Add the following import statement:
import httplib2
And add this code to the end of the main
function:
# Create httplib2.Http object to handle HTTP requests and # attach auth credentials. http = httplib2.Http() http = credentials.authorize(http)
Step 3: Obtain a service
The Python client library's build
function constructs a resource that can interact with an API. After the user has authorized our application, we create the service
object, which provides methods for interacting with the ContentOwnerService
.
Add the following import statement:
from apiclient.discovery import build
And add this code at the end of the main
function:
service = build("youtubePartner", "v1", http=http, static_discovery=False) contentOwnersService = service.contentOwners()
Step 4: Execute an API request
Now, we'll create a service request and execute it. The following code creates and executes a contentOwnersService.get()
request, which retrieves information about the specified content owner.
Add this code at the end of the main
function:
# Create and execute get request. request = contentOwnersService.get(contentOwnerId=FLAGS.content_owner_id) content_owner_doc = request.execute(http) print ('Content owner details: id: %s, name: %s, ' 'notification email: %s') % ( content_owner_doc['id'], content_owner_doc['displayName'], content_owner_doc['disputeNotificationEmails'])
Complete application
This section shows the complete application with some licensing information and additional comments in the script. There are two ways to run the program:
-
This command launches a browser window through which you can authenticate, if necessary, and authorize the application to submit API requests. If you authorize the application, the credentials are automatically relayed back to the script.
python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID.
Note: You can find the
CONTENT_OWNER_ID
value for your account on the Account Settings page in your CMS account. The value is listed as thePartner Code
in the account information section on that page. -
This command outputs a URL that you can open in a browser and it also prompts you to enter an authorization code. When you navigate to the URL, that page lets you authorize the application to submit API requests on your behalf. If you grant that authorization, the page displays the authorization code that you need to enter at the prompt to complete the authorization flow.
python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID --noauth_local_webserver.
Note: The
oauth2client
module recognizes thenoauth_local_webserver
parameter even though the parameter is not mentioned in the script.
client_secrets.json
{ "web": { "client_id": "INSERT CLIENT ID HERE", "client_secret": "INSERT CLIENT SECRET HERE", "redirect_uris": [], "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token" } }
yt_partner_api.py
#!/usr/bin/python2.6 # -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Simple command-line sample for YouTube Content ID API. Command-line application that retrieves the information about given content owner. Usage: $ python yt_partner_api.py --content_owner_id=[contentOwnerId] $ python yt_partner_api.py --content_owner_id=[contentOwnerId] --noauth_local_webserver You can also get help on all the command-line flags the program understands by running: $ python yt_partner_api.py --help To get detailed log output run: $ python yt_partner_api.py --logging_level=DEBUG \ --content_owner_id=[contentOwnerId] """ import gflags import httplib2 import logging import sys import os from datetime import * from apiclient.discovery import build from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import run # Define flags. The gflags module makes it easy to define command-line options # for an application. Run this program with the '--help' argument to see all # of the flags that it understands. FLAGS = gflags.FLAGS gflags.DEFINE_string('content_owner_id', None, ('Required flag. ' 'Identifies the content owner id whose details are printed out.')) gflags.MarkFlagAsRequired('content_owner_id') gflags.DEFINE_enum('logging_level', 'ERROR', ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], 'Set the level of logging detail.') def main(argv): # Let the gflags module process the command-line arguments try: argv = FLAGS(argv) except gflags.FlagsError, e: print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS) sys.exit(1) # Set the logging according to the command-line flag logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level)) # Set up a Flow object to be used if we need to authenticate. FLOW = flow_from_clientsecrets('client_secrets.json', scope='https://www.googleapis.com/auth/youtubepartner', message='error message') # The Storage object stores the credentials. If the credentials are invalid # or expired and the script isn't working, delete the file specified below # and run the script again. storage = Storage('yt_partner_api.dat') credentials = storage.get() if (credentials is None or credentials.invalid or credentials.token_expiry <= datetime.now()): credentials = run(FLOW, storage) http = httplib2.Http() http = credentials.authorize(http) service = build("youtubePartner", "v1", http=http) contentOwnersService = service.contentOwners() # Create and execute get request. request = contentOwnersService.get(contentOwnerId=FLAGS.content_owner_id) content_owner_doc = request.execute(http) print ('Content owner details: id: %s, name: %s, ' 'notification email: %s') % ( content_owner_doc['id'], content_owner_doc['displayName'], content_owner_doc['disputeNotificationEmails']) if __name__ == '__main__': main(sys.argv)