PlaylistItems: list

傳回符合 API 要求參數的播放清單項目集合。您可以擷取指定播放清單中的所有播放清單項目,也可以依其專屬 ID 擷取一個或多個播放清單項目。

配額影響:呼叫此方法的配額費用為 1 單位。

常見用途

要求

HTTP 要求

GET https://www.googleapis.com/youtube/v3/playlistItems

參數

下表列出這項查詢支援的參數。上方列出的所有參數都是查詢參數。

參數
必要參數
part string
part 參數會指定以逗號分隔的清單,其中包含 API 回應所包含的一或多個 playlistItem 資源屬性。

如果參數指定的屬性包含子項資源,則子屬性將納入回應中。舉例來說,在 playlistItem 資源中,snippet 屬性包含許多欄位,包括 titledescriptionpositionresourceId 屬性。因此,如果您設定 part=snippet,API 回應就會包含以上所有屬性。

以下清單包含可在參數值中加入的 part 名稱:
  • contentDetails
  • id
  • snippet
  • status
篩選器 (請僅指定下列其中一個參數)
id string
id 參數用來指定以逗號分隔的一或多個播放清單項目 ID 清單。
playlistId string
playlistId 參數會指定要擷取播放清單項目的播放清單專屬 ID。請注意,即使這是選用參數,每個擷取播放清單項目的請求都必須指定 id 參數或 playlistId 參數的值。
選用參數
maxResults unsigned integer
maxResults 參數會指定要在結果集中傳回的項目數量上限。可接受的值為 050 (含首尾)。預設值為 5
onBehalfOfContentOwner string
這個參數只能在妥善的授權要求中使用。注意:這個參數僅適用於 YouTube 內容合作夥伴。

onBehalfOfContentOwner 參數表示請求的授權憑證能代表代替參數值中所指定的內容擁有者所擔任的 YouTube CMS 使用者。這個參數適用於擁有和管理多個不同 YouTube 頻道的 YouTube 內容合作夥伴。內容擁有者只要驗證一次即可,就能存取所有影片和頻道資料,而不需要為每個頻道分別提供驗證憑證。使用者驗證的 CMS 帳戶必須連結至指定的 YouTube 內容擁有者。
pageToken string
pageToken 參數可指定要傳回結果集中的網頁。在 API 回應中,nextPageTokenprevPageToken 屬性可識別其他可擷取的網頁。
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
符合要求條件的播放清單清單。

範例

注意:下列程式碼範例不一定能支援所有支援的語言。如需支援語言的清單,請參閱用戶端程式庫說明文件。

Go

此程式碼範例會呼叫 API 的 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()
		}
	}
}

.NET

下列程式碼範例會呼叫 API 的 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;
        }
      }
    }
  }
}

Ruby

這個範例會呼叫 API 的 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 不支援列出指定播放清單中的影片。舉例來說,你無法在稍後觀看清單中列出影片。

試試看!

使用 APIs Explorer 呼叫這個 API 並查看 API 要求和回應。