İlk İstek Gönderme

Not: YouTube Content ID API, YouTube içerik iş ortaklarının kullanımı için tasarlanmıştır ve tüm geliştiriciler ya da tüm YouTube kullanıcıları tarafından kullanılamaz. YouTube Content ID API'yi Google API Konsolu'nda listelenen hizmetlerden biri olarak görmüyorsanız YouTube İş Ortağı Programı hakkında daha fazla bilgi edinmek için YouTube Yardım Merkezi'ni ziyaret edin.

Bu adım adım açıklamalı eğitimde, ContentOwnersService ile bağlantı kuran ve belirli bir içerik sahibiyle ilgili bilgileri alan bir komut dosyasının nasıl oluşturulacağı açıklanmaktadır. Eğiticinin sonunda eksiksiz bir kod örneği sağlanır. Bu kod Python'da yazılmışken diğer popüler programlama dilleri için istemci kitaplıkları da mevcuttur.

Koşullar

API istekleri göndermek için komut dosyası oluşturma

Aşağıdaki adımlarda, YouTube Content ID API isteği göndermek için nasıl komut dosyası oluşturacağınız açıklanmaktadır.

1. Adım: Temel komut dosyasını oluşturun

Aşağıdaki komut dosyası, aşağıdaki komut satırı parametrelerini kabul eder ve genel FLAGS değişkenindeki değerleri ayarlar:

  • content_owner_id parametresi gereklidir ve hakkında bilgi aldığınız İYS içerik sahibini tanımlar.
  • logging_level parametresi, komut dosyasının günlük kaydı ayrıntı düzeyini belirtir.
  • help parametresi, komut dosyasının anladığı parametrelerin bir listesini oluşturmasını sağlar.
#!/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. Adım: Kullanıcı kimlik doğrulamasını ve yetkilendirmesini etkinleştirin

Bu adımda, OAuth 2.0 yetkilendirmesini komut dosyasına dahil edeceğiz. Bu işlem, komut dosyasını çalıştıran kullanıcının, komut dosyasını kullanıcının hesabıyla ilişkilendirilen API isteklerini gerçekleştirmek üzere yetkilendirmesini sağlar.

2a Adımı: client_secrets.json dosyası oluşturun

YouTube Content ID API'nin kimlik doğrulaması için API Konsolu'ndan alınan bilgileri içeren bir client_secrets.json dosyası gerekir. Ayrıca uygulamanızı kaydetmeniz de gerekir. Kimlik doğrulamanın işleyiş şekliyle ilgili daha kapsamlı bir açıklama için kimlik doğrulama kılavuzuna göz atın.

 {
  "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 Adımı: Komut dosyanıza kimlik doğrulama kodu ekleyin

Kullanıcı kimlik doğrulamasını ve yetkilendirmeyi etkinleştirmek için aşağıdaki import ifadelerini eklemeniz gerekir:

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

Ardından, 2a adımında yapılandırılan istemci gizli anahtarlarını kullanarak bir FLOW nesnesi oluşturacağız. Kullanıcı, kullanıcı adına API istekleri göndermek üzere uygulamamıza yetki verirse sonuçta elde edilen kimlik bilgileri daha sonra kullanılmak üzere bir Storage nesnesinde depolanır. Kimlik bilgilerinin geçerliliği sona ererse kullanıcının uygulamamızı yeniden yetkilendirmesi gerekir.

main işlevinin sonuna aşağıdaki kodu ekleyin:

  # 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 Adımı: httplib2 nesnesi oluşturun ve kimlik bilgilerini ekleyin

Kullanıcı komut dosyamızı yetkilendirdikten sonra, API isteklerini işleyen bir httplib2.Http nesnesi oluşturur ve yetkilendirme kimlik bilgilerini bu nesneye ekleriz.

Aşağıdaki import (içe aktarma) ifadesini ekleyin:

  import httplib2

Ayrıca şu kodu main işlevinin sonuna ekleyin:

  # Create httplib2.Http object to handle HTTP requests and
  # attach auth credentials.
  http = httplib2.Http()
  http = credentials.authorize(http)

3. Adım: Bir hizmet edinin

Python istemci kitaplığının build işlevi, API ile etkileşim kurabilecek bir kaynak oluşturur. Kullanıcı uygulamamızı yetkilendirdikten sonra, ContentOwnerService ile etkileşim için yöntemler sunan service nesnesini oluştururuz.

Aşağıdaki import (içe aktarma) ifadesini ekleyin:

from apiclient.discovery import build

Şu kodu da main işlevinin sonuna ekleyin:

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

4. Adım: Bir API isteği yürütün

Şimdi bir hizmet isteği oluşturup bu isteği yürüteceğiz. Aşağıdaki kod, belirtilen içerik sahibiyle ilgili bilgileri getiren bir contentOwnersService.get() isteği oluşturup yürütür.

main işlevinin sonuna şu kodu ekleyin:

  # 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'])

Başvuruyu tamamla

Bu bölümde, bazı lisanslama bilgileri ve komut dosyasındaki ek yorumlarla birlikte uygulamanın tamamı gösterilmektedir. Programı iki şekilde yürütebilirsiniz:

  • Bu komut, gerekirse kimlik doğrulaması yapabileceğiniz ve uygulamaya API istekleri gönderme yetkisi verebileceğiniz bir tarayıcı penceresi açar. Uygulamayı yetkilendirirseniz kimlik bilgileri otomatik olarak komut dosyasına geri aktarılır.

    python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID.

    Not: Hesabınızın CONTENT_OWNER_ID değerini İYS hesabınızdaki Hesap Ayarları sayfasında bulabilirsiniz. Değer, söz konusu sayfadaki hesap bilgileri bölümünde Partner Code olarak listelenir.

  • Bu komut, tarayıcıda açabileceğiniz bir URL oluşturur ve yetkilendirme kodu girmenizi ister. URL'ye gittiğinizde bu sayfa, uygulamayı sizin adınıza API istekleri göndermesi için yetkilendirmenize olanak tanır. Bu yetkilendirmeyi verirseniz sayfada, yetkilendirme akışını tamamlamak için istemde girmeniz gereken yetkilendirme kodu görüntülenir.

    python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID --noauth_local_webserver.

    Not: oauth2client modülü, komut dosyasında parametreden bahsedilmemesine rağmen noauth_local_webserver parametresini tanır.

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)