发送第一个请求

注意:YouTube Data API 仅供 YouTube 内容合作伙伴使用,并非所有开发者或 YouTube 用户都可以访问。您需要拥有 YouTube 内容管理器账号才能访问。如果您拥有 YouTube Content Manager 账号,但未在 Google Cloud 控制台中看到 YouTube Data API 列为服务之一,请与您的指定合作伙伴经理或合作伙伴支持团队联系。

本分步教程介绍了如何构建一个连接到 ContentOwnersService 并检索指定内容所有者相关信息的脚本。本教程末尾提供了完整的代码示例。虽然此代码是用 Python 编写的,但也有适用于其他常用编程语言的客户端库。

要求

构建用于发送 API 请求的脚本

以下步骤说明了如何构建脚本以发送 YouTube Data API 请求:

第 1 步:创建基本脚本

以下脚本接受以下命令行实参:

  • content_owner_id 参数是必需的,用于标识您要检索其信息的 CMS 内容所有者。
  • logging_level 参数用于指定脚本的日志记录详细程度。
  • help 参数会导致脚本输出其可识别的参数列表。
#!/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 Data 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()

第 2 步:启用用户身份验证和授权

在此步骤中,我们将把 OAuth 2.0 授权纳入脚本中。这样一来,运行脚本的用户便可授权脚本执行归因于用户账号的 API 请求。

第 2a 步:创建 client_secrets.json 文件

YouTube Data API 需要一个 client_secrets.json 文件(其中包含来自 Cloud 控制台的信息)才能执行身份验证。您还需要注册应用。如需更全面地了解身份验证的运作方式,请参阅身份验证指南。

 {
  "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 datetime import datetime
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import argparser, run_flow

接下来,我们将使用在步骤 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(FLOW, storage, args)

第 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=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']))

完整申请

本部分展示了完整的应用,其中包含一些许可信息和脚本中的其他注释。您可以通过以下两种方式运行该程序:

  • 此命令会启动一个浏览器窗口,您可以在其中进行身份验证(如有必要),并授权应用提交 API 请求。如果您授权该应用,凭据会自动中继回脚本。

    python3 yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID

    注意:您可以在 CMS 账号的账号设置页面中找到您账号的 CONTENT_OWNER_ID 值。该值会以 Partner Code 的形式列在该页面上的账号信息部分。

  • 此命令会输出一个可在浏览器中打开的网址,还会提示您输入授权代码。当您前往该网址时,该网页会允许您授权应用代表您提交 API 请求。如果您授予该授权,页面会显示授权代码,您需要在提示符处输入该代码才能完成授权流程。

    python3 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/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 Data 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 Data 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()