개발자 가이드: Python

YouTube Data API를 사용하면 클라이언트 애플리케이션이 Google Data API 피드 형식으로 YouTube 콘텐츠를 검색하고 업데이트할 수 있습니다. 클라이언트 애플리케이션은 YouTube Data API 피드를 사용하여 동영상, 댓글, 응답, 재생목록, 사용자 프로필, 사용자 연락처를 가져오고 검색 및 업데이트할 수 있으며 특정 기준과 일치하는 동영상을 쿼리할 수 있습니다.

이 문서에서는 YouTube Data API의 기능에 관한 배경 정보를 제공할 뿐만 아니라 Python 클라이언트 라이브러리를 사용하여 API와 상호작용하는 예시를 제공합니다. Python 클라이언트 라이브러리를 사용하려면 Python 2.0 이상과 Element Tree, httplib, urllib 모듈이 필요합니다. 자세한 내용은 종속 항목 모듈을 참고하세요.

Python 클라이언트 라이브러리를 설정하는 데 도움이 필요한 경우 시작 가이드를 참고하세요. Python 클라이언트 라이브러리가 YouTube와 상호작용하는 데 사용하는 기본 프로토콜에 대해 자세히 알아보려면 개발자 가이드 프로토콜 페이지를 참고하세요.

이 문서에 관한 정보

잠재고객

이 문서는 Python 클라이언트 라이브러리를 사용하여 YouTube와 상호작용할 수 있는 클라이언트 애플리케이션을 작성하려는 프로그래머를 대상으로 합니다. 기본 데이터 API 상호작용의 일련의 예를 제공합니다.

YouTube Data API 참조 정보는 참조 가이드를 참고하세요.

이 문서에서는 여러분이 Google Data API 프로토콜의 일반적인 개념을 이해하고 Python으로 프로그래밍하는 방법을 알고 있다고 가정합니다.

Python 클래스 및 메서드에 관한 참조 정보는 소스 코드에 포함된 pyDocs (서비스 클래스데이터 클래스)를 참고하세요.

문서 구조

이 도움말에는 다음과 같은 섹션이 있습니다.

  • 인증 섹션에서는 API 작업을 특정 사용자 계정과 연결하는 데 사용할 수 있는 두 가지 인증 방법을 설명합니다. 이 섹션에서는 YouTube Data API와 다른 Google Data API의 인증 간의 차이점도 간략히 설명합니다. 이 문서 전체에서 특정 API 함수에 대한 설명은 함수에 사용자 인증이 필요한지 여부를 명확하게 나타냅니다. 일반적으로 동영상 또는 피드 데이터를 수정하는 모든 요청은 인증되어야 합니다. 공개 동영상에 대한 읽기 전용 요청에는 인증이 필요하지 않습니다.

  • 동영상 피드 및 항목 이해하기 섹션에서는 샘플 API 응답을 제공하고 동영상 목록 또는 검색 결과 집합에서 단일 동영상에 관한 정보를 추출하는 방법을 설명합니다. 이 섹션에서는 특정 동영상 항목에 관한 메타데이터에 액세스하는 방법도 설명합니다. 마지막으로 이 섹션에서는 개별 동영상 항목을 업데이트하는 메커니즘을 설명합니다.

  • 동영상 검색 및 가져오기 섹션에서는 YouTube 인기 동영상의 표준 피드와 같은 특정 동영상 목록을 가져오는 방법을 설명합니다. 다른 동영상 목록에는 특정 사용자가 업로드한 동영상과 특정 동영상과 관련된 동영상 목록이 포함됩니다. 이 섹션에서는 API를 사용하여 사용자가 특정 검색어 또는 카테고리를 기준으로 YouTube 동영상 보관함을 검색할 수 있도록 하는 방법도 설명합니다.

  • 동영상 업로드 섹션에서는 사용자가 애플리케이션에서 YouTube에 동영상을 업로드하도록 허용하는 두 가지 방법을 간단히 설명합니다. 또한 이 섹션에서는 다른 동영상에 대한 응답으로 동영상을 업로드하는 방법도 설명합니다.

  • 동영상 업데이트 및 삭제 섹션에서는 API를 사용하여 YouTube 동영상에 대한 정보를 업데이트하는 방법을 설명합니다. 또한 API를 사용하여 동영상을 삭제하는 방법도 설명합니다.

  • 커뮤니티 기능 사용 섹션에서는 사용자가 YouTube 동영상과 상호작용할 수 있는 API 함수를 설명합니다. 이 함수는 기존 동영상에 평점, 댓글 또는 불만사항을 게시해 달라는 요청을 설명합니다. API를 사용하여 동영상 댓글 목록을 가져올 수도 있습니다.

  • 동영상 저장 및 수집 섹션에서는 API를 사용하여 즐겨찾는 동영상, 동영상 재생목록, YouTube 채널 구독에 액세스하고 이를 만들고 업데이트하는 방법을 설명합니다. 동영상을 추가 및 삭제하여 동영상 재생목록과 즐겨찾기를 수정하는 방법도 보여줍니다.

  • 사용자 상호작용 사용 설정 섹션에서는 API를 사용하여 사용자 프로필을 검색하고 업데이트하는 방법을 설명합니다. 이 섹션에서는 사용자 연락처를 검색, 추가, 업데이트, 삭제하는 방법도 설명합니다.

시작하기

요구사항

클라이언트 애플리케이션은 YouTube Data API 피드를 사용하여 동영상, 댓글, 응답, 재생목록, 구독, 사용자 프로필 등을 검색, 검색, 업데이트할 수 있습니다.

이 문서에서는 YouTube Data API의 기능에 관한 배경 정보를 제공할 뿐만 아니라 Python 클라이언트 라이브러리를 사용하여 API와 상호작용하는 예시를 제공합니다. Python 클라이언트 라이브러리를 사용하려면 Python 2.2 이상과 Element Tree, httplib, urllib 모듈이 필요합니다. 자세한 내용은 종속 항목 모듈을 참고하세요.

환경 구성에 관한 자세한 내용은 시작 가이드를 참고하세요. Python 클라이언트 라이브러리에서 YouTube와 상호작용하는 데 사용하는 기본 프로토콜에 대해 자세히 알아보려면 개발자 가이드 프로토콜 페이지를 참고하세요.

아래의 샘플 코드 스니펫은 코드에 복사/붙여넣고 필요에 맞게 수정할 수 있습니다.

YouTube Data API로 작업을 실행하려면 먼저 아래와 같이 gdata.youtube.service.YouTubeService 객체를 초기화해야 합니다. 아래에 나열된 import 문은 gdata.mediagdata.geo 모듈에서 추가 가져오기를 자동으로 실행합니다. 공개 콘텐츠를 검색하는 작업 외의 모든 작업에는 인증이 필요합니다.

