注意: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
对象并附加凭据
用户授权我们的脚本后,我们会创建一个用于处理 API 请求的 httplib2.Http
对象,并将授权凭据附加到该对象。
添加以下 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.
注意:
oauth2client
模块可识别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/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)