Page Summary
-
This tutorial demonstrates how to build a Python script that uses the YouTube Content ID API to retrieve content owner information.
-
The YouTube Content ID API is exclusively for YouTube content partners and requires registration.
-
The script leverages OAuth 2.0 for user authentication and authorization to access the API.
-
A
client_secrets.jsonfile with API credentials from the Google API Console is necessary. -
Users need to authorize the script to submit API requests on their behalf, and the script provides two ways to authorize.
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. Access requires a YouTube Content Manager account, and the API appears in the Google Cloud console only when you sign in with a Google Account that is an active Content Manager user (allow 1 to 2 days after accepting an invitation for access to sync). If you still don't see the YouTube Content ID API after 2 days, contact your YouTube point of contact or partner support.
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 3.7 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 arguments:
- The
content_owner_idparameter is required and identifies the CMS content owner that you are retrieving information about. - The
logging_levelparameter specifies the level of logging detail for the script. - The
helpparameter causes the script to output a list of the parameters that it understands.
#!/usr/bin/env python3
import argparse
import logging
import sys
# Define command-line arguments using argparse. Run this program with
# the '--help' argument to see all parameters that it understands.
parser = argparse.ArgumentParser(
description='Simple command-line sample for YouTube Content ID API.')
parser.add_argument(
'--content_owner_id',
required=True,
help='Required. Identifies the content owner whose details are printed out.')
parser.add_argument(
'--logging_level',
default='ERROR',
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
help='Set the level of logging detail.')
def main():
args = parser.parse_args()
# Set the logging according to the command-line flag
logging.getLogger().setLevel(getattr(logging, args.logging_level))
if __name__ == '__main__':
main()
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 Cloud 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 datetime import datetime from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import argparser, run_flow
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(FLOW, storage, args)
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=args.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.
python3 yt_partner_api.py --content_owner_id=CONTENT_OWNER_IDThis 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.
python3 yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID --noauth_local_webserver
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/env python3
#
# 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:
$ python3 yt_partner_api.py --content_owner_id=[contentOwnerId]
$ python3 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:
$ python3 yt_partner_api.py --help
To get detailed log output run:
$ python3 yt_partner_api.py --logging_level=DEBUG \
--content_owner_id=[contentOwnerId]
"""
import argparse
from datetime import datetime
import logging
import os
import sys
from apiclient.discovery import build
import httplib2
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
# Define parser.
parser = argparse.ArgumentParser(
parents=[argparser],
description='Simple command-line sample for YouTube Content ID API.')
parser.add_argument(
'--content_owner_id',
required=True,
help='Required. Identifies the content owner id whose details are printed out.')
parser.add_argument(
'--logging_level',
default='ERROR',
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
help='Set the level of logging detail.')
def main():
args = parser.parse_args()
# Set the logging according to the command-line flag
logging.getLogger().setLevel(getattr(logging, args.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(FLOW, storage, args)
http = httplib2.Http()
http = credentials.authorize(http)
service = build("youtubePartner", "v1", http=http, static_discovery=False)
contentOwnersService = service.contentOwners()
# Create and execute get request.
request = contentOwnersService.get(contentOwnerId=args.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()