注: YouTube Data API は YouTube コンテンツ パートナーによる使用を想定していますので、すべてのデベロッパーやすべての YouTube ユーザーがアクセスできるわけではありません。アクセスするには、YouTube コンテンツ マネージャ アカウントが必要です。YouTube コンテンツ マネージャー アカウントをお持ちで、Google Cloud コンソールに表示されるサービスのリストに YouTube Data API が含まれていない場合は、担当のパートナー マネージャーまたはパートナー サポートにお問い合わせください。
このチュートリアルでは、ContentOwnersService に接続して特定のコンテンツ所有者に関する情報を取得するスクリプトを作成する方法について、手順を追って説明します。完全なコード サンプルはチュートリアルの最後にあります。e tutorial. このコードは Python で書かれていますが、他の一般的なプログラミング言語のクライアント ライブラリも利用できます。
要件
- Python 3.7 以降
- google-api-python-client
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 では、認証を行うために Cloud コンソールの情報を含む 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" } }
ステップ 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 オブジェクトを作成して認証情報を関連付ける
ユーザーがスクリプトを承認すると、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 とやり取りできるリソースを構築します。ユーザーがアプリを承認したら、ContentOwnerService とやり取りするためのメソッドを提供する service オブジェクトを作成します。
次の 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']))
完全なアプリケーション
このセクションでは、ライセンス情報とスクリプト内の追加のコメントを含む完全なアプリケーションを示します。このプログラムを実行するには、2 つの方法があります。
-
このコマンドは、ブラウザ ウィンドウを起動し必要に応じて認証を行い、API リクエストを送信するアプリケーションを承認します。アプリケーションを承認すると、認証情報がスクリプトに自動的に送り返されます。
python3 yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID
注: アカウントの
CONTENT_OWNER_ID値は、CMS アカウントの [アカウント設定] ページで確認できます。このページのアカウント情報セクションに、Partner Codeとして値が表示されます。 -
このコマンドはブラウザで開ける URL を出力し、承認コードの入力を求めるプロンプトを表示します。URL を開いたら、そのページからアプリケーションを承認して、API リクエストを送信します。承認を付与すると、ページに承認フローで入力を求められる承認コードが表示されます。
python3 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/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()