注意:YouTube Content ID API 专供 YouTube 内容合作伙伴使用,并非所有开发者或 YouTube 用户都能使用。如果您在 Google API 控制台中未看到 YouTube Content ID API 列为某项服务,请访问 YouTube 帮助中心,详细了解 YouTube 合作伙伴计划。
此分步教程介绍了如何构建连接到 ContentOwnersService
并检索指定内容所有者信息的脚本。本教程结尾提供了完整的代码示例。尽管此代码是用 Python 编写的,但您也可以使用其他常用编程语言的客户端库。
要求
- Python 2.5 或更高版本
- google-api-python-client
构建用于发送 API 请求的脚本
以下步骤介绍了如何构建用于发送 YouTube Content ID API 请求的脚本。
第 1 步:创建基本脚本
以下脚本接受以下命令行参数,并为全局 FLAGS
变量设置值:
content_owner_id
是必需参数,可用于识别您要检索其相关信息的 CMS 内容所有者。logging_level
参数指定脚本的日志记录详细信息级别。help
参数会使脚本输出其可以理解的参数列表。
#!/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)
第 2 步:启用用户身份验证和授权
在此步骤中,我们会将 OAuth 2.0 授权整合到脚本中。这样一来,运行脚本的用户就可以授权该脚本执行归因于用户账号的 API 请求。
第 2a 步:创建 client_secrets.json 文件
YouTube Content ID API 需要 client_secrets.json
文件,该文件包含来自 API 控制台的信息,才能执行身份验证。您还需要注册应用。如需更全面��了解身份验证的工作原理,请参阅身份验证指南。
{ "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" } }
第 2b 步:向脚本中添加身份验证代码
如需启用用户身份验证和授权,您需要添加以下 import
语句:
from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import run
接下来,我们将使用第 2a 步中配置的客户端密钥创建 FLOW
对象。如果用户授权应用代表用户提交 API 请求,生成的凭据会存储在 Storage
对象中以供日后使用。如果凭据过期,用户将需要重新授权我们的应用。
将以下代码添加到 main
函数的末尾:
# 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)
第 2c 步:创建 httplib2
对象并附加凭据
在用户为脚本授权后,我们创建一个 httplib2.Http
对象来处理 API 请求,并将授权凭据附加到该对象。
添加以下 import 语句:
import httplib2
并将以下代码添加到 main
函数的末尾:
# Create httplib2.Http object to handle HTTP requests and # attach auth credentials. http = httplib2.Http() http = credentials.authorize(http)
第 3 步:获取服务
Python 客户端库的 build
函数用于构造可与 API 交互的资源。用户为应用授权后,我们创建 service
对象,用于提供与 ContentOwnerService
交互的方法。
添加以下 import 语句:
from apiclient.discovery import build
在 main
函数的末尾添加以下代码:
service = build("youtubePartner", "v1", http=http, static_discovery=False) contentOwnersService = service.contentOwners()
第 4 步:执行 API 请求
现在,我们将创建服务请求并执行该请求。以下代码创建并执行 contentOwnersService.get()
请求,用于检索关于指定内容所有者的信息。
在 main
函数的末尾添加以下代码:
# 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'])
完成申请
此部分显示完整的应用程序,在脚本中包含一些许可信息和其他注释。您可以通过以下两种方式运行程序:
-
此命令会启动一个浏览器窗口,如有必要,您可以通过该窗口进行身份验证,并授权应用提交 API 请求。如果您授权该应用,系统会自动将凭据中继回脚本。
python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID.
注意:您可以在 CMS 帐号的帐号设置页面上找到帐号的
CONTENT_OWNER_ID
值。该值会在该页面的帐号信息部分以Partner Code
的形式列出。 -
此命令会输出一个可在浏览器中打开的网址,还会提示您输入授权代码。当您导航到该网址时,通过该页面,您可以授权应用代表您提交 API 请求。如果您授予该授权,页面会显示授权代码。您需要在提示时输入此授权代码才能完成授权流程。
python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID --noauth_local_webserver.
注意:即使脚本中未提及
noauth_local_webserver
参数,oauth2client
模块也会识别该参数。
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)