Lưu ý: API Content ID của YouTube dành cho các đối tác nội dung của YouTube. Không phải nhà phát triển hoặc người dùng YouTube nào cũng có thể sử dụng API này. Nếu bạn không thấy Content ID API của YouTube là một trong các dịch vụ được liệt kê trong Bảng điều khiển API của Google, 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 một 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 nhất định. Bạn sẽ thấy mã mẫu hoàn chỉnh ở 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
Tạo tập lệnh để gửi 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 sau chấp nhận các tham số dòng lệnh sau và đặt giá trị trên biến FLAGS toàn cục:
- Tham số
content_owner_idlà 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_levelchỉ định cấp độ chi tiết ghi nhật ký cho tập lệnh. - Tham số
helpkhiến tập lệnh đưa 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ẽ kết hợp uỷ quyền OAuth 2.0 vào tập lệnh. Điều này cho phép người dùng chạy tập lệnh uỷ quyền cho 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ừ API Console để xác thực. Bạn cũng cần phải đăng ký đơn đăng ký của mình. Để biết nội dung giải thích đầy đủ hơn về cách hoạt động của quy trình 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
Để bật tính năng xác thực và uỷ quyền cho 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 khoá bí mật ứ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 của chúng tôi 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 cần phải uỷ quyền lại ứng dụng của chúng tôi 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 xác thực
Sau khi người dùng uỷ quyền cho tập lệnh của chúng ta, 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: Nhận dịch vụ
Hàm build của thư viện ứng dụng Python tạo một tài nguyên có thể tương tác với một API. Sau khi người dùng đã uỷ quyền cho ứng dụng của chúng ta, 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 sẽ tạo và thực thi yêu cầu contentOwnersService.get(). Yêu cầu này 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 cho thấy ứ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 để 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 được chuyển lại cho 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_IDcho 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ị này được liệt kê dưới dạngPartner Codetrong phần thông tin tài khoản trên trang đó. -
Lệnh này sẽ xuất ra một URL mà bạn có thể mở trong trình duyệt và cũng nhắc bạn nhập mã uỷ quyền. Khi bạn chuyển đến URL này, trang đó cho phép bạn uỷ quyền cho ứ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 theo 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
oauth2clientnhận dạng tham sốnoauth_local_webservermặ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)