import gdata.youtube
import gdata.youtube.service

yt_service = gdata.youtube.service.YouTubeService()

# Turn on HTTPS/SSL access.
# Note: SSL is not available at this time for uploads.
yt_service.ssl = True

이 가이드의 대부분의 메서드 예시는 gdata.youtube.service.YouTubeService 인스턴스에서 작동합니다. 대화형 Python 인터프리터에서 인증되지 않은 요청을 테스트하는 것이 좋습니다.

참고: Python 클라이언트 라이브러리가 경로에 올바르게 추가되어야 합니다. 제공된 setup.py 스크립트를 실행하여 설치해야 합니다. 자세한 내용은 시작 가이드를 참고하세요.

인증

Python 클라이언트 라이브러리는 공개 피드 또는 비공개 피드와 함께 사용할 수 있습니다. 공개 피드는 읽기 전용이며 인증이 필요하지 않습니다. 비공개 피드를 사용하려면 YouTube 서버에 인증해야 합니다.

인증은 ClientLogin 인증 (데스크톱 앱의 경우) 또는 AuthSub 인증 (웹 애플리케이션의 경우)을 통해 실행할 수 있습니다.

개발자 키 및 클라이언트 ID 설정

개발자 키는 API 요청을 제출하는 YouTube 개발자를 식별합니다. 클라이언트 ID는 로깅 및 디버깅을 위해 애플리케이션을 식별합니다.

Python 클라이언트 라이브러리를 사용하여 API를 요청하면 X-GData-Key 요청 헤더가 개발자 키를 지정하는 데 사용되고 X-GData-Client 헤더가 클라이언트 ID를 지정하는 데 사용됩니다. 개발자 키와 클라이언트 ID는 사용 중인 인증 스킴과 관계없이 YouTubeService 객체에서 설정할 수 있습니다.

yt_service.developer_key = 'ABCxyz123...'
yt_service.client_id = 'My-Client_id'

YouTube 개발자 키를 가입해야 합니다.

웹 애플리케이션을 위한 AuthSub 인증

AuthSub 프록시 인증은 YouTube/Google 계정에 사용자를 인증해야 하는 웹 애플리케이션에서 사용됩니다. 운영자는 YouTube 사용자의 사용자 이름과 비밀번호에 액세스할 필요가 없습니다. 특수 AuthSub 토큰만 있으면 됩니다.

사용자가 애플리케이션을 처음 방문할 때는 아직 Google 서비스로 인증되지 않았습니다. 이 경우 사용자에게 Google로 연결되는 링크를 제공하여 애플리케이션의 YouTube 계정 액세스 요청을 승인하도록 해야 합니다. Python 클라이언트 라이브러리는 이 URL을 생성하는 함수를 제공합니다. 아래 코드는 AuthSubRequest 페이지로 연결되는 링크를 설정합니다.

def GetAuthSubUrl():
  next = 'http://www.example.com/video_upload.pyc'
  scope = 'http://gdata.youtube.com'
  secure = False
  session = True

yt_service = gdata.youtube.service.YouTubeService()
return yt_service.GenerateAuthSubURL(next, scope, secure, session)

authSubUrl = GetAuthSubUrl()
print '<a href="%s">Login to your Google account</a>' % authSubUrl

서비스 객체의 GenerateAuthSubURL 메서드로 전송된 매개변수를 확인합니다.

  • next: 사용자가 애플리케이션이 자신의 계정에 액세스하도록 승인한 후 YouTube에서 사용자를 리디렉션해야 하는 페이지의 URL입니다.
  • scope: 애플리케이션이 YouTube API 피드에만 액세스함을 나타냅니다.
  • secure: 반환된 토큰이 안전하지 않은 토큰임을 나타냅니다.
  • session: 이 토큰을 다중 사용 (세션) 토큰으로 교환할 수 있음을 나타냅니다.

반환된 URL은 다음과 같이 표시됩니다.

https://www.google.com/accounts/AuthSubRequest?scope=http%3A%2F%2Fgdata.youtube.com&session=1&secure=0&next=http%3A%2F%2Fwww.example.com%2Fvideo_upload.pyc

그러면 사용자는 링크를 따라 YouTube 계정에 로그인할 수 있습니다. 사용자가 애플리케이션이 자신의 계정에 액세스하도록 승인하면 next URL로 다시 리디렉션됩니다. URL에 일회용 토큰 값이 쿼리 매개변수로 추가됩니다. URL은 다음과 같이 표시됩니다.

http://www.example.com/video_upload.pyc?token=Abc123...

다음 섹션에서는 이 토큰을 업그레이드하는 방법을 보여줍니다. 아래 스니펫은 URL에서 이 토큰을 가져오는 방법 중 하나를 보여줍니다.

import cgi
parameters = cgi.FieldStorage()
authsub_token = parameters[[]'token' ]

세션 토큰으로 업그레이드

보안상의 이유로 이 토큰은 일회용으로만 사용되므로 이제 이 일회용 토큰을 세션 토큰으로 교환해야 합니다. 이 프로세스는 AuthSub 문서에 설명되어 있습니다. 다음 코드 스니펫은 토큰을 업그레이드하는 방법을 보여줍니다.

yt_service = gdata.youtube.service.YouTubeService()
yt_service.SetAuthSubToken(authsub_token)
yt_service.UpgradeToSessionToken()

이 토큰 값은 일회용 AuthSub 토큰을 나타냅니다. session = True가 위에 지정되었으므로 이 토큰은 AuthSubSessionToken 서비스를 호출하는 UpgradeToSessionToken 메서드를 사용하여 AuthSub 세션 토큰으로 교환할 수 있습니다.

이제 YouTubeService 객체가 완전히 인증되었으며 YouTube API로 추가 요청을 실행하는 데 사용할 수 있습니다. AuthSub 세션 토큰은 관리자가 취소 요청을 구체적으로 제출하거나 사용자가 YouTube 계정에서 승인된 사이트 페이지를 방문하여 액세스 권한을 취소하기로 결정하지 않는 한 만료되지 않습니다.

설치된 애플리케이션의 ClientLogin 인증

ClientLogin 인증은 사용자의 사용자 이름과 비밀번호를 저장하거나 쿼리할 수 있는 설치된 애플리케이션에서 사용됩니다. 이 인증 방식을 사용하려면 gdata.service.GDataService 클래스에서 상속받은 YouTubeServiceProgrammaticLogin 메서드를 호출하여 클라이언트가 인증 요청을 보내는 사용자의 ID와 비밀번호를 지정합니다.

