참고: YouTube Data API는 YouTube 콘텐츠 파트너가 사용하도록 설계되었으며 모든 개발자 또는 모든 YouTube 사용자가 액세스할 수 있는 것은 아닙니다. 액세스하려면 YouTube 콘텐츠 관리자 계정이 필요합니다. YouTube 콘텐츠 관리자 계정이 있지만 Google Cloud 콘솔에 YouTube Data API가 서비스로 표시되지 않는 경우 담당 파트너 관리자 또는 파트너 지원팀에 문의하세요.
이 단계별 튜토리얼에서는 ContentOwnersService에 연결하고 지정된 콘텐츠 소유자에 관한 정보를 가져오는 스크립트를 빌드하는 방법을 설명합니다. 튜토리얼 끝에 완전한 코드 샘플이 제공됩니다. 이 코드는 Python으로 작성되지만 기타 인기 프로그래밍 언어에 대한 클라이언트 라이브러리도 제공됩니다.
요구사항
- Python 3.7 이상
- google-api-python-client
스크립트를 빌드하여 API 요청 보내기
다음 단계에서는 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 승인을 통합합니다. 그러면 사용자가 스크립트를 실행하여 사용자의 계정에 따른 API 요청을 수행하도록 스크립트를 인증할 수 있습니다.
2a단계: client_secrets.json 파일 만들기
YouTube Data API는 인증을 수행하기 위해 Cloud 콘솔의 정보가 포함된 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" } }
2b단계: 스크립트에 인증 코드 추가
사용자 인증 및 승인을 사용 설정하려면 다음 import 문을 추가해야 합니다.
from datetime import datetime from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import argparser, run_flow
다음으로 2a단계에서 구성한 클라이언트 보안 비밀을 사용하여 FLOW 객체를 만듭니다. 사용자가 애플리케이션이 사용자 대신 API 요청을 제출하도록 승인하면 결과 사용자 인증 정보가 나중에 사용할 수 있도록 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)
2c단계: httplib2 객체 만들기 및 사용자 인증 정보 연결
사용자가 스크립트를 승인하면 API 요청을 처리하는 httplib2.Http 객체를 만들고 승인 사용자 인증 정보를 이 객체에 연결합니다.
다음 import 문을 추가합니다.
import httplib2
다음 코드를 main 함수의 끝에 추가합니다.
# Create httplib2.Http object to handle HTTP requests and # attach auth credentials. http = httplib2.Http() http = credentials.authorize(http)
3단계: 서비스 가져오기
Python 클라이언트 라이브러리의 build 함수는 API와 상호작용할 수 있는 리소스를 구성합니다. 사용자가 애플리케이션을 승인하면 ContentOwnerService와 상호작용하는 메서드를 제공하는 service 객체가 생성됩니다.
다음 import 문을 추가합니다.
from apiclient.discovery import build
다음 코드를 main 함수 끝에 추가합니다.
service = build("youtubePartner", "v1", http=http, static_discovery=False) contentOwnersService = service.contentOwners()
4단계: API 요청 실행
이제 서비스 요청을 만들고 실행합니다. 다음 코드는 지정된 콘텐츠 소유자에 관한 정보를 가져오는 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']))
전체 애플리케이션
이 섹션에서는 스크립트에 라이선스 정보와 추가 의견이 포함된 전체 애플리케이션을 보여줍니다. 프로그램을 실행하는 방법에는 2가지가 있습니다.
-
이 명령어는 필요한 경우 인증하고 애플리케이션이 API 요청을 제출하도록 승인할 수 있는 브라우저 창을 실행합니다. 애플리케이션을 인증하면 자격증명이 자동으로 스크립트에 다시 전달됩니다.
python3 yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID
참고: CMS 계정의 계정 설정 페이지에서 계정의
CONTENT_OWNER_ID값을 확인할 수 있습니다. 이 페이지의 계정 정보 섹션에 값이Partner Code로 표시됩니다. -
이 명령어는 브라우저에서 열 수 있는 URL을 출력하고 승인 코드를 입력하라는 메시지를 표시합니다. URL로 이동하면 해당 페이지에서 애플리케이션이 사용자를 대신하여 API 요청을 제출하도록 승인할 수 있습니다. 권한을 부여하면 페이지에 승인 코드가 표시되며 승인 절차를 완료하려면 메시지에 이 코드를 입력해야 합니다.
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()