傳送第一個要求

注意:YouTube Data API 僅供 YouTube 內容合作夥伴使用,並未開放所有開發人員或 YouTube 使用者存取。你必須擁有 YouTube 內容管理工具帳戶,才能存取這項功能。如果你有 YouTube 內容管理工具帳戶,但 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 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 互動的方法。

新增下列匯入陳述式:

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()