傳回一組符合 API 要求參數的播放清單項目。您可以擷取指定播放清單中的所有播放清單項目,或是依專屬 ID 擷取一或多個播放清單項目。
配額影響:呼叫這個方法的配額為 1 個單位。
常見用途
要求
HTTP 要求
GET https://www.googleapis.com/youtube/v3/playlistItems
參數
下表列出此查詢支援的參數。這裡列出的參數全都是查詢參數。
參數 | ||
---|---|---|
必要參數 | ||
part |
string part 參數會指定一份以半形逗號分隔的清單,列出一或多個 API 回應會包含的 playlistItem 資源屬性。如果參數識別含有子屬性的屬性,則回應中會加入這些子項屬性。舉例來說,在 playlistItem 資源中,snippet 屬性包含許多欄位,包括 title 、description 、position 和 resourceId 屬性。因此,如果您設定 part=snippet ,API 回應就會包含所有屬性。以下清單包含您可以加入參數值中的 part 名稱:
|
|
篩選器 (請僅指定下列其中一個參數) | ||
id |
string id 參數會指定包含一或多個不重複播放清單項目 ID 的清單 (以半形逗號分隔)。 |
|
playlistId |
string playlistId 參數會指定要擷取播放清單項目的播放清單專屬 ID。請注意,雖然這是選用參數,但每個擷取播放清單項目的要求都必須指定 id 參數或 playlistId 參數的值。 |
|
選用參數 | ||
maxResults |
unsigned integer maxResults 參數會指定結果集應傳回的項目數量上限。可接受的值為 0 到 50 (含頭尾)。預設值為 5 。 |
|
onBehalfOfContentOwner |
string 這個參數只能在正確的授權要求中使用。注意:這個參數僅適用於 YouTube 內容合作夥伴。 onBehalfOfContentOwner 參數代表透過要求的授權憑證,代表 YouTube CMS 使用者,代表在參數值中指定的內容擁有者擔任代理人。這個參數適用於擁有及管理多個不同 YouTube 頻道的 YouTube 內容合作夥伴。內容擁有者只要通過一次驗證,即可存取所有影片和頻道資料,不必分別提供各個頻道的驗證憑證。用於驗證的 CMS 帳戶,必須連結至指定的 YouTube 內容擁有者。 |
|
pageToken |
string pageToken 參數可在結果集中指明應傳回的特定網頁。在 API 回應中,nextPageToken 和 prevPageToken 屬性會識別其他可擷取的網頁。 |
|
videoId |
string videoId 參數指定要求應只傳回含有指定影片的播放清單項目。 |
要求主體
呼叫此方法時,不要提供要求主體。
回應
如果成功的話,這個方法會傳回回應內文,其結構如下:
{
"kind": "youtube#playlistItemListResponse",
"etag":etag ,
"nextPageToken":string ,
"prevPageToken":string ,
"pageInfo": {
"totalResults":integer ,
"resultsPerPage":integer
},
"items": [
playlistItem Resource
]
}
屬性
下表定義了這項資源中顯示的屬性:
屬性 | |
---|---|
kind |
string 識別 API 資源的類型。值為 youtube#playlistItemListResponse 。 |
etag |
etag 這項資源的 Etag。 |
nextPageToken |
string 可做為 pageToken 參數值的權杖,用於擷取結果集中的下一頁。 |
prevPageToken |
string 可做為 pageToken 參數值的權杖,擷取結果集中的上一頁。 |
pageInfo |
object pageInfo 物件會封裝結果集的分頁資訊。 |
pageInfo.totalResults |
integer 結果集的結果總數。 |
pageInfo.resultsPerPage |
integer API 回應中包含的結果數量。 |
items[] |
list 符合要求條件的播放清單項目清單。 |
範例
注意:下列程式碼範例可能不是所有支援的程式設計語言。如需支援的語言清單,請參閱用戶端程式庫說明文件。
playlistItems.list
方法,擷取已上傳至與要求相關聯頻道的影片清單。程式碼也會呼叫 channels.list
方法,將 mine
參數設為 true
,以擷取用於識別頻道上傳影片的播放清單 ID。本範例使用 Go 用戶端程式庫。
package main
import (
"fmt"
"log"
"google.golang.org/api/youtube/v3"
)
// Retrieve playlistItems in the specified playlist
func playlistItemsList(service *youtube.Service, part string, playlistId string, pageToken string) *youtube.PlaylistItemListResponse {
call := service.PlaylistItems.List(part)
call = call.PlaylistId(playlistId)
if pageToken != "" {
call = call.PageToken(pageToken)
}
response, err := call.Do()
handleError(err, "")
return response
}
// Retrieve resource for the authenticated user's channel
func channelsListMine(service *youtube.Service, part string) *youtube.ChannelListResponse {
call := service.Channels.List(part)
call = call.Mine(true)
response, err := call.Do()
handleError(err, "")
return response
}
func main() {
client := getClient(youtube.YoutubeReadonlyScope)
service, err := youtube.New(client)
if err != nil {
log.Fatalf("Error creating YouTube client: %v", err)
}
response := channelsListMine(service, "contentDetails")
for _, channel := range response.Items {
playlistId := channel.ContentDetails.RelatedPlaylists.Uploads
// Print the playlist ID for the list of uploaded videos.
fmt.Printf("Videos in list %s\r\n", playlistId)
nextPageToken := ""
for {
// Retrieve next set of items in the playlist.
playlistResponse := playlistItemsList(service, "snippet", playlistId, nextPageToken)
for _, playlistItem := range playlistResponse.Items {
title := playlistItem.Snippet.Title
videoId := playlistItem.Snippet.ResourceId.VideoId
fmt.Printf("%v, (%v)\r\n", title, videoId)
}
// Set the token to retrieve the next page of results
// or exit the loop if all results have been retrieved.
nextPageToken = playlistResponse.NextPageToken
if nextPageToken == "" {
break
}
fmt.Println()
}
}
}
playlistItems.list
方法,擷取與要求相關聯頻道上傳的影片清單。程式碼也會呼叫 channels.list
方法,將 mine
參數設為 true
,擷取用於識別頻道上傳影片的播放清單 ID。本範例使用 .NET 用戶端程式庫。
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace Google.Apis.YouTube.Samples
{
/// <summary>
/// YouTube Data API v3 sample: retrieve my uploads.
/// Relies on the Google APIs Client Library for .NET, v1.7.0 or higher.
/// See https://developers.google.com/api-client-library/dotnet/get_started
/// </summary>
internal class MyUploads
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("YouTube Data API: My Uploads");
Console.WriteLine("============================");
try
{
new MyUploads().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows for read-only access to the authenticated
// user's account, but not other types of account access.
new[] { YouTubeService.Scope.YoutubeReadonly },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
var channelsListRequest = youtubeService.Channels.List("contentDetails");
channelsListRequest.Mine = true;
// Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
var channelsListResponse = await channelsListRequest.ExecuteAsync();
foreach (var channel in channelsListResponse.Items)
{
// From the API response, extract the playlist ID that identifies the list
// of videos uploaded to the authenticated user's channel.
var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
Console.WriteLine("Videos in list {0}", uploadsListId);
var nextPageToken = "";
while (nextPageToken != null)
{
var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
playlistItemsListRequest.PlaylistId = uploadsListId;
playlistItemsListRequest.MaxResults = 50;
playlistItemsListRequest.PageToken = nextPageToken;
// Retrieve the list of videos uploaded to the authenticated user's channel.
var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
foreach (var playlistItem in playlistItemsListResponse.Items)
{
// Print information about each video.
Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
}
nextPageToken = playlistItemsListResponse.NextPageToken;
}
}
}
}
}
playlistItems.list
方法,擷取與要求相關聯頻道上傳的影片清單。程式碼也會呼叫 channels.list
方法,並將 mine
參數設為 true
,擷取用於識別頻道上傳影片的播放清單 ID。本範例使用 Ruby 用戶端程式庫。
#!/usr/bin/ruby
require 'rubygems'
gem 'google-api-client', '>0.7'
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/file_storage'
require 'google/api_client/auth/installed_app'
# This OAuth 2.0 access scope allows for read-only access to the authenticated
# user's account, but not other types of account access.
YOUTUBE_READONLY_SCOPE = 'https://www.googleapis.com/auth/youtube.readonly'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
def get_authenticated_service
client = Google::APIClient.new(
:application_name => $PROGRAM_NAME,
:application_version => '1.0.0'
)
youtube = client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION)
file_storage = Google::APIClient::FileStorage.new("#{$PROGRAM_NAME}-oauth2.json")
if file_storage.authorization.nil?
client_secrets = Google::APIClient::ClientSecrets.load
flow = Google::APIClient::InstalledAppFlow.new(
:client_id => client_secrets.client_id,
:client_secret => client_secrets.client_secret,
:scope => [YOUTUBE_READONLY_SCOPE]
)
client.authorization = flow.authorize(file_storage)
else
client.authorization = file_storage.authorization
end
return client, youtube
end
def main
client, youtube = get_authenticated_service
begin
# Retrieve the "contentDetails" part of the channel resource for the
# authenticated user's channel.
channels_response = client.execute!(
:api_method => youtube.channels.list,
:parameters => {
:mine => true,
:part => 'contentDetails'
}
)
channels_response.data.items.each do |channel|
# From the API response, extract the playlist ID that identifies the list
# of videos uploaded to the authenticated user's channel.
uploads_list_id = channel['contentDetails']['relatedPlaylists']['uploads']
# Retrieve the list of videos uploaded to the authenticated user's channel.
next_page_token = ''
until next_page_token.nil?
playlistitems_response = client.execute!(
:api_method => youtube.playlist_items.list,
:parameters => {
:playlistId => uploads_list_id,
:part => 'snippet',
:maxResults => 50,
:pageToken => next_page_token
}
)
puts "Videos in list #{uploads_list_id}"
# Print information about each video.
playlistitems_response.data.items.each do |playlist_item|
title = playlist_item['snippet']['title']
video_id = playlist_item['snippet']['resourceId']['videoId']
puts "#{title} (#{video_id})"
end
next_page_token = playlistitems_response.next_page_token
end
puts
end
rescue Google::APIClient::TransmissionError => e
puts e.result.body
end
end
main
錯誤
下表列出 API 回應此方法時可能傳回的錯誤訊息。詳情請參閱錯誤訊息的說明文件。
錯誤類型 | 錯誤詳細資料 | 說明 |
---|---|---|
forbidden (403) |
playlistItemsNotAccessible |
請求未獲適當授權,無法擷取指定的播放清單。 |
forbidden (403) |
watchHistoryNotAccessible |
您無法透過 API 擷取觀看記錄資料。 |
forbidden (403) |
watchLaterNotAccessible |
無法透過 API 擷取「稍後觀看」播放清單中的項目。 |
notFound (404) |
playlistNotFound |
找不到使用要求 playlistId 參數指定的播放清單。 |
notFound (404) |
videoNotFound |
找不到使用要求 videoId 參數的影片。 |
required (400) |
playlistIdRequired |
訂閱要求未指定必要的 playlistId 屬性值。 |
invalidValue (400) |
playlistOperationUnsupported |
API 不支援列出指定播放清單中的影片。舉例來說,你無法在「稍後觀看」播放清單中列出影片。 |