PlaylistItems: list

API 요청 매개변수와 일치하는 재생목록 항목의 모음을 반환합니다. 지정된 재생목록의 모든 항목을 검색하거나 고유 ID를 통해 하나 또는 여러 개의 재생목록 항목을 검색할 수 있습니다. 지금 사용해 보거나 예를 참조하세요.

요청

HTTP 요청

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

매개변수

아래 표는 이 쿼리가 지원하는 매개변수 목록입니다. 나열된 모든 매개변수는 쿼리 매개변수입니다.

매개변수 이름
필수 매개변수
part string
part 매개변수는 API 응답이 포함하는 playlistItem 리소스 속성 하나 이상의 쉼표로 구분된 목록을 지정합니다. 매개변수 값에 포함할 수 있는 part 이름은 id, snippet, contentDetails, status입니다.

매개변수가 하위 속성을 포함하는 속성을 식별하는 경우 하위 속성이 응답에 포함됩니다. 예를 들어 playlistItem 리소스에서 snippet 속성은 title, description, position, resourceId 속성 등 여러 필드를 포함합니다. 따라서 part=snippet을 설정하는 경우 API 응답은 하위 속성도 모두 포함합니다.
필터(다음 매개변수 중 하나만 지정합니다.)
id string
id 매개변수는 쉼표로 구분된 하나 이상의 고유한 재생목록 항목 ID 목록을 지정합니다.
playlistId string
playlistId 매개변수는 재생목록 항목을 검색하려는 재생목록의 고유한 ID를 지정합니다. 이 매개변수는 선택적 매개변수이지만 재생목록 항목을 검색하는 모든 요청은 id 매개변수 또는 playlistId 매개변수에 값을 지정해야 합니다.
선택적 매개변수
maxResults unsigned integer
maxResults 매개변수는 결과 집합에 반환해야 하는 최대 항목 수를 지정합니다. 허용값은 0 이상 50 이하입니다. 기본값은 5입니다.
pageToken string
pageToken 매개변수는 반환해야 하는 결과 집합의 특정 페이지를 식별합니다. API 응답에서 nextPageTokenprevPageToken 속성은 검색할 기타 페이지를 식별합니다.
videoId string
videoId 매개변수는 요청이 지정된 동영상을 포함하는 재생목록만 반환해야 함을 지정합니다.

요청 본문

이 메소드를 호출할 때 요청 본문을 제공하지 마세요.

응답

성공하는 경우 이 메소드는 다음 구조로 응답 본문을 반환합니다.

