שליחת בקשה ראשונה

הערה: ממשק ה-API של Content ID ב-YouTube מיועד לשימוש של שותפי תוכן ב-YouTube, ולא זמין לכל המפתחים או לכל המשתמשים ב-YouTube. אם ממשק ה-API של YouTube Content ID לא מופיע כאחד מהשירותים שמפורטים במסוף Google API, אפשר לעיין במרכז העזרה של YouTube כדי לקבל מידע נוסף על תוכנית השותפים של YouTube.

במדריך המפורט הזה נסביר איך ליצור סקריפט שמתחבר אל ContentOwnersService ומאחזר מידע על בעלי תוכן נתון. דוגמה מלאה לקוד מוצגת בסוף המדריך. הקוד הזה נכתב ב-Python, אבל יש גם ספריות לקוח בשפות תכנות פופולריות אחרות.

דרישות

פיתוח סקריפט לשליחת בקשות API

בשלבים הבאים נסביר איך ליצור סקריפט לשליחת בקשה ל-API של YouTube Content ID:

שלב 1: יוצרים את הסקריפט הבסיסי

הסקריפט הבא מקבל את הפרמטרים הבאים של שורת הפקודה ומגדיר ערכים למשתנה הגלובלי FLAGS:

  • הפרמטר content_owner_id נדרש ומזהה את בעלי התוכן של מערכת ניהול התוכן שלגביו רוצים לאחזר את המידע.
  • הפרמטר 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 שמשויכות לחשבון המשתמש.

שלב 2א: יוצרים קובץ client_secrets.json

כדי לבצע אימות, נדרש קובץ client_secrets.json ב-YouTube Content ID API שמכיל מידע מ-API Console. בנוסף, צריך לרשום את הבקשה. הסבר מקיף יותר על אופן הפעולה של האימות זמין במדריך האימות.

 {
  "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"
  }
}

שלב 2ב: מוסיפים קוד אימות לסקריפט

כדי להפעיל אימות והרשאה של משתמשים, צריך להוסיף את הצהרות import הבאות:

from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run

בשלב הבא ניצור אובייקט FLOW באמצעות סודות הלקוח שהוגדרו בשלב 2א. אם המשתמש מאשר לאפליקציה לשלוח בקשות 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)

שלב 2ג: יוצרים אובייקט 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: קבלת שירות

הפונקציה build בספריית הלקוח של Python יוצרת משאב שיכול לקיים אינטראקציה עם 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.

    הערה: הערך של CONTENT_OWNER_ID בחשבון מופיע בדף Account Settings (הגדרות החשבון) בחשבון ה-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)