yt_service = gdata.youtube.service.YouTubeService()
yt_service.email = 'jo@gmail.com'
yt_service.password = 'mypassword'
yt_service.source = 'my-example-application'
yt_service.ProgrammaticLogin()

사용자 인증 정보가 설정되면 YouTubeService 객체를 사용하여 모든 추가 요청을 처리할 수 있습니다. YouTube API에 업로드 및 모든 종류의 '쓰기' 요청 (댓글 추가 등)을 실행하려면 인증을 실행할 때 개발자 키와 클라이언트 ID도 yt_service 객체에 전달해야 합니다.

# A complete client login request
yt_service.email = 'jo@gmail.com'
yt_service.password = 'mypassword'
yt_service.source = 'my-example-application'
yt_service.developer_key = 'ABC123...'
yt_service.client_id = 'my-example-application'
yt_service.ProgrammaticLogin()

YouTubeService 객체는 developer_keyclient_id 속성이 설정되면 올바른 X-GData-KeyX-GData-Client 헤더를 자동으로 설정합니다.

참고: AuthSub 및 ClientLogin 메커니즘에 관한 자세한 내용은 Google Data API 인증 문서를 참고하세요.

동영상 피드 및 항목 이해하기

YouTube Data API는 표준 피드, 업로드, 구독, 즐겨찾기와 같이 동영상 목록을 나타내는 여러 동영상 피드를 제공합니다. 각 피드의 URL은 참조 가이드에 설명되어 있습니다.

동영상 피드 표시

YouTube API의 많은 피드는 동영상 항목으로 구성됩니다. 이러한 피드는 각각 여러 개의 gdata.youtube.YouTubeVideoEntry 객체를 포함하는 gdata.youtube.YouTubeVideoFeed 객체로 가장 간단하게 모델링할 수 있습니다. 각 동영상 항목은 YouTube의 정확히 하나의 동영상에 해당하며 동영상에 대한 정보를 포함합니다.

동영상 목록을 검색하는 기본 구조는 동영상 피드의 URL을 생성한 다음 다음 코드와 같이 항목을 한 번에 하나씩 처리하는 것입니다.

def GetAndPrintVideoFeed(uri):
  yt_service = gdata.youtube.service.YouTubeService()
  feed = yt_service.GetYouTubeVideoFeed(uri)
  for entry in feed.entry:
    PrintEntryDetails(entry) # full documentation for this function

동영상 검색 및 가져오기 섹션에서는 여러 일반적인 피드 URL과 다양한 동영상 피드를 가져오는 방법을 자세히 설명합니다.

특정 동영상 항목 검색

동영상 ID를 알고 있으면 특정 동영상 항목에 대한 정보만 가져올 수 있습니다. 항목 URL은 동영상 ID를 기반으로 합니다.

http://gdata.youtube.com/feeds/api/videos/videoID

다음 코드는 YouTube의 동영상에 해당하는 gdata.youtube.YouTubeVideoEntry를 가져옵니다.

entry = yt_service.GetYouTubeVideoEntry(video_id='the0KZLEacs')

동영상 항목 콘텐츠

gdata.youtube.YouTubeVideoEntry 객체에서 가져올 수 있는 메타데이터는 미리보기 이미지, 플레이어 URL, 동영상 길이 등 다양합니다. 다음 코드는 이러한 정보 중 일부를 가져오는 방법을 보여줍니다. Python 클라이언트 라이브러리는 XML 요소를 클래스에 매핑하여 이 기능의 대부분을 추상화합니다. YouTubeVideoEntry 항목에 관한 대부분의 중요한 정보는 항목 내의 media 속성 (gdata.media.Group 객체 포함)의 하위 요소 (XML media:group 요소를 나타냄)에서 가져올 수 있습니다. 다음은 동영상 메타데이터를 검색하는 방법의 예입니다.

def PrintEntryDetails(entry):
  print 'Video title: %s' % entry.media.title.text
  print 'Video published on: %s ' % entry.published.text
  print 'Video description: %s' % entry.media.description.text
  print 'Video category: %s' % entry.media.category[[]0].text
  print 'Video tags: %s' % entry.media.keywords.text
  print 'Video watch page: %s' % entry.media.player.url
  print 'Video flash player URL: %s' % entry.GetSwfUrl()
  print 'Video duration: %s' % entry.media.duration.seconds

  # non entry.media attributes
  print 'Video geo location: %s' % entry.geo.location()
  print 'Video view count: %s' % entry.statistics.view_count
  print 'Video rating: %s' % entry.rating.average

  # show alternate formats
  for alternate_format in entry.media.content:
    if 'isDefault' not in alternate_format.extension_attributes:
      print 'Alternate format: %s | url: %s ' % (alternate_format.type,
                                                 alternate_format.url)

  # show thumbnails
  for thumbnail in entry.media.thumbnail:
    print 'Thumbnail url: %s' % thumbnail.url

참고: 페이지에 플레이어와 함께 동영상을 삽입하는 데 필요한 정보를 생성하는 방법에 관한 자세한 내용은 프로토콜 가이드를 참고하세요.

동영상 검색 및 가져오기

표준 피드 검색 중

YouTube Data API는 YouTube에서 가장 인기 있는 동영상의 표준 피드를 제공합니다. 이전에는 이 API가 다른 표준 피드를 지원했으나 이후 지원 중단되었습니다. 자세한 내용은 개발자 가이드를 참고하세요.

YouTube 인기 동영상 피드의 URL은 다음과 같은 형식을 가집니다.

http://gdata.youtube.com/feeds/api/standardfeeds/most_popular

참고: http://gdata.youtube.com/feeds/api/standardfeeds/localeID/feedID 형식으로 localeID를 지정하여 언어별 표준 피드를 검색할 수도 있습니다. 예를 들어 일본에서 가장 인기 있는 동영상은 http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_popular입니다. 예상되는 localeID의 전체 목록은 참조 가이드 를 참고하세요.

def PrintVideoFeed(feed):
  for entry in feed.entry:
    PrintEntryDetails(entry)

def GetAndPrintFeedByUrl:
  yt_service = gdata.youtube.service.YouTubeService()

  # You can retrieve a YouTubeVideoFeed by passing in the URI
  uri = 'http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_popular'
  PrintVideoFeed(yt_service.GetYouTubeVideoFeed(uri))

특정 사용자가 업로드한 동영상 검색

각 YouTube 사용자는 http://gdata.youtube.com/feeds/api/users/username/uploads에 업로드한 동영상에 해당하는 연결된 동영상 피드를 보유합니다. 다음 코드는 사용자 업로드 피드를 가져와 표시하는 방법을 보여줍니다.