{
  "kind": "youtube#playlistItemListResponse",
  "etag": etag,
  "nextPageToken": string,
  "prevPageToken": string,
  "pageInfo": {
    "totalResults": integer,
    "resultsPerPage": integer
  },
  "items": [
    playlistItems 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
요청 기준과 일치하는 재생목록 항목의 목록입니다.

참고: 아래의 코드 샘플은 지원되는 일부 프로그래밍 언어를 나타냅니다. 지원되는 언어 목록을 보려면 클라이언트 라이브러리 문서를 참조하세요.

Java

Java 클라이언트 라이브러리를 사용하는 예입니다.

  • MyUploads.java

    /*
     * Copyright (c) 2012 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
     * in compliance with the License. You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software distributed under the License
     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
     * or implied. See the License for the specific language governing permissions and limitations under
     * the License.
     */
    
    package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_myuploads_sample;
    
    import java.io.File;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.json.GoogleJsonResponseException;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.youtube.YouTube;
    import com.google.api.services.youtube.model.Channel;
    import com.google.api.services.youtube.model.ChannelListResponse;
    import com.google.api.services.youtube.model.PlaylistItem;
    import com.google.api.services.youtube.model.PlaylistItemListResponse;
    import com.google.common.collect.Lists;
    
    /**
     * Prints a list of videos uploaded to the user's YouTube account using OAuth2 for authentication.
     *
     *  Details: The app uses Youtube.Channnels.List to get the playlist id associated with all the
     * videos ever uploaded to the user's account. It then gets all the video info using
     * YouTube.PlaylistItems.List. Finally, it prints all the information to the screen.
     *
     * @author Jeremy Walker
     */
    public class MyUploads {
    
      /** Global instance of the HTTP transport. */
      private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = new JacksonFactory();
    
      /** Global instance of YouTube object to make all API requests. */
      private static YouTube youtube;
    
      /**
       * Authorizes the installed application to access user's protected data.
       *
       * @param scopes list of scopes needed to run upload.
       */
      private static Credential authorize(List<String> scopes) throws Exception {
    
        // Load client secrets.
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            JSON_FACTORY, MyUploads.class.getResourceAsStream("/client_secrets.json"));
    
        // Checks that the defaults have been replaced (Default = "Enter X here").
        if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
          System.out.println(
              "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential"
              + "into youtube-cmdline-myuploads-sample/src/main/resources/client_secrets.json");
          System.exit(1);
        }
    
        // Set up file credential store.
        FileCredentialStore credentialStore = new FileCredentialStore(
            new File(System.getProperty("user.home"), ".credentials/youtube-api-myuploads.json"),
            JSON_FACTORY);
    
        // Set up authorization code flow.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
            .build();
    
        // Build the local server and bind it to port 9000
        LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();
    
        // Authorize.
        return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
      }
    
      /**
       * Authorizes user, runs Youtube.Channnels.List get the playlist id associated with uploaded
       * videos, runs YouTube.PlaylistItems.List to get information on each video, and prints out the
       * results.
       *
       * @param args command line args (not used).
       */
      public static void main(String[] args) {
    
        // Scope required to upload to YouTube.
        List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
    
        try {
          // Authorization.
          Credential credential = authorize(scopes);
    
          // YouTube object used to make all API requests.
          youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
              "youtube-cmdline-myuploads-sample").build();
    
          /*
           * Now that the user is authenticated, the app makes a channel list request to get the
           * authenticated user's channel. Returned with that data is the playlist id for the uploaded
           * videos. https://developers.google.com/youtube/v3/docs/channels/list
           */
          YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
          channelRequest.setMine("true");
          /*
           * Limits the results to only the data we needo which makes things more efficient.
           */
          channelRequest.setFields("items/contentDetails,nextPageToken,pageInfo");
          ChannelListResponse channelResult = channelRequest.execute();
    
          /*
           * Gets the list of channels associated with the user. This sample only pulls the uploaded
           * videos for the first channel (default channel for user).
           */
          List<Channel> channelsList = channelResult.getItems();
    
          if (channelsList != null) {
            // Gets user's default channel id (first channel in list).
            String uploadPlaylistId =
                channelsList.get(0).getContentDetails().getRelatedPlaylists().getUploads();
    
            // List to store all PlaylistItem items associated with the uploadPlaylistId.
            List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>();
    
            /*
             * Now that we have the playlist id for your uploads, we will request the playlistItems
             * associated with that playlist id, so we can get information on each video uploaded. This
             * is the template for the list call. We call it multiple times in the do while loop below
             * (only changing the nextToken to get all the videos).
             * https://developers.google.com/youtube/v3/docs/playlistitems/list
             */
            YouTube.PlaylistItems.List playlistItemRequest =
                youtube.playlistItems().list("id,contentDetails,snippet");
            playlistItemRequest.setPlaylistId(uploadPlaylistId);
    
            // This limits the results to only the data we need and makes things more efficient.
            playlistItemRequest.setFields(
                "items(contentDetails/videoId,snippet/title,snippet/publishedAt),nextPageToken,pageInfo");
    
            String nextToken = "";
    
            // Loops over all search page results returned for the uploadPlaylistId.
            do {
              playlistItemRequest.setPageToken(nextToken);
              PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute();
    
              playlistItemList.addAll(playlistItemResult.getItems());
    
              nextToken = playlistItemResult.getNextPageToken();
            } while (nextToken != null);
    
            // Prints results.
            prettyPrint(playlistItemList.size(), playlistItemList.iterator());
          }
    
        } catch (GoogleJsonResponseException e) {
          e.printStackTrace();
          System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
              + e.getDetails().getMessage());
    
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    
      /*
       * Method that prints all the PlaylistItems in an Iterator.
       *
       * @param size size of list
       *
       * @param iterator of Playlist Items from uploaded Playlist
       */
      private static void prettyPrint(int size, Iterator<PlaylistItem> playlistEntries) {
        System.out.println("=============================================================");
        System.out.println("\t\tTotal Videos Uploaded: " + size);
        System.out.println("=============================================================\n");
    
        while (playlistEntries.hasNext()) {
          PlaylistItem playlistItem = playlistEntries.next();
          System.out.println(" video name  = " + playlistItem.getSnippet().getTitle());
          System.out.println(" video id    = " + playlistItem.getContentDetails().getVideoId());
          System.out.println(" upload date = " + playlistItem.getSnippet().getPublishedAt());
          System.out.println("\n-------------------------------------------------------------\n");
        }
      }
    }
    
  • pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.google.api.services.samples.youtube.cmdline</groupId>
      <artifactId>youtube-cmdline-myuploads-sample</artifactId>
      <version>1.0</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-myuploads-sample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.youtube.version>v3-rev8-1.12.0-beta</project.youtube.version>
        <project.http.version>1.12.0-beta</project.http.version>
        <project.oauth.version>1.12.0-beta</project.oauth.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <repositories>
        <repository>
          <id>google-api-services</id>
          <url>http://google-api-client-libraries.appspot.com/mavenrepo</url>
        </repository>
      </repositories>
    
      <dependencies>
    
        <!-- YouTube Data V3 support -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-youtube</artifactId>
          <version>${project.youtube.version}</version>
        </dependency>
    
        <dependency>
          <groupId>com.google.http-client</groupId>
          <artifactId>google-http-client-jackson2</artifactId>
          <version>${project.http.version}</version>
        </dependency>
        <dependency>
          <groupId>com.google.oauth-client</groupId>
          <artifactId>google-oauth-client-jetty</artifactId>
          <version>${project.oauth.version}</version>
        </dependency>
      </dependencies>
    
      <build>
        <plugins>
          <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
              <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_myuploads_sample.MyUploads</mainClass>
            </configuration>
          </plugin>
    
          <!-- Forces Maven to use Java 1.6 -->
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
              <source>1.6</source>
              <target>1.6</target>
              <compilerArgument></compilerArgument>
            </configuration>
          </plugin>
        </plugins>
      </build>
    
    </project>
    
  • client_secrets.json

    {
      "installed": {
        "client_id": "Enter your client id here",
        "client_secret": "Enter your client secret here"
      }
    }
    

