API 요청 매개변수와 일치하는 재생목록 항목의 컬렉션을 반환합니다. 지정된 재생목록의 모든 항목을 검색하거나 고유 ID를 통해 하나 또는 여러 개의 재생목록 항목을 검색할 수 있습니다.
할당량 영향: 이 메서드를 호출하면 1단위의 할당량 비용이 적용됩니다.
일반적인 사용 사례
요청
HTTP 요청
GET https://www.googleapis.com/youtube/v3/playlistItems
매개변수
다음 표에는 이 쿼리가 지원하는 매개변수가 나와 있습니다. 나열된 모든 매개변수는 쿼리 매개변수입니다.
| 매개변수 | ||
|---|---|---|
| 필수 매개변수 | ||
| part | stringpart매개변수는 API 응답에 포함될 하나 이상의playlistItem리소스 속성의 쉼표로 구분된 목록을 지정합니다.매개변수가 하위 속성을 포함하는 속성을 식별하는 경우 하위 속성이 응답에 포함됩니다. 예를 들어 playlistItem리소스에서snippet속성에는title,description,position,resourceId속성을 비롯한 수많은 필드가 포함되어 있습니다. 따라서part=snippet를 설정하면 API 응답에 이러한 모든 속성이 포함됩니다.다음 목록에는 매개변수 값에 포함할 수 있는 part이름이 나와 있습니다.
 | |
| 필터(다음 매개변수 중 하나만 지정) | ||
| id | stringid매개변수는 쉼표로 구분된 하나 이상의 고유한 재생목록 항목 ID 목록을 지정합니다. | |
| playlistId | stringplaylistId매개변수는 재생목록 항목을 검색하려는 재생목록의 고유 ID를 지정합니다. 이는 선택적 매개변수이지만 재생목록 항목을 검색하는 모든 요청은id매개변수 또는playlistId매개변수의 값을 지정해야 합니다. | |
| 선택적 매개변수 | ||
| maxResults | unsigned integermaxResults매개변수는 결과 집합에 반환해야 하는 최대 항목 수를 지정합니다. 사용 가능한 값:0~50기본값은5입니다. | |
| onBehalfOfContentOwner | string이 매개변수는 제대로 승인된 요청에서만 사용할 수 있습니다. 참고: 이 매개변수는 YouTube 콘텐츠 파트너 전용입니다. onBehalfOfContentOwner매개변수는 요청의 승인 사용자 인증 정보가 매개변수 값에 지정된 콘텐츠 소유자를 대신하는 YouTube CMS 사용자를 식별함을 나타냅니다. 이 매개변수는 다양한 YouTube 채널을 소유하고 관리하는 YouTube 콘텐츠 파트너를 위한 것입니다. 콘텐츠 소유자가 각 채널에 사용자 인증 정보를 제공하지 않고도 한 번만 인증하면 모든 동영상 및 채널 데이터에 액세스할 수 있습니다. 사용자가 인증할 CMS 계정은 지정된 YouTube 콘텐츠 소유자에게 연결되어야 합니다. | |
| pageToken | stringpageToken매개변수는 반환해야 하는 결과 집합의 특정 페이지를 식별합니다. API 응답에서nextPageToken속성과prevPageToken속성은 검색 가능한 다른 페이지를 식별합니다. | |
| videoId | stringvideoId매개변수는 요청이 지정된 동영상이 포함된 재생목록 항목만 반환해야 함을 지정합니다. | |
요청 본문
이 메소드를 호출할 때 요청 본문을 제공하지 마세요.
응답
요청에 성공할 경우 이 메소드는 다음과 같은 구조의 응답 본문을 반환합니다.
{
  "kind": "youtube#playlistItemListResponse",
  "etag": etag,
  "nextPageToken": string,
  "prevPageToken": string,
  "pageInfo": {
    "totalResults": integer,
    "resultsPerPage": integer
  },
  "items": [
    playlistItem Resource
  ]
}
속성
다음 표는 이 리소스에 표시되는 속성을 정의합니다.
| 속성 | |
|---|---|
| kind | stringAPI 리소스 유형을 식별합니다. 값은 youtube#playlistItemListResponse입니다. | 
| etag | etag이 리소스의 Etag입니다. | 
| nextPageToken | stringpageToken매개변수의 값으로 사용하여 결과 집합의 다음 페이지를 검색할 수 있는 토큰입니다. | 
| prevPageToken | stringpageToken매개변수의 값으로 사용하여 결과 집합의 이전 페이지를 검색할 수 있는 토큰입니다. | 
| pageInfo | objectpageInfo객체는 결과 집합의 페이지 정보를 요약합니다. | 
| pageInfo.totalResults | integer결과 집합의 총 결과 수입니다. | 
| pageInfo.resultsPerPage | integerAPI 응답에 포함된 결과 수입니다. | 
| items[] | list요청 기준과 일치하는 재생목록 항목의 목록입니다. | 
예
참고: 다음 코드 샘플은 지원되는 일부 프로그래밍 언어를 나타냅니다. 지원되는 언어 목록을 보려면 클라이언트 라이브러리 문서를 참조하세요.
Go
이 코드 샘플은 API의playlistItems.list 메서드를 호출하여 요청과 연결된 채널에 업로드된 동영상 목록을 검색합니다. 또한 이 코드는 mine 매개변수를 true로 설정하고 channels.list 메서드를 호출하여 채널에 업로드된 동영상을 식별하는 재생목록 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 메서드를 호출하여 요청과 연결된 채널에 업로드된 동영상 목록을 검색합니다. 또한 이 코드는 mine 매개변수를 true로 설정하고 channels.list 메서드를 호출하여 채널의 업로드된 동영상을 식별하는 재생목록 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 메서드를 호출하여 요청과 연결된 채널에 업로드된 동영상 목록을 검색합니다. 또한 이 코드는 mine 매개변수를 true로 설정하고 channels.list 메서드를 호출하여 채널에 업로드된 동영상을 식별하는 재생목록 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 요청 및 응답을 확인하세요.