def GetAndPrintUserUploads(username):
  yt_service = gdata.youtube.service.YouTubeService()
  uri = 'http://gdata.youtube.com/feeds/api/users/%s/uploads' % username
  PrintVideoFeed(yt_service.GetYouTubeVideoFeed(uri))

참고: username 대신 'default' 문자열을 사용하여 현재 인증된 사용자의 동영상을 가져올 수도 있습니다.

관련 동영상을 가져오려면 gdata.youtube.YouTubeVideoEntry 객체의 동영상 ID를 gdata.youtube.service.YouTubeService 객체의 GetYouTubeRelatedVideoFeed 메서드에 전달합니다. 이렇게 하면 관련 항목이 포함된 YouTubeVideoFeed 객체가 검색됩니다.

related_feed = yt_service.GetYouTubeRelatedVideoFeed(video_id='abc123')

동영상 검색

YouTube Data API를 사용하면 특정 저자가 게시한 동영상 항목, 동영상 형식별 동영상 항목, 특정 키워드가 포함된 동영상 항목 등 지정된 기준과 일치하는 항목 집합을 요청할 수 있습니다. 이렇게 하려면 특정 검색 기준으로 gdata.service.YouTubeVideoQuery 객체를 만들고 이를 gdata.youtube.service.YouTubeServiceYouTubeQuery 메서드에 전달합니다.

아래 예는 제한된 동영상 (API에서는 '선정적이거나 노골적'이라고 함)을 포함하여 조회수를 기준으로 결과가 정렬된 검색 쿼리를 실행하는 방법을 보여줍니다.

def SearchAndPrint(search_terms):
  yt_service = gdata.youtube.service.YouTubeService()
  query = gdata.youtube.service.YouTubeVideoQuery()
  query.vq = search_terms
  query.orderby = 'viewCount'
  query.racy = 'include'
  feed = yt_service.YouTubeQuery(query)
  PrintVideoFeed(feed)

gdata.service.Query 클래스와 YouTubeVideoQuery와 같은 서브클래스는 피드 URL을 구성합니다. 위의 VideoQuery는 다음과 동일한 URL을 구성합니다.

http://gdata.youtube.com/feeds/api/videos?vq=<searchTerms>&racy=include&orderby=viewCount

다음은 검색 매개변수를 설정하는 데 사용되는 가장 일반적인 YouTubeVideoQuery 속성입니다.

author
항목의 작성자를 설정합니다. 저자는 YouTube 사용자 이름과 동의어입니다.
format
동영상 형식을 지정합니다. 숫자 매개변수를 사용하여 모바일 동영상 재생을 위한 두 가지 종류의 RTSP 스트리밍 URL 중 하나 또는 삽입 가능한 플래시 플레이어의 HTTP URL을 지정합니다.
racy
제한된 콘텐츠를 결과에 포함할지 여부를 나타냅니다. 'include' 또는 'exclude'라는 두 가지 매개변수만 허용합니다.
max_results
한 번에 반환할 최대 항목 수를 설정합니다.
start_index
가져올 첫 번째 결과의 1 기반 색인을 설정합니다 (페이징용).
orderby
항목을 나열할 순서를 설정합니다(예: relevance, viewCount, published, rating).
time
표준 피드 결과를 today, this_week, this_month 또는 all_time로 제한하는 기간을 설정합니다.
vq
검색어를 설정합니다. 제목, 태그, 설명과 같은 모든 동영상 메타데이터에서 지정된 문자열을 검색합니다.

참고: 쿼리 매개변수에 관한 자세한 내용은 YouTube Data API 참조 가이드Google Data API 참조 가이드를 참고하세요.

카테고리 및 키워드로 검색

검색 결과를 제한하여 지정된 카테고리 및 키워드와 일치하는 동영상만 표시할 수 있습니다. 참조 가이드에서는 사전 정의된 YouTube 카테고리 (예: 음악, 사람 및 블로그 등)와 사용자 정의 키워드 (태그)를 모두 지정하는 방법을 설명합니다.

다음 코드는 검색어를 소문자로 변경하여 키워드 (태그)를 사용하여 검색하는 방법을 보여줍니다. 참고: 일부 단어 (예: '코미디')는 YouTube 카테고리이자 키워드가 될 수 있으므로 카테고리 및 키워드 검색어에서는 대문자 단어 ('코미디')는 YouTube 카테고리를 나타내고 소문자 단어 ('코미디')는 키워드를 나타내는 규칙을 사용합니다.

def SearchAndPrintVideosByKeywords(list_of_search_terms):
  yt_service = gdata.youtube.service.YouTubeService()
  query = gdata.youtube.service.YouTubeVideoQuery()
  query.orderby = 'viewCount'
  query.racy = 'include'
  for search_term in list_of_search_terms:
    new_term = search_term.lower()
    query.categories.append('/%s' % new_term)
  feed = yt_service.YouTubeQuery(query)
  PrintVideoFeed(feed)

개발자 태그로 검색

개발자 태그는 개발자가 최종 사용자가 애플리케이션을 통해 업로드한 콘텐츠에 태그를 지정하는 데 사용할 수 있는 추가 숨겨진 키워드입니다. 개발자 태그는 업로드 중에 헤더에 설정된 개발자 키와 일치합니다. 이러한 키워드는 공개되지 않으며 동영상을 검색하는 데 사용될 수 있습니다. 특정 개발자 태그로 동영상을 검색하려면 개발자 키를 사용하여 일반 YouTube Data API 검색 요청을 전송합니다. 동영상이 일치해야 하는 카테고리 스키마와 개발자 태그를 지정해야 합니다. 아래 URL에서 개발자 태그(이 예에서는 'your_tag_here')와 일치하는 동영상 피드를 가져올 수 있습니다.

developer_tag_uri = 'http://gdata.youtube.com/feeds/videos/-/%7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007%2Fdevelopertags.cat%7Dyour_tag_here'
yt_service = gdata.youtube.service.YouTubeService()
PrintVideoFeed(yt_service.GetYouTubeVideoFeed(developer_tag_uri))

동영상 업로드하기

업로드 프로세스에 대한 개요는 프로토콜 가이드의 다이어그램을 검토하세요. 동영상은 다음 두 가지 방법 중 하나로 업로드할 수 있습니다.

  • 직접 업로드 방법을 통해 서버에서 직접 동영상을 업로드
  • 또는 먼저 메타데이터를 전송한 후 사용자가 브라우저 기반 업로드 방법을 통해 동영상을 YouTube에 직접 업로드하도록 합니다.

직접 업로드