JavaScript

JavaScript 클라이언트 라이브러리를 사용하는 예입니다.

// Define some variables used to remember state.
var playlistId, nextPageToken, prevPageToken;

// After the API loads, call a function to get the uploads playlist ID.
function handleAPILoaded() {
  requestUserUploadsPlaylistId();
}

// Call the Data API to retrieve the playlist ID that uniquely identifies the
// list of videos uploaded to the currently authenticated user's channel.
function requestUserUploadsPlaylistId() {
  // See https://developers.google.com/youtube/v3/docs/channels/list
  var request = gapi.client.youtube.channels.list({
    mine: true,
    part: 'contentDetails'
  });
  request.execute(function(response) {
    playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
    requestVideoPlaylist(playlistId);
  });
}

// Retrieve the list of videos in the specified playlist.
function requestVideoPlaylist(playlistId, pageToken) {
  $('#video-container').html('');
  var requestOptions = {
    playlistId: playlistId,
    part: 'snippet',
    maxResults: 10
  };
  if (pageToken) {
    requestOptions.pageToken = pageToken;
  }
  var request = gapi.client.youtube.playlistItems.list(requestOptions);
  request.execute(function(response) {
    // Only show pagination buttons if there is a pagination token for the
    // next or previous page of results.
    nextPageToken = response.result.nextPageToken;
    var nextVis = nextPageToken ? 'visible' : 'hidden';
    $('#next-button').css('visibility', nextVis);
    prevPageToken = response.result.prevPageToken
    var prevVis = prevPageToken ? 'visible' : 'hidden';
    $('#prev-button').css('visibility', prevVis);

    var playlistItems = response.result.items;
    if (playlistItems) {
      $.each(playlistItems, function(index, item) {
        displayResult(item.snippet);
      });
    } else {
      $('#video-container').html('Sorry you have no uploaded videos');
    }
  });
}

// Create a listing for a video.
function displayResult(videoSnippet) {
  var title = videoSnippet.title;
  var videoId = videoSnippet.resourceId.videoId;
  $('#video-container').append('<p>' + title + ' - ' + videoId + '</p>');
}

