最初のリクエストを送信する

注: YouTube Content ID API は、YouTube コンテンツ パートナーによる使用を目的とした API であり、すべてのデベロッパーまたはすべての YouTube ユーザーがアクセスすることはできません。Google API Console に YouTube Content ID API がサービスとして表示されない場合は、YouTube ヘルプセンターで YouTube パートナー プログラムの詳細をご覧ください。

このチュートリアルでは、ContentOwnersService に接続して特定のコンテンツ所有者に関する情報を取得するスクリプトの作成方法について説明します。完全なコード ��ンプルはチュートリアルの最後にあります。e tutorial. このコードは 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 で認証を行うには、API Console から取得した情報を含む 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 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 オブジェクトを作成して認証情報を関連付ける

ユーザーがスクリプトを承認したら、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 とやり取りできるリソースを構築します。ユーザーがアプリケーションを承認したら、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=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'])

完全なアプリケーション

このセクションでは、スクリプトにライセンス情報とその他のコメントを加えた完全なアプリケーションについて説明します。このプログラムを実行するには、2 つの方法があります。

  • このコマンドは、ブラウザ ウィンドウを起動し必要に応じて認証を行い、API リクエストを送信するアプリケーションを承認します。アプリケーションを承認すると、認証情報がスクリプトに自動的に送り返されます。

    python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID.

    注: アカウントの CONTENT_OWNER_ID の値は、CMS アカウントの [アカウント設定] ページで確認できます。この値は、該当ページのアカウント情報セクションに Partner Code として表示されています。

  • このコマンドはブラウザで開ける URL を出力し、承認コードの入力を求めるプロンプトを表示します。URL を開いたら、そのページからアプリケーションを承認して、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)