Lưu ý: Content ID của YouTube dành cho các đối tác nội dung của YouTube và không phải nhà phát triển hoặc người dùng YouTube nào cũng có thể truy cập được. Nếu bạn không thấy YouTube Content ID API trong danh sách các dịch vụ trong Google API Console, hãy truy cập vào Trung tâm trợ giúp của YouTube để tìm hiểu thêm về Chương trình Đối tác YouTube.
Hướng dẫn từng bước này giải thích cách tạo tập lệnh kết nối với ContentOwnersService
và truy xuất thông tin về một chủ sở hữu nội dung cụ thể. Mã mẫu hoàn chỉnh sẽ được cung cấp ở cuối hướng dẫn. Mặc dù mã này được viết bằng Python, nhưng bạn cũng có thể sử dụng thư viện ứng dụng cho các ngôn ngữ lập trình phổ biến khác.
Yêu cầu
- Python 2.5 trở lên
- google-api-python-client
Xây dựng tập lệnh để gửi các yêu cầu API
Các bước sau đây giải thích cách tạo tập lệnh để gửi yêu cầu API Content ID của YouTube.
Bước 1: Tạo tập lệnh cơ bản
Tập lệnh bên dưới chấp nhận các tham số dòng lệnh sau và đặt giá trị cho biến FLAGS
toàn cục:
- Tham số
content_owner_id
là bắt buộc và xác định chủ sở hữu nội dung CMS mà bạn đang truy xuất thông tin. - Tham số
logging_level
chỉ định cấp chi tiết ghi nhật ký cho tập lệnh. - Tham số
help
khiến tập lệnh xuất ra danh sách các tham số mà tập lệnh hiểu được.
#!/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)
Bước 2: Bật tính năng xác thực và uỷ quyền người dùng
Trong bước này, chúng ta sẽ tích hợp việc uỷ quyền OAuth 2.0 vào tập lệnh. Điều này cho phép người dùng đang chạy tập lệnh cho phép tập lệnh thực hiện các yêu cầu API được phân bổ cho tài khoản của người dùng.
Bước 2a: Tạo tệp client_secrets.json
API Content ID của YouTube yêu cầu tệp client_secrets.json
chứa thông tin từ Bảng điều khiển API để thực hiện xác thực. Bạn cũng cần đăng ký ứng dụng của mình. Để xem giải thích đầy đủ hơn về cách hoạt động của tính năng xác thực, hãy xem hướng dẫn xác thực.
{ "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" } }
Bước 2b: Thêm mã xác thực vào tập lệnh của bạn
Để bật tính năng xác thực và uỷ quyền người dùng, bạn cần thêm các câu lệnh import
sau:
from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import run
Tiếp theo, chúng ta sẽ tạo một đối tượng FLOW
bằng mật khẩu ứng dụng khách được định cấu hình ở bước 2a. Nếu người dùng cho phép ứng dụng thay mặt người dùng gửi yêu cầu API, thì thông tin xác thực thu được sẽ được lưu trữ trong đối tượng Storage
để sử dụng sau này. Người dùng sẽ phải uỷ quyền lại ứng dụng nếu thông tin đăng nhập hết hạn.
Thêm mã sau vào cuối hàm 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)
Bước 2c: Tạo đối tượng httplib2
và đính kèm thông tin đăng nhập
Sau khi người dùng cho phép tập lệnh, chúng ta sẽ tạo một đối tượng httplib2.Http
để xử lý các yêu cầu API và đính kèm thông tin xác thực uỷ quyền vào đối tượng đó.
Thêm câu lệnh nhập sau:
import httplib2
Và thêm mã này vào cuối hàm main
:
# Create httplib2.Http object to handle HTTP requests and # attach auth credentials. http = httplib2.Http() http = credentials.authorize(http)
Bước 3: Yêu cầu dịch vụ
Hàm build
của thư viện ứng dụng Python tạo tài nguyên có thể tương tác với API. Sau khi người dùng đã uỷ quyền cho ứng dụng, chúng ta sẽ tạo đối tượng service
. Đối tượng này cung cấp các phương thức để tương tác với ContentOwnerService
.
Thêm câu lệnh nhập sau:
from apiclient.discovery import build
Và thêm mã này vào cuối hàm main
:
service = build("youtubePartner", "v1", http=http, static_discovery=False) contentOwnersService = service.contentOwners()
Bước 4: Thực thi yêu cầu API
Bây giờ, chúng ta sẽ tạo một yêu cầu dịch vụ và thực thi yêu cầu đó. Mã sau đây tạo và thực thi yêu cầu contentOwnersService.get()
để truy xuất thông tin về chủ sở hữu nội dung đã chỉ định.
Thêm mã này vào cuối hàm 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'])
Hoàn tất đơn đăng ký
Phần này hiển thị ứng dụng hoàn chỉnh cùng với một số thông tin cấp phép và nhận xét bổ sung trong tập lệnh. Có hai cách để chạy chương trình:
-
Lệnh này sẽ khởi chạy một cửa sổ trình duyệt mà qua đó bạn có thể xác thực (nếu cần) và cho phép ứng dụng gửi yêu cầu API. Nếu bạn cho phép ứng dụng, thông tin xác thực sẽ tự động chuyển tiếp trở lại tập lệnh.
python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID.
Lưu ý: Bạn có thể tìm thấy giá trị
CONTENT_OWNER_ID
cho tài khoản của mình trên trang Cài đặt tài khoản trong tài khoản CMS. Giá trị được liệt kê làPartner Code
trong phần thông tin tài khoản trên trang đó. -
Lệnh này sẽ tạo ra một URL mà bạn có thể mở trong trình duyệt, đồng thời nhắc bạn nhập mã uỷ quyền. Khi bạn truy cập vào URL đó, trang đó sẽ cho phép bạn cho phép ứng dụng thay mặt bạn gửi yêu cầu API. Nếu bạn cấp quyền đó, trang sẽ hiển thị mã uỷ quyền mà bạn cần nhập tại lời nhắc để hoàn tất quy trình uỷ quyền.
python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID --noauth_local_webserver.
Lưu ý: Mô-đun
oauth2client
nhận dạng tham sốnoauth_local_webserver
mặc dù tham số này không được đề cập trong tập lệnh.
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)