PlaylistItems: list

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

配額影響:呼叫這個方法會產生 1 個單位的配額費用。

常見用途

要求

HTTP 要求

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

參數

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

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

如果參數識別的屬性包含子屬性,則子屬性會包含在回應中。舉例來說,在 playlistItem 資源中,snippet 屬性包含多個欄位,包括 title、description、position 和 resourceId 屬性。因此,如果您設定 part=snippet,API 回應就會包含所有這些屬性。

下列清單包含可納入參數值的 part 名稱:
  • contentDetails
  • id
  • snippet
  • status
篩選器 (請指定下列其中一個參數)
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
符合要求條件的播放清單項目清單。

範例

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

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;
        }
      }
    }
  }
}

小茹

這個範例會呼叫 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 要求和回應。