傳送第一個要求

注意:YouTube Content ID API 為 YouTube 內容合作夥伴使用,並未開放所有開發人員或所有 YouTube 使用者存取。如果 Google API 控制台顯示的服務中沒有 YouTube Content ID API,請參閱 YouTube 說明中心,進一步瞭解 YouTube 合作夥伴計畫。

這個逐步教學課程會說明如何建構指令碼來連線至 ContentOwnersService,以及如何擷取特定內容擁有者的相關資訊。教學課程結束時會提供完整的程式碼範例。雖然這個程式碼是以 Python 編寫,不過您也可以使用其他熱門程式設計語言的用戶端程式庫。

需求條件

建構傳送 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 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=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)