// Retrieve the next page of videos in the playlist.
function nextPage() {
  requestVideoPlaylist(playlistId, nextPageToken);
}

// Retrieve the previous page of videos in the playlist.
function previousPage() {
  requestVideoPlaylist(playlistId, prevPageToken);
}

.NET

.NET 클라이언트 라이브러리를 사용하는 예입니다.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

/*
 * External dependencies, OAuth 2.0 support, and core client libraries are at:
 *   https://developers.google.com/api-client-library/dotnet/apis/
 * Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at:
 *   https://github.com/youtube/api-samples/tree/master/dotnet
 */

using DotNetOpenAuth.OAuth2;

using Google.Apis.Authentication;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Samples.Helper;
using Google.Apis.Services;
using Google.Apis.Util;
using Google.Apis.Youtube.v3;
using Google.Apis.Youtube.v3.Data;

namespace dotnet
{
  class my_uploads
  {
    static void Main(string[] args)
    {
      CommandLine.EnableExceptionHandling();
      CommandLine.DisplayGoogleSampleHeader("YouTube Data API: My Uploads");

      var credentials = PromptingClientCredentials.EnsureFullClientCredentials();
      var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
      {
        ClientIdentifier = credentials.ClientId,
        ClientSecret = credentials.ClientSecret
      };
      var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

      var youtube = new YoutubeService(new BaseClientService.Initializer()
      {
        Authenticator = auth
      });

      var channelsListRequest = youtube.Channels.List("contentDetails");
      channelsListRequest.Mine = true;

      var channelsListResponse = channelsListRequest.Fetch();

      foreach (var channel in channelsListResponse.Items)
      {
        var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;

        CommandLine.WriteLine(String.Format("Videos in list {0}", uploadsListId));

        var nextPageToken = "";
        while (nextPageToken != null)
        {
          var playlistItemsListRequest = youtube.PlaylistItems.List("snippet");
          playlistItemsListRequest.PlaylistId = uploadsListId;
          playlistItemsListRequest.MaxResults = 50;
          playlistItemsListRequest.PageToken = nextPageToken;

          var playlistItemsListResponse = playlistItemsListRequest.Fetch();

          foreach (var playlistItem in playlistItemsListResponse.Items)
          {
            CommandLine.WriteLine(String.Format("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId));
          }

          nextPageToken = playlistItemsListResponse.NextPageToken;
        }
      }

      CommandLine.PressAnyKeyToExit();
    }

    private static IAuthorizationState GetAuthorization(NativeApplicationClient client)
    {
      var storage = MethodBase.GetCurrentMethod().DeclaringType.ToString();
      var key = "storage_key";

      IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(storage, key);
      if (state != null)
      {
        client.RefreshToken(state);
      }
      else
      {
        state = AuthorizationMgr.RequestNativeAuthorization(client, YoutubeService.Scopes.YoutubeReadonly.GetStringValue());
        AuthorizationMgr.SetCachedRefreshToken(storage, key, state);
      }

      return state;
    }
  }
}

PHP

PHP 클라이언트 라이브러리를 사용하는 예입니다.

<?php

/**
 * Library Requirements
 *
 * 1. Install composer (https://getcomposer.org)
 * 2. On the command line, change to this directory (api-samples/php)
 * 3. Require the google/apiclient library
 *    $ composer require google/apiclient:~2.0
 */
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
  throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}

require_once __DIR__ . '/vendor/autoload.php';
session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * Google API Console <https://console.developers.google.com/>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <https://developers.google.com/youtube/v3/guides/authentication>
 * Please ensure that you have enabled the YouTube Data API for your project.
 */
$OAUTH2_CLIENT_ID = 'REPLACE_ME';
$OAUTH2_CLIENT_SECRET = 'REPLACE_ME';

$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
  FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);

// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);

// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

  $client->authenticate($_GET['code']);
  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
  header('Location: ' . $redirect);
}