동영상을 업로드하려면 먼저 새 gdata.youtube.YouTubeVideoEntry 객체를 생성하고 여기에 필수 메타데이터가 포함된 gdata.media.Group 객체를 전달해야 합니다. 다음 예는 다음 속성을 사용하여 Quicktime 동영상 'mytestmovie.mov'를 YouTube에 업로드하는 방법을 보여줍니다.

속성
제목My Test Movie
카테고리자동차
키워드자동차, 재미있음
설명내 설명
파일 이름mytestmovie.mov
파일 MIME 유형video/quicktime
동영상이 비공개인가요?거짓
동영상 위치37,-122 (위도,경도)
개발자 태그mydevelopertag, anotherdevelopertag

아래 코드는 업로드할 빈 YouTubeVideoEntry를 만듭니다. YouTubeServiceInsertVideoEntry 메서드에는 다음 매개변수가 필요합니다.

이 예에서는 yt_service 변수가 완전히 인증된 YouTubeService 객체를 참조한다고 가정합니다.

# prepare a media group object to hold our video's meta-data
my_media_group = gdata.media.Group(
  title=gdata.media.Title(text='My Test Movie'),
  description=gdata.media.Description(description_type='plain',
                                      text='My description'),
  keywords=gdata.media.Keywords(text='cars, funny'),
  category=[[]gdata.media.Category(
      text='Autos',
      scheme='http://gdata.youtube.com/schemas/2007/categories.cat',
      label='Autos')],
  player=None
)


# prepare a geo.where object to hold the geographical location
# of where the video was recorded
where = gdata.geo.Where()
where.set_location((37.0,-122.0))

# create the gdata.youtube.YouTubeVideoEntry to be uploaded
video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group,
                                              geo=where)

# set the path for the video file binary
video_file_location = '/path/to/my/file.mov'

new_entry = yt_service.InsertVideoEntry(video_entry, video_file_location)

선택적 개발자 태그로 동영상을 태그하려면 (자세한 내용은 개발자 태그로 검색 참고) InsertVideoEntry 호출을 실행하기 전에 AddDeveloperTags 메서드를 사용할 수 있습니다.

developer_tags = [[]'some_tag_01', 'another_tag']
video_entry.AddDeveloperTags(developer_tags)

참고: 동영상을 비공개로 업로드하려면 비공개 속성을 gdata.media.Group에 전달해야 합니다.

my_media_group = gdata.media.Group(
  title=gdata.media.Title(text='My Test Movie'),
  description=gdata.media.Description(description_type='plain',
                                      text='My description'),
  keywords=gdata.media.Keywords(text='cars, funny'),
  category=[[]gdata.media.Category(
      text='Autos',
      scheme='http://gdata.youtube.com/schemas/2007/categories.cat',
      label='Autos')],
  player=None,
  private=gdata.media.Private()
)

video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group)

# assuming that video_file_location points to a valid path
new_entry = yt_service.InsertVideoEntry(video_entry, video_file_location)

브라우저 기반 업로드

브라우저 기반 업로드는 동영상 메타데이터를 전송하는 데 사용하는 것과 동일한 요청으로 파일 바이너리를 업로드하지 않는다는 점을 제외하고 직접 업로드와 거의 동일하게 실행됩니다. 대신 메타데이터만 포함하는 YouTubeVideoEntry를 만듭니다. 그러면 이 동영상 항목이 YouTube API 서버의 특수 링크에 게시됩니다. XML 응답에는 tokenurl가 포함되며, 이를 사용하여 표준 HTML 양식을 사용하여 바이너리 파일을 업로드할 수 있습니다.

# create media group as usual
my_media_group = gdata.media.Group(
  title=gdata.media.Title(text='My Test Movie'),
  description=gdata.media.Description(description_type='plain',
                                      text='My description'),
  keywords=gdata.media.Keywords(text='cars, funny'),
  category=[[]gdata.media.Category(
      text='Autos',
      scheme='http://gdata.youtube.com/schemas/2007/categories.cat',
      label='Autos')],
  player=None
)

# create video entry as usual
video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group)

# upload meta data only
response = yt_service.GetFormUploadToken(video_entry)

# parse response tuple and use the variables to build a form (see next code snippet)
post_url = response[[]0]
youtube_token = response[[]1]

위 코드는 사용자의 브라우저에 표시할 HTML 양식을 구성하는 데 사용되는 링크와 토큰을 출력합니다. 아래에 간단한 양식 예시가 나와 있습니다. youtube_token는 위의 YouTubeVideoEntry에서 가져온 것처럼 반환된 토큰 요소의 콘텐츠를 나타냅니다. 사용자가 양식을 제출한 후 웹사이트로 리디렉션되도록 하려면 아래와 같이 post_urlnext 매개변수를 추가해야 합니다. 이 매개변수는 AuthSub 링크의 next 매개변수와 동일한 방식으로 작동합니다. 유일한 차이점은 여기서는 일회용 토큰 대신 statusid 변수가 URL 매개변수로 반환된다는 것입니다.

next = 'http://example.com/post_video_upload.pyc'

form = """<form action="%s?nexturl=%s" method="post" enctype="multipart/form-data">
          <input name="file" type="file"/>
          <input name="token" type="hidden" value="%s"/>
          <input value="Upload Video File" type="submit" />
          </form>""" % (post_url, next, youtube_token)

업로드에 성공하면 응답은 다음과 같습니다.

http://example.com/post_video_upload.pyc?status=200&id=ABC123

status 매개변수는 업로드 트랜잭션의 HTTP 트랜잭션 상태를 반환합니다. id 매개변수는 업로드된 동영상에 할당된 YouTube 동영상 ID를 반환합니다.

업로드 상태 확인 중

동영상을 업로드하면 인증된 사용자의 업로드 피드에 즉시 표시됩니다. 하지만 처리될 때까지 사이트에 공개되지는 않습니다. 거부되었거나 업로드에 실패한 동영상도 인증된 사용자의 업로드 피드에만 표시됩니다. 다음 코드는 YouTubeVideoEntry의 상태를 확인하여 아직 게시되지 않았거나 거부되었는지 확인합니다.

upload_status = yt_service.CheckUploadStatus(new_entry)

if upload_status is not None:
  video_upload_state = upload_status[[]0]
  detailed_message = upload_status[[]1]

동영상 업데이트 및 삭제

동영상 정보 업데이트

동영상 메타데이터를 업데이트하려면 YouTubeVideoEntry 객체를 업데이트한 다음 YouTubeService 객체의 UpdateVideoEntry 메서드를 사용하면 됩니다. 이 메서드는 업데이트된 메타데이터가 포함된 YouTubeVideoEntry를 매개변수로 사용합니다.

# assuming we have a video entry that was just posted in our 'new_entry' variable
new_entry.media.title.text = 'My Updated Video Title'
new_entry.media.description.text = 'Just updated'

