注意: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 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)