開發人員指南: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 互動時使用的基礎通訊協定,請參閱開發人員指南通訊協定頁面

您可以將下方的程式碼片段複製/貼上至程式碼中,並視需求進行修改。

您必須先初始化 gdata.youtube.service.YouTubeService 物件,才能使用 YouTube Data API 執行任何作業,如以下所示。下列 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 驗證

需要驗證使用者 YouTube/Google 帳戶的網頁應用程式,會使用 AuthSub 代理驗證。操作員不需要存取 YouTube 使用者的使用者名稱和密碼,只需要特殊的 AuthSub 權杖。

使用者首次造訪應用程式時,尚未透過 Google 服務進行驗證。在這種情況下,您必須提供連結,引導使用者前往 Google 授權應用程式存取其 YouTube 帳戶的權限。Python 用戶端程式庫提供產生這個網址的函式。下方程式碼會設定連結至 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 應將使用者重新導向至的網頁網址。
  • scope:表示應用程式只會存取 YouTube API 動態消息。
  • secure:表示傳回的權杖不是安全權杖。
  • session:表示此符記可兌換成多用途 (工作階段) 符記。

傳回的網址如下所示:

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 網址。網址會附加單次使用權杖值做為查詢參數。網址格式如下:

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

下一節將說明如何升級此權杖。下列程式碼片段示範從網址擷取此符記的其中一種方法:

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,因此可以使用 UpgradeToSessionToken 方法 (會呼叫 AuthSubSessionToken 服務) 交換此權杖,以取得 AuthSub 工作階段權杖。

您的 YouTubeService 物件現在已完成驗證,可以用於透過 YouTube API 執行所有後續要求。除非您明確提出撤銷要求,或是使用者決定在 YouTube 帳戶中造訪「已授權網站」頁面撤銷存取權,否則 AuthSub 工作階段權杖不會到期。

已安裝應用程式的 ClientLogin 驗證

用戶端登入驗證機制可用於已安裝的應用程式,這些應用程式可儲存或查詢使用者的使用者名稱和密碼。如要使用這類驗證方式,請叫用 YouTubeService 繼承自 gdata.service.GDataService 類別的 ProgrammaticLogin 方法,指定用戶端代表哪位使用者傳送驗證要求的 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()

設定 developer_keyclient_id 屬性後,YouTubeService 物件會自動設定正確的 X-GData-KeyX-GData-Client 標頭。

注意:如要進一步瞭解 AuthSub 和 ClientLogin 機制,請參閱 Google Data API 驗證說明文件

瞭解影片動態饋給和項目

YouTube Data API 提供多種影片動態,代表影片清單,例如標準動態、上傳內容、訂閱內容和收藏內容。如要瞭解各動態饋給的網址,請參閱參考指南

顯示影片動態

YouTube API 中的許多動態消息都包含影片項目。這些動態饋給最簡單的建模方式是 gdata.youtube.YouTubeVideoFeed 物件,每個物件都包含多個 gdata.youtube.YouTubeVideoEntry 物件。每個影片項目都會對應至 YouTube 上的一支影片,並包含影片相關資訊。

擷取影片清單的基本結構是建立影片動態消息的網址,然後逐一處理項目,類似於以下程式碼:

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

請參閱「擷取及搜尋影片」一節,瞭解許多常見的動態饋給網址,以及如何擷取各種影片動態饋給。

擷取特定影片項目

只要知道影片 ID,您就能擷取特定影片項目的資訊。輸入網址是以影片 ID 為依據:

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

以下程式碼會擷取 YouTube 影片對應的 gdata.youtube.YouTubeVideoEntry

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

影片內容