updated_entry = yt_service.UpdateVideoEntry(new_entry)

동영상 삭제

동영상을 삭제하는 것은 매우 간단하며 YouTubeService 객체의 DeleteVideoEntry를 호출하기만 하면 됩니다.

response = yt_service.DeleteVideoEntry(entry_to_be_deleted)

if response:
  print 'Video successfully deleted!'

커뮤니티 기능 사용하기

평점 추가

동영상에 평점을 매기려면 YouTubeService 객체의 AddRating 메서드를 사용합니다. 자신의 동영상에는 평점을 줄 수 없으며 평점은 1~5점 (양 끝값 포함)이어야 합니다.

video_id_to_rate = 'Ncakifd_16k'
video_entry = yt_service.GetYouTubeVideoEntry(video_id=video_id_to_rate)
response = yt_service.AddRating(3, video_entry)

댓글

동영상의 댓글 검색

YouTubeVideoEntry 객체 또는 간단한 동영상 ID가 주어지면 YouTubeService 객체의 GetYouTubeVideoCommentFeed 메서드를 사용하여 동영상에 대한 댓글이 포함된 피드를 검색하고 출력할 수 있습니다. 결과 피드는 gdata.youtube.YouTubeCommentEntry 객체로 구성된 gdata.youtube.YouTubeCommentFeed입니다. 이 피드는 다른 피드와 마찬가지로 파싱할 수 있습니다.

video_id = 'ABC123...'
comment_feed = yt_service.GetYouTubeVideoCommentFeed(video_id=video_id)

for comment_entry in comment_feed.entry:
  print comment_entry.ToString()

의견 추가

새 주석을 추가하려면 YouTubeService 객체의 AddComment 메서드를 사용하면 됩니다. 이 메서드에는 주석을 달려는 전체 YouTubeVideoEntry 객체와 주석을 나타내는 문자열이 필요합니다.

my_comment = 'what a boring test video'
video_id = '9g6buYJTt_g'
video_entry = yt_service.GetYouTubeVideoEntry(video_id=video_id)
yt_service.AddComment(comment_text=my_comment, video_entry=video_entry)

동영상 응답

YouTube 동영상 응답은 두 번째 동영상에 답장으로 연결된 동영상입니다. 이 공지사항에 설명된 대로 동영상 응답 기능이 지원 중단되었습니다. 기존 동영상 응답은 계속 사용할 수 있지만, 동영상의 동영상 응답 목록을 검색하거나, 새 동영상 응답을 업로드하거나, 동영상 응답을 삭제하는 기능은 더 이상 지원되지 않습니다. 단, 동영상 응답에 사용된 동영상은 삭제할 수 있습니다. 따라서 이러한 함수도 API에서 더 이상 지원되지 않습니다.

이제 동영상 응답 작업에 대한 API 요청이 다음을 반환합니다.

  • 동영상에 대한 동영상 응답을 검색해 달라는 요청은 빈 목록을 반환합니다.
  • 동영상 응답 추가 요청은 403 HTTP 응답 코드를 반환합니다.
  • 동영상 응답 삭제 요청은 403 HTTP 응답 코드를 반환합니다.

동영상 신고

동영상에 대한 신고를 추가하려면 YouTubeService 객체의 AddComplaint 메서드를 사용합니다. 불만사항 용어가 유효한 카테고리여야 합니다. 자세한 내용은 프로토콜 가이드의 신고 추가 섹션을 참고하세요.

video_id_to_flag = 'Ncakifd_16k'
complaint_term = 'VIOLENCE'
complaint_text = ('Please ignore this complaint. '
                  'I\'m testing a YouTube API and needed to issue '
                  'a complaint to test the add complaint function. ')

response = yt_service.AddComplaint(complaint_text, complaint_term, video_id_to_flag)

동영상 저장 및 수집

즐겨찾는 동영상

사용자의 즐겨찾는 동영상 검색

YouTube 사용자는 시청한 동영상을 즐겨찾기로 표시할 수 있습니다. 사용자의 즐겨찾기 피드의 일반적인 위치는 다음 URL입니다.

http://gdata.youtube.com/feeds/api/users/username/favorites

사용자의 즐겨찾는 동영상을 가져오려면 YouTubeService 객체의 GetUserFavoritesFeed 메서드를 사용합니다. 이 메서드는 즐겨찾는 피드를 검색할 사용자의 YouTube 사용자 이름을 나타내는 문자열 매개변수를 선택적으로 취합니다.

favorite_feed = yt_service.GetUserFavoritesFeed(username='gdpython')

반환된 피드는 YouTubeVideoEntry 객체가 포함된 일반 동영상 피드입니다.

참고: 또는 default 문자열을 전달하여 현재 인증된 사용자의 즐겨찾기를 가져올 수 있습니다. 이는 사용자 이름이 제공되지 않은 경우 GetUserFavoritesFeed 메서드의 기본 동작입니다.

즐겨찾기 추가

즐겨찾는 동영상을 추가하려면 YouTubeService 객체의 AddVideoEntryToFavorites 메서드를 사용합니다. 매개변수는 추가할 YouTubeVideoEntry와 선택적으로 즐겨찾기에 추가할 사용자 이름입니다 (기본값은 현재 인증된 사용자).

video_id = 'Ncakifd_16k'
video_entry = yt_service.GetYouTubeVideoEntry(video_id=video_id)
response = yt_service.AddVideoEntryToFavorites(video_entry)

# The response, if successfully posted is a YouTubeVideoEntry
if isinstance(response, gdata.youtube.YouTubeVideoEntry):
  print 'Video successfully added to favorites'

즐겨찾기 삭제

즐겨찾기를 삭제하려면 YouTubeService 객체의 DeleteVideoEntryFromFavorites 메서드를 사용하면 됩니다.

video_id = 'Ncakifd_16k'
response = yt_service.DeleteVideoEntryFromFavorites(video_id)
if response is True:
  print 'Video deleted from favorites'

재생목록

각 YouTube 사용자에게는 사용자가 만든 모든 재생목록이 포함된 재생목록 피드가 있습니다. 그러면 각 재생목록에는 재생목록에 있는 모든 동영상의 피드가 있습니다.

사용자 재생목록 검색

사용자의 모든 재생목록 목록을 수동으로 가져오려면 다음 URL을 사용합니다.

http://gdata.youtube.com/feeds/api/users/username/playlists

Python 클라이언트 라이브러리를 사용하면 YouTubeService 객체의 GetYouTubePlaylistFeed 메서드를 사용할 수 있습니다.

playlist_feed = yt_service.GetYouTubePlaylistFeed(username='gdpython')

