첫 번째 요청 보내기

참고: YouTube Content ID API는 YouTube 콘텐츠 파트너가 사용하도록 설계되었으며 일부 개발자나 YouTube 사용자는 액세스할 수 없습니다. Google API 콘솔에 나열된 서비스 중 하나로 YouTube Content ID API가 표시되지 않으면 YouTube 고객센터에서 YouTube 파트너 프로그램에 대해 자세히 알아보세요.

이 단계별 튜토리얼에서는 ContentOwnersService에 연결하여 지정된 콘텐츠 소유자에 관한 정보를 가져오는 스크립트를 빌드하는 방법을 설명합니다. 전체 코드 샘플은 가이드의 끝부분에서 제공됩니다. 이 코드는 Python으로 작성되지만 기타 인기 프로그래밍 언어에 대한 클라이언트 라이브러리도 제공됩니다.

요구사항

스크립트를 빌드하여 API 요청 보내기

다음 단계에서는 스크립트를 구축하여 YouTube Content ID API 요청을 보내는 방법에 대해 설명합니다.

1단계: 기본 스크립트 만들기

아래 스크립트는 다음 명령줄 매개변수를 허용하며 전역 FLAGS 변수에서 값을 설정합니다.

  • content_owner_id 매개변수는 필수 항목이며 정보를 검색하려는 CMS 콘텐츠 소유자를 식별합니다.
  • logging_level 매개변수는 스크립트의 로깅 세부정보 수준을 지정합니다.
  • help 매개변수를 사용하면 스크립트가 이해할 수 있는 매개변수 목록을 출력합니다.
#!/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단계: 사용자 인증 및 승인 사용 설정

이 단계에서는 OAuth 2.0 승인을 스크립트에 통합합니다. 그러면 사용자가 스크립트를 실행하여 사용자의 계정에 따른 API 요청을 수행하도록 스크립트를 인증할 수 있습니다.

2a단계: client_secrets.json 파일 만들기

YouTube Content ID API에서 인증을 수행하려면 API 콘솔의 정보가 포함된 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 oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run

다음으로, 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, storage)

단계 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=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'])

전체 애플리케이션

이 섹션에서는 일부 라이선스 정보와 스크립트의 추가 주석이 포함된 전체 애플리케이션을 보여줍니다. 프로그램을 실행하는 방법에는 2가지가 있습니다.

  • 이 명령은 필요한 경우 인증할 수 있는 브라우저 창을 실행하고 애플리케이션이 API 요청을 제출하도록 인증합니다. 애플리케이션을 인증하면 자격증명이 자동으로 스크립트에 다시 전달됩니다.

    python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID.

    참고: 계정에 대한 CONTENT_OWNER_ID 값은 CMS 계정의 계정 설정 페이지에서 확인할 수 있습니다. 값은 페이지의 계정 정보 섹션에서 Partner Code로 표시됩니다.

  • 이 명령은 브라우저에서 열 수 있는 URL을 출력하고 승인 코드를 입력하라는 메시지도 표시합니다. URL로 이동하면 해당 페이지에서 사용자를 대신하여 API 요청을 제출하도록 애플리케이션을 승인할 수 있습니다. 권한을 부여하면 페이지에 승인 코드가 표시되며 승인 절차를 완료하려면 메시지에 이 코드를 입력해야 합니다.

    python 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/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)