إرسال الطلب الأول

ملاحظة: إنّ واجهة YouTube Data API مخصّصة لشركاء المحتوى في YouTube، ولا يمكن لجميع المطوّرين أو جميع مستخدمي YouTube الوصول إليها. يتطلّب الوصول إلى هذه الميزة حسابًا على "إدارة المحتوى" في YouTube. إذا كان لديك حساب على "إدارة المحتوى" في YouTube ولكنّك لا ترى YouTube Data API كإحدى الخدمات المُدرَجة في وحدة تحكّم Google Cloud، يُرجى التواصل مع مدير الشركاء أو فريق دعم الشركاء المخصّص لك.

يشرح هذا البرنامج التعليمي المفصّل كيفية إنشاء نص برمجي يتصل بـ ContentOwnersService ويسترد معلومات حول مالك محتوى معيّن. يتوفّر نموذج رمز كامل في نهاية البرنامج التعليمي. على الرغم من أنّ هذا الرمز مكتوب بلغة Python، تتوفّر أيضًا مكتبات برامج للغات برمجة شائعة أخرى.

المتطلبات

إنشاء نص برمجي لإرسال طلبات إلى واجهة برمجة التطبيقات

توضّح الخطوات التالية كيفية إنشاء نص برمجي لإرسال طلب بيانات من واجهة برمجة التطبيقات إلى 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 إلى النص البرمجي. يتيح ذلك للمستخدم الذي يشغّل البرنامج النصي تفويض البرنامج النصي بتنفيذ طلبات واجهة برمجة التطبيقات التي يتم إسنادها إلى حساب المستخدم.

الخطوة 2 (أ): إنشاء ملف client_secrets.json

تتطلّب YouTube Data API ملف client_secrets.json يحتوي على معلومات من Cloud 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 datetime import datetime
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import argparser, run_flow

بعد ذلك، سننشئ عنصر FLOW باستخدام أسرار العميل التي تم إعدادها في الخطوة 2أ. إذا سمح المستخدم لتطبيقنا بإرسال طلبات إلى واجهة برمجة التطبيقات نيابةً عنه، يتم تخزين بيانات الاعتماد الناتجة في عنصر 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)

الخطوة 2(ج): إنشاء عنصر httplib2 وإرفاق بيانات الاعتماد

بعد أن يمنح المستخدم الإذن لبرنامجنا النصي، ننشئ عنصر httplib2.Http، الذي يتعامل مع طلبات البيانات من واجهة برمجة التطبيقات، ونرفق بيانات اعتماد التفويض بهذا العنصر.

أضِف عبارة الاستيراد التالية:

  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 موردًا يمكنه التفاعل مع إحدى واجهات برمجة التطبيقات. بعد أن يمنح المستخدم الإذن لتطبيقنا، ننشئ العنصر service الذي يوفّر طرقًا للتفاعل مع ContentOwnerService.

أضِف عبارة الاستيراد التالية:

from apiclient.discovery import build

وأضِف هذا الرمز في نهاية الدالة main:

  service = build("youtubePartner", "v1", http=http, static_discovery=False)
  contentOwnersService = service.contentOwners()

الخطوة 4: تنفيذ طلب بيانات من واجهة برمجة التطبيقات

الآن، سننشئ طلب خدمة وننفّذه. تنشئ الرمز البرمجي التالي طلب 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']))

إكمال الطلب

يعرض هذا القسم التطبيق الكامل مع بعض معلومات الترخيص والتعليقات الإضافية في النص البرمجي. هناك طريقتان لتشغيل البرنامج:

  • يؤدي هذا الأمر إلى فتح نافذة متصفّح يمكنك من خلالها إجراء المصادقة، إذا لزم الأمر، والسماح للتطبيق بإرسال طلبات إلى واجهة برمجة التطبيقات. في حال منح الإذن للتطبيق، يتم تلقائيًا إعادة إرسال بيانات الاعتماد إلى النص البرمجي.

    python3 yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID

    ملاحظة: يمكنك العثور على قيمة CONTENT_OWNER_ID لحسابك في صفحة إعدادات الحساب في حساب نظام إدارة المحتوى. يتم إدراج القيمة على أنّها Partner Code في قسم معلومات الحساب على تلك الصفحة.

  • يُخرج هذا الأمر عنوان URL يمكنك فتحه في متصفّح، ويطلب منك أيضًا إدخال رمز تفويض. عند الانتقال إلى عنوان URL، تتيح لك هذه الصفحة منح التطبيق الإذن بإرسال طلبات إلى واجهة برمجة التطبيقات نيابةً عنك. في حال منح هذا التفويض، ستعرض الصفحة رمز التفويض الذي عليك إدخاله عند الطلب لإكمال مسار التفويض.

    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()