Catatan: YouTube Content ID API ditujukan untuk digunakan oleh partner konten YouTube dan tidak dapat diakses oleh semua developer atau pengguna YouTube. Jika Anda tidak melihat YouTube Content ID API sebagai salah satu layanan yang tercantum di Konsol API Google, lihat Pusat Bantuan YouTube untuk mempelajari Program Partner YouTube lebih lanjut.
Tutorial langkah demi langkah ini menjelaskan cara membuat skrip yang terhubung ke ContentOwnersService
dan mengambil informasi tentang pemilik konten tertentu. Contoh kode lengkap diberikan di akhir tutorial. Meskipun kode ini ditulis dalam Python, library klien untuk bahasa pemrograman populer lainnya juga tersedia.
Persyaratan
- Python 2.5 atau yang lebih baru
- google-api-python-client
Membuat skrip untuk mengirim permintaan API
Langkah-langkah berikut menjelaskan cara membuat skrip untuk mengirimkan permintaan Content ID API YouTube.
Langkah 1: Buat skrip dasar
Skrip di bawah menerima parameter command line berikut dan menetapkan nilai pada variabel FLAGS
global:
- Parameter
content_owner_id
diperlukan dan mengidentifikasi pemilik konten CMS yang informasinya Anda ambil. - Parameter
logging_level
menentukan tingkat detail logging untuk skrip. - Parameter
help
menyebabkan skrip menampilkan daftar parameter yang dipahami.
#!/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)
Langkah 2: Aktifkan autentikasi dan otorisasi pengguna
Pada langkah ini, kami akan menerapkan otorisasi OAuth 2.0 ke dalam skrip. Hal ini memungkinkan pengguna yang menjalankan skrip untuk memberikan otorisasi pada skrip agar dapat melakukan permintaan API yang diatribusikan ke akun pengguna.
Langkah 2a: Buat file client_secrets.json
YouTube Content ID API memerlukan file client_secrets.json
, yang berisi informasi dari Konsol API, untuk melakukan autentikasi. Anda juga harus mendaftarkan aplikasi Anda. Untuk penjelasan yang lebih lengkap tentang cara kerja autentikasi, lihat panduan autentikasi.
{ "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" } }
Langkah 2b: Tambahkan kode autentikasi ke skrip Anda
Untuk mengaktifkan autentikasi dan otorisasi pengguna, Anda perlu menambahkan pernyataan import
berikut:
from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import run
Selanjutnya, kita akan membuat objek FLOW
menggunakan rahasia klien yang dikonfigurasi di langkah 2a. Jika pengguna mengizinkan aplikasi kita untuk mengirimkan permintaan API atas nama pengguna, kredensial yang dihasilkan akan disimpan dalam objek Storage
untuk digunakan nanti. Pengguna perlu memberikan otorisasi ulang ke aplikasi kita jika masa berlaku kredensial berakhir.
Tambahkan kode berikut ke bagian akhir fungsi 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)
Langkah 2c: Buat objek httplib2
dan lampirkan kredensial
Setelah pengguna memberikan otorisasi pada skrip, kita akan membuat objek httplib2.Http
, yang menangani permintaan API, dan melampirkan kredensial otorisasi ke objek tersebut.
Tambahkan pernyataan import berikut:
import httplib2
Dan tambahkan kode ini ke bagian akhir fungsi main
:
# Create httplib2.Http object to handle HTTP requests and # attach auth credentials. http = httplib2.Http() http = credentials.authorize(http)
Langkah 3: Dapatkan layanan
Fungsi build
library klien Python membuat resource yang dapat berinteraksi dengan API. Setelah pengguna memberi aplikasi otorisasi, kita membuat objek service
, yang menyediakan metode untuk berinteraksi dengan ContentOwnerService
.
Tambahkan pernyataan import berikut:
from apiclient.discovery import build
Dan tambahkan kode ini di akhir fungsi main
:
service = build("youtubePartner", "v1", http=http, static_discovery=False) contentOwnersService = service.contentOwners()
Langkah 4: Jalankan permintaan API
Sekarang, kita akan membuat permintaan layanan dan menjalankannya. Kode berikut membuat dan menjalankan permintaan contentOwnersService.get()
, yang mengambil informasi tentang pemilik konten yang ditentukan.
Tambahkan kode ini di akhir fungsi 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'])
Lengkapi permohonan
Bagian ini menampilkan aplikasi lengkap dengan beberapa info pemberian lisensi dan komentar tambahan dalam skrip. Ada dua cara untuk menjalankan program:
-
Perintah ini meluncurkan jendela browser yang dapat Anda gunakan untuk mengautentikasi, jika perlu, dan mengizinkan aplikasi untuk mengirimkan permintaan API. Jika Anda mengizinkan aplikasi, kredensial akan otomatis diteruskan kembali ke skrip.
python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID.
Catatan: Anda dapat menemukan nilai
CONTENT_OWNER_ID
untuk akun di halaman Setelan Akun pada akun CMS. Nilai dicantumkan sebagaiPartner Code
di bagian informasi akun pada halaman tersebut. -
Perintah ini menghasilkan URL yang dapat Anda buka di browser dan juga meminta Anda untuk memasukkan kode otorisasi. Saat membuka URL, Anda dapat mengizinkan aplikasi mengirimkan permintaan API atas nama Anda. Jika Anda memberikan otorisasi tersebut, halaman akan menampilkan kode otorisasi yang harus Anda masukkan saat diminta untuk menyelesaikan alur otorisasi.
python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID --noauth_local_webserver.
Catatan: Modul
oauth2client
mengenali parameternoauth_local_webserver
meskipun parameter tersebut tidak disebutkan dalam skrip.
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)