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(含 0 和 5000)。默认值为 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 请求和响应。