PlaylistItems: list

API リクエストのパラメータに一致する、再生リストのアイテムのコレクションを返します。指定した再生リストのアイテムをすべて取得したり、一意の ID を指定して再生リストのアイテムを 1 つまたは複数取得したりできます。 今すぐ試すまたは例を見る

リクエスト

HTTP リクエスト

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

パラメータ

下記の表は、このクエリでサポートされているパラメータの一覧です。このリストのパラメータはすべてクエリ パラメータです。

パラメータ
必須パラメータ
part string
part パラメータには、API レスポンスに含める 1 つまたは複数の playlistItem リソース プロパティをカンマ区切りリストの形式で指定します。このパラメータ値に指定できる part 名は idsnippetcontentDetailsstatus などです。

このパラメータに子プロパティを持つプロパティが指定されている場合、その子プロパティもレスポンスに含まれます。たとえば playlistItem リソースの snippet プロパティは、titledescriptionpositionresourceId プロパティなどの複数のフィールドを持ちます。この場合、part=snippet と設定すると、API レスポンスにはこれらのプロパティすべてが含まれることになります。
フィルタ(以下のパラメータのいずれか 1 つのみを指定します)
id string
id パラメータには、1 つまたは複数の一意の再生リスト アイテム 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 リソース
  ]
}

プロパティ

次の表は、このリソースで使用されているプロパティの定義を示したものです。

プロパティ
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://code.google.com/apis/console/?api=youtube"
              + "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://code.google.com/p/google-api-dotnet-client/wiki/APIs#YouTube_Data_API
 * Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at:
 *   https://code.google.com/p/google-api-dotnet-client/wiki/Downloads
 */

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

// Call set_include_path() as needed to point to your client library.
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
session_start();

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * Google Developers 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);

if (isset($_GET['code'])) {
  if (strval($_SESSION['state']) !== strval($_GET['state'])) {
    die('The session state did not match.');
  }

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

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

// 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['token'] = $client->getAccessToken();
} 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 Developers 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 Developers 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 リクエストとレスポンスを確認してください。