if (isset($_SESSION[$tokenSessionKey])) {
  $client->setAccessToken($_SESSION[$tokenSessionKey]);
}

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  try {
    // Call the channels.list method to retrieve information about the
    // currently authenticated user's channel.
    $channelsResponse = $youtube->channels->listChannels('contentDetails', array(
      'mine' => 'true',
    ));

    $htmlBody = '';
    foreach ($channelsResponse['items'] as $channel) {
      // Extract the unique playlist ID that identifies the list of videos
      // uploaded to the channel, and then call the playlistItems.list method
      // to retrieve that list.
      $uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads'];

      $playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array(
        'playlistId' => $uploadsListId,
        'maxResults' => 50
      ));

      $htmlBody .= "<h3>Videos in list $uploadsListId</h3><ul>";
      foreach ($playlistItemsResponse['items'] as $playlistItem) {
        $htmlBody .= sprintf('<li>%s (%s)</li>', $playlistItem['snippet']['title'],
          $playlistItem['snippet']['resourceId']['videoId']);
      }
      $htmlBody .= '</ul>';
    }
  } catch (Google_Service_Exception $e) {
    $htmlBody = sprintf('<p>A service error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  } catch (Google_Exception $e) {
    $htmlBody = sprintf('<p>An client error occurred: <code>%s</code></p>',
      htmlspecialchars($e->getMessage()));
  }

  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') {
  $htmlBody = <<<END
  <h3>Client Credentials Required</h3>
  <p>
    You need to set <code>\$OAUTH2_CLIENT_ID</code> and
    <code>\$OAUTH2_CLIENT_ID</code> before proceeding.
  <p>
END;
} else {
  $state = mt_rand();
  $client->setState($state);
  $_SESSION['state'] = $state;

  $authUrl = $client->createAuthUrl();
  $htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
}
?>

<!doctype html>
<html>
  <head>
    <title>My Uploads</title>
  </head>
  <body>
    <?=$htmlBody?>
  </body>
</html>

Python

Python 클라이언트 라이브러리를 사용하는 예입니다.

#!/usr/bin/python

import httplib2
import os
import sys

from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow


# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the Google API Console at
# https://console.developers.google.com/.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
#   https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
#   https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = "client_secrets.json"

# This variable defines a message to display if the CLIENT_SECRETS_FILE is
# missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0

To make this sample run you will need to populate the client_secrets.json file
found at:

   %s

with information from the API Console
https://console.developers.google.com/

For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
                                   CLIENT_SECRETS_FILE))

# 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"

flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
  message=MISSING_CLIENT_SECRETS_MESSAGE,
  scope=YOUTUBE_READONLY_SCOPE)

storage = Storage("%s-oauth2.json" % sys.argv[0])
credentials = storage.get()

if credentials is None or credentials.invalid:
  flags = argparser.parse_args()
  credentials = run_flow(flow, storage, flags)

youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
  http=credentials.authorize(httplib2.Http()))

# Retrieve the contentDetails part of the channel resource for the
# authenticated user's channel.
channels_response = youtube.channels().list(
  mine=True,
  part="contentDetails"
).execute()

for channel in channels_response["items"]:
  # 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"]

  print "Videos in list %s" % uploads_list_id

  # Retrieve the list of videos uploaded to the authenticated user's channel.
  playlistitems_list_request = youtube.playlistItems().list(
    playlistId=uploads_list_id,
    part="snippet",
    maxResults=50
  )

  while playlistitems_list_request:
    playlistitems_list_response = playlistitems_list_request.execute()

    # Print information about each video.
    for playlist_item in playlistitems_list_response["items"]:
      title = playlist_item["snippet"]["title"]
      video_id = playlist_item["snippet"]["resourceId"]["videoId"]
      print "%s (%s)" % (title, video_id)

    playlistitems_list_request = youtube.playlistItems().list_next(
      playlistitems_list_request, playlistitems_list_response)

  print

Ruby

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 playlistItemsNotAccessible 지정된 재생목록을 검색할 수 있도록 요청이 제대로 인증되지 않았습니다.
notFound playlistNotFound 요청의 playlistId 매개변수로 식별된 재생목록을 찾을 수 없습니다.
notFound videoNotFound 요청의 videoId 매개변수로 식별된 동영상을 찾을 수 없습니다.
required playlistIdRequired 구독 요청이 필수 playlistId 속성 값을 지정하지 않았습니다.

직접 사용해 보세요!

API Explorer를 사용하여 실시간 데이터에서 이 메소드를 호출하고 API 요청 및 응답을 확인해 보세요.