# instead of passing in a username, you can also pass the URI to the playlist feed:
playlist_feed = yt_service.GetYouTubePlaylistFeed(uri='http://gdata.youtube.com/feeds/api/users/default/playlists')

참고: 특정 사용자 이름 (예: 위 예시의 'gdpython')을 전달하는 대신 문자열 'default'을 전달하여 현재 인증된 사용자를 참조할 수도 있습니다.

gdata.youtube.YouTubePlaylistFeedgdata.youtube.YouTubePlaylistEntry 객체의 피드를 나타냅니다. 이는 사용자가 보유하고 있을 수 있는 개별 재생목록을 나타냅니다. 특정 재생목록의 동영상 항목은 gdata.youtube.YouTubePlaylistVideoEntry 객체로 표시됩니다. 이러한 객체는 몇 가지 예외를 제외하고 일반 gdata.youtube.YouTubeVideoEntry 객체와 매우 유사합니다. 동영상에 맞춤 제목과 설명을 적용할 수 있으며, 위치 입력란은 재생목록에서 동영상이 표시되는 위치를 나타냅니다.

재생목록 정보 가져오기

특정 재생목록을 나타내는 YouTubePlaylistEntry가 주어지면 YouTubePlaylistVideoEntry 객체가 포함된 YouTubePlaylistVideoFeed를 가져올 수 있습니다. 위에서 설명한 대로 이 객체는 재생목록의 개별 동영상을 나타냅니다 (선택사항인 맞춤 제목 및 설명 포함). 재생목록의 URI를 YouTubeService 객체의 GetYouTubePlaylistVideoFeed 메서드에 전달하여 이 피드를 가져올 수 있습니다.

# a typical playlist URI
playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'

playlist_video_feed = yt_service.GetYouTubePlaylistVideoFeed(uri=playlist_uri)

# iterate through the feed as you would with any other
for playlist_video_entry in playlist_video_feed.entry:
  print playlist_video_entry.title.text

재생목록 추가

새 재생목록을 추가하려면 YouTubeService 객체의 AddPlaylist 메서드를 사용하면 됩니다. 이 메서드는 playlist_title, playlist_description (둘 다 문자열) 매개변수와 재생목록을 비공개로 표시하려는 경우 True로 설정할 수 있는 선택적 불리언 매개변수를 사용합니다.

new_public_playlistentry = yt_service.AddPlaylist('my new playlist', 'a new playlist')

if isinstance(new_public_playlistentry, gdata.youtube.YouTubePlaylistEntry):
  print 'New playlist added'

# adding a private playlist
new_private_playlistentry = yt_service.AddPlaylist('new private playlist', 'a new private playlist', True)

if isinstance(new_private_playlistentry, gdata.youtube.YouTubePlaylistEntry):
  print 'New private playlist added'

재생목록 업데이트

재생목록을 업데이트하려면 YouTubeService 객체의 UpdatePlaylist 메서드를 사용합니다. 이 메서드는 업데이트할 재생목록의 ID, 새 제목, 새 설명, 재생목록을 비공개로 표시하는 불리언(선택사항), 재생목록을 소유한 사용자 이름을 나타내는 문자열(선택사항) 매개변수를 사용합니다. 문자열은 기본적으로 현재 인증된 사용자로 설정됩니다.

# here we are updating a public playlist with a new title while also making it private

# we assume that playlist_to_be_updated here represents a YouTubePlaylistEntry object
playlist_entry_id = playlist_to_be_updated.id.text.split('/')[[]-1]

# we want to keep the original description for the playlist so we store it first
original_description = playlist_to_be_updated.description.text

updated_playlist = yt_service.UpdatePlaylist(playlist_entry_id,
                                             'a new updated title',
                                             original_playlist_description,
                                             playlist_private=True)

재생목록에 동영상 추가

YouTubeService 객체의 AddPlaylistVideoEntryToPlaylist 메서드를 사용하여 재생목록에 동영상을 추가할 수 있습니다. 아래 코드는 맞춤 제목과 설명이 포함된 동영상을 재생목록에 추가합니다.

custom_video_title = 'my test video on my test playlist'
custom_video_description = 'this is a test video on my test playlist'
video_id = 'Ncakifd_16k'
playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'

playlist_video_entry = yt_service.AddPlaylistVideoEntryToPlaylist(
    playlist_uri, video_id, custom_video_title, custom_video_description)

if isinstance(playlist_video_entry, gdata.youtube.YouTubePlaylistVideoEntry):
  print 'Video added'

참고: 맞춤 제목과 설명은 필수가 아니며 지정하지 않으면 동영상의 실제 제목과 설명이 사용됩니다.

재생목록에서 동영상 정보 수정하기

YouTubeService 객체의 UpdatePlaylistVideoEntryMetaData 메서드를 사용하여 YouTubePlaylistVideoEntry의 메타데이터를 변경합니다. 아래 예에서는 동영상에 새 맞춤 제목을 지정하고 재생목록의 첫 번째 위치 (위치 1)로 이동하기로 합니다.

playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'
playlist_entry_id = 'B0F29389E537F888'

new_video_title = 'a useful video'
new_video_description = 'updated video description'

updated_playlist_video_entry = yt_service.UpdatePlaylistVideoEntryMetaData(
    playlist_uri, playlist_entry_id, new_video_title, new_video_description, 1)

참고: 재생목록에서 동영상의 설명과 제목을 원래 메타데이터로 되돌리려면 제목과 설명 모두에 NULL를 전달하면 됩니다.

재생목록에서 동영상 삭제

재생목록에서 동영상을 삭제하려면 YouTubeService 객체의 DeletePlaylistVideoEntry 메서드를 사용합니다. 이 메서드에는 삭제할 항목이 포함된 재생목록의 URI와 항목의 ID가 필요합니다.

playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'
playlist_entry_id = 'B0F29389E537F888'
response = yt_service.DeletePlaylistVideoEntry(playlist_uri,
                                               playlist_entry_id)
if response is True:
  print 'Entry successfully deleted'

재생목록 삭제

재생목록을 삭제하려면 YouTubeService 객체의 DeletePlaylist 메서드를 사용하여 삭제할 재생목록의 URI를 전달하면 됩니다.

playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'
response = yt_service.DeletePlaylist(playlist_uri)

if response is True:
  print 'Playlist successfully deleted'

구독

특정 사용자가 구독 중인 채널, 검색어, 즐겨찾기 목록을 가져오려면 다음 URI를 사용하세요.

http://gdata.youtube.com/feeds/api/users/username/subscriptions

참고: 또는 default 문자열을 전달하여 현재 인증된 사용자의 즐겨찾기를 가져올 수 있습니다.

사용자 구독 검색

다음 코드는 특정 사용자의 정기 결제 목록을 검색하고 출력하는 방법을 보여줍니다. 구독은 gdata.youtube.YouTubeSubscriptionEntry 객체로 구성된 gdata.youtube.YouTubeSubscriptionFeed로 표시됩니다. 구독을 검색하려면 YouTubeService 객체의 GetYouTubeSubscriptionFeed 메서드를 사용하여 구독 피드의 URI 또는 구독 피드를 검색할 사용자 이름을 전달합니다. 사용자 이름 매개변수는 현재 인증된 사용자로 기본 설정됩니다.

subscription_feed = yt_service.GetYouTubeSubscriptionFeed(username='gdpython')

if isinstance(subscription_feed, gdata.youtube.YouTubeSubscriptionFeed)):
  # given a YouTubeSubscriptionEntry we can determine it's type (channel, favorite, or query)
  for entry in subscription_feed.entry:
    print entry.GetSubscriptionType()

구독 추가

인증된 사용자의 구독 피드에 새 YouTubeSubsciptionEntry를 삽입하여 새 구독을 만들 수 있습니다. 사용자의 채널 구독 (AddSubscriptionToChannel 사용), 사용자의 즐겨찾기 구독 (AddSubscriptionToFavorites 사용), 특정 키워드 구독 (AddSubscriptionToQuery 사용) 등 세 가지 유형의 구독을 만들 수 있습니다. 다음 코드는 인증된 사용자를 'GoogleDevelopers' 채널에 구독합니다.

new_subscription = yt_service.AddSubscriptionToChannel(
      username_to_subscribe_to='GoogleDevelopers')

if isinstance(new_subscription, gdata.youtube.YouTubeSubscriptionEntry):
  print 'New subscription added'

'GoogleDevelopers' 사용자의 즐겨찾기를 구독할 수도 있습니다.

new_subscription = yt_service.AddSubscriptionToFavorites(
    username='GoogleDevelopers')
if isinstance(new_subscription, gdata.youtube.YouTubeSubscriptionEntry):
  print 'New subscription added'

마지막으로 특정 검색어를 구독할 수도 있습니다. 여기서는 'python' 태그가 지정된 동영상에 대한 검색어를 구독합니다.

new_subscription = yt_service.AddSubscriptionToQuery(query='python')

if isinstance(new_subscription, gdata.youtube.YouTubeSubscriptionEntry):
  print 'New subscription added'

구독 삭제

사용자 구독을 삭제하려면 YouTubeService 객체의 DeleteSubscription 메서드를 사용합니다.

sample_subscription_uri = ('http://gdata.youtube.com/feeds/api/users/'
                           'gdpython/subscriptions/c0c77ca6102a7479')

response = yt_service.DeleteSubscription(sample_subscription_uri)

if response is True:
  print 'Subscription successfully deleted'

사용자 상호작용 사용 설정

사용자 프로필

사용자 프로필 검색

사용자의 YouTube 프로필을 직접 가져오려면 다음 URI를 사용합니다.

http://gdata.youtube.com/feeds/api/users/username

YouTubeService 객체의 GetYouTubeUserEntry 메서드를 사용하여 gdata.youtube.YouTubeUserEntry를 가져올 수 있습니다.

user_entry = yt_service.GetYouTubeUserEntry(username='gdpython')

# we can then write a helper function to print out the user details
def PrintUserEntry(entry):
  # print required fields where we know there will be information
  print 'URI: %s\n' % entry.id.text
  print 'Age: %s\n' % entry.age.text
  print 'Gender: %s\n' % entry.gender.text
  print 'Location: %s\n' % entry.location.text

  # check if there is information in the other fields and if so print it
  if user.first_name: 
    print 'First Name: %s\n' % user.first_name.text
  if user.last_name:
    print 'Last Name: %s\n' % user.last_name.text
  if user.relationship:
    print 'Relationship: %s\n' % user.relationship.text
  if user.description:
    print 'About me: %s\n' % user.description.text
  for link in user.link:
    if link.rel == 'related':
      print 'Website: %s\n' % link.href
  if user.company:
    print 'Company: %s\n' % user.company.text
  if user.occupation:
    print 'Occupation: %s\n' % user.occupation.text
  if user.school:
    print 'School: %s\n' % user.school.text
  if user.hobbies:
    print 'Hobbies: %s\n' % user.hobbies.text
  if user.movies:
    print 'Movies: %s\n' % user.movies.text
  if user.music:
    print 'Music: %s\n' % user.music.text
  if user.books:
    print 'Books: %s\n' % user.books.text
  if user.hometown:
    print 'Hometown: %s\n' % user.hometown.text

연락처

특정 사용자의 연락처 목록은 다음 URL에서 가져올 수 있습니다.

http://gdata.youtube.com/feeds/api/users/username/contacts

사용자 연락처 검색

YouTubeService 객체의 GetYouTubeContactFeed 메서드를 사용하여 gdata.youtube.YouTubeContactEntry 객체로 구성된 gdata.youtube.YouTubeContactFeed를 가져올 수 있습니다.

contact_feed = yt_service.GetYouTubeContactFeed(username='GoogleDevelopers')
for entry in contact_feed.entry:
  print entry.title.text
  # find the apprpriate category element to find out the contact type
  for category in entry.category:
    if category.scheme == 'http://gdata.youtube.com/schemas/2007/contact.cat':
      print category.term

연락처 추가

사용자 연락처 피드에 새 연락처를 추가하려면 YouTubeService 객체의 AddContact 메서드를 사용합니다.

new_contact = yt_service.AddContact(contact_username='GoogleDevelopers')

if isinstance(new_contact, gdata.youtube.YouTubeContactEntry)
  print 'New contact added'

연락처 수락/거부

연락처를 업데이트하려면 YouTubeService 객체의 UpdateContact 메서드를 사용합니다. 이 메서드는 연락처 요청을 수락/거부하고 연락처를 '친구' 또는 '가족'으로 분류하는 데 사용할 수 있습니다. 아래 예에서는 연락처를 수락한 후 카테고리를 '가족'으로 설정합니다.

# in this case user 'gdpython' has requested to be our contact
#so the original contact status is 'pending'
updated_contact = yt_service.UpdateContact('gdpython', 'accepted', 'Family')

if isinstance(updated_contact, gdata.youtube.YouTubeContactEntry)
  print 'New contact added'

연락처 삭제

연락처를 삭제하려면 YouTubeService 객체의 DeleteContact 메서드를 사용하여 삭제하려는 연락처의 사용자 이름을 전달합니다.

response = yt_service.DeleteContact(contact_username='gdpython')

if response is True:
  print 'Contact deleted'

맨 위로