您可以從 gdata.youtube.YouTubeVideoEntry 物件擷取許多中繼資料,例如縮圖、播放器網址和影片時間長度。以下程式碼示範如何取得部分資訊。Python 用戶端程式庫會將 XML 元素對應至類別,藉此抽象化大部分的功能。YouTubeVideoEntry 項目的大部分重要資訊,可從該項目 (代表 XML media:group 元素) 內的 media 屬性 (包含 gdata.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 最受歡迎影片動態消息的網址格式如下:

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

注意:您也可以指定 localeID 格式 (http://gdata.youtube.com/feeds/api/standardfeeds/localeID/feedID),擷取特定語言代碼的標準動態饋給。舉例來說,日本最熱門的影片會是: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))

注意:您也可以使用字串「default」取代 username,為目前已驗證的使用者擷取影片。

如要擷取相關影片,請將 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 中稱為「Racy」):

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 等子類別負責建構動態饋給網址。上方顯示的 VideoQuery 會建構等同於下列網址的網址:

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

以下是一些最常見的 YouTubeVideoQuery 屬性,可用於設定搜尋參數

author
可設定項目的作者。作者與 YouTube 使用者名稱相同。
format
指定影片格式。接受數值參數,指定行動裝置影片播放的兩種 RTSP 串流網址之一,或嵌入式 Flash 播放器的 HTTP 網址。
racy
指出結果是否應包含受限內容。只接受兩個參數:「include」或「exclude」。
max_results
設定一次傳回的項目數量上限。
start_index
設定要擷取的第一個結果的索引 (以 1 為起點) (用於分頁)。
orderby
設定清單項目的排序順序,例如依據 relevanceviewCountpublishedrating 排序。
time
設定時間範圍,將標準動態饋給結果限制在 todaythis_weekthis_monthall_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 搜尋要求。請務必指定影片必須相符的類別配置和開發人員標記。您可以透過下列網址,擷取與開發人員代碼相符的影片動態饋給 (在本例中為「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 類型影片/quicktime
影片是否為私人影片?false
影片位置37,-122 (lat,long)
開發人員代碼mydevelopertag, anotherdevelopertag

以下程式碼會建立要上傳的空白 YouTubeVideoEntryYouTubeService 上的 InsertVideoEntry 方法需要下列參數:

請注意,這些範例假設 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 擷取。為了讓使用者在提交表單後重新導向至您的網站,請務必將 next 參數附加至 post_url (如下所示),這會與 AuthSub 連結的 next 參數運作方式相同。唯一的差異在於,此處會以 statusid 變數的形式傳回網址參數,而非單次使用權杖。

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.YouTubeCommentFeed,其中包含 gdata.youtube.YouTubeCommentEntry 物件。動態饋給可像其他動態饋給一樣進行剖析:

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 影片回應是指與其他影片相關聯的影片,如這篇公告所述,我們已淘汰影片回應功能。雖然現有的影片回應仍可使用,但 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 使用者可以選擇將觀看的影片標示為「我的最愛」。使用者最愛動態的一般位置如下網址。

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 使用者都有播放清單動態饋給,其中包含使用者建立的所有播放清單。每個播放清單都會提供其內含的所有影片動態消息。

擷取使用者播放清單

如要手動擷取使用者的所有播放清單清單,請使用下列網址:

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')

注意:您也可以傳入字串 'default',以便參照目前已經驗證的使用者,而非傳入特定使用者名稱 (例如上述範例中的「gdpython」)。

gdata.youtube.YouTubePlaylistFeed 代表 gdata.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.YouTubeSubscriptionFeed 表示,其中包含 gdata.youtube.YouTubeSubscriptionEntry 物件。如要擷取訂閱項目,請使用 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

聯絡人

您可以透過下列網址,擷取特定使用者的聯絡人清單:

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

擷取使用者聯絡人

YouTubeService 物件的 GetYouTubeContactFeed 方法可用來擷取 gdata.youtube.YouTubeContactFeed,其中包含 gdata.youtube.YouTubeContactEntry 物件。

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 方法。這個方法可用於接受/拒絕聯絡要求,也可以將聯絡人分類為「朋友」或「家人」。在以下範例中,我們接受聯絡人,然後將其類別設為「Family」:

# 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'

返回頁首