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

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

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

דרישות

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

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

שלב 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

כדי לבצע אימות ב-YouTube Content ID API, נדרש קובץ client_secrets.json, שמכיל מידע מ-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 של החשבון בדף הגדרות חשבון בחשבון מערכת ניהול התוכן. הערך מופיע בתור 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)