Playlists: insert

コレクションでコンテンツを整理 必要に応じて、コンテンツの保存と分類を行います。

再生リストを作成します。 今すぐ試すまたは例を見る

リクエスト

HTTP リクエスト

POST https://www.googleapis.com/youtube/v3/playlists

承認

このリクエストは、最低でも以下のスコープの 1 つによって承認される必要があります(認証と承認の詳細については、こちらをご覧ください)。

スコープ
https://www.googleapis.com/auth/youtubepartner
https://www.googleapis.com/auth/youtube

パラメータ

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

パラメータ
必須パラメータ
part string
この操作では、part パラメータは 2 つの目的で使用されます。書き込み操作で設定されるプロパティの特定と API レスポンスに含まれるプロパティの特定です。

このパラメータに指定できる part 名は snippetstatus です。

リクエストの本文

リクエストの本文には再生リストのリソースを指定します。 このリソースでは、次の点に注意してください。

  • 以下のプロパティの値を指定する必要があります。

    • snippet.title

  • 以下のプロパティの値を設定することができます。

    • snippet.title
    • snippet.description
    • status.privacyStatus
    • snippet.tags[]

レスポンス

成功すると、このメソッドはレスポンスの本文で再生リストのリソースを返します。

注: 以下のコード サンプルは、サポートされているプログラミング言語すべてについて表したものではありません。サポートされている言語の一覧については、クライアント ライブラリのドキュメントを参照してください。

Java

この例では、Java クライアント ライブラリを使用しています。

  • PlaylistUpdates.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_playlistupdates_sample;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Calendar;
    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.Playlist;
    import com.google.api.services.youtube.model.PlaylistItem;
    import com.google.api.services.youtube.model.PlaylistItemSnippet;
    import com.google.api.services.youtube.model.PlaylistSnippet;
    import com.google.api.services.youtube.model.PlaylistStatus;
    import com.google.api.services.youtube.model.ResourceId;
    import com.google.common.collect.Lists;
    
    /**
     * Creates a new, private playlist in the authorized user's channel and adds a playlistitem
     * containing a video to that new playlist.
     *
     * @author Jeremy Walker
     */
    public class PlaylistUpdates {
    
      /** 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;
    
      /*
       * Global instance of the video id we want to post as the first PlaylistItem in our new playlist.
       */
      private static String VIDEO_ID = "SZj6rAYkYOg";
    
      /**
       * 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,
                PlaylistUpdates.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-playlistupdates-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-playlistupdates.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, creates a playlist, adds a playlistitem with a video to that new playlist.
       *
       * @param args command line args (not used).
       */
      public static void main( String[] args ) {
    
        // General read/write scope for YouTube APIs.
        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-playlistupdates-sample")
            .build();
    
          // Creates a new playlist in the authorized user's channel.
          String playlistId = insertPlaylist();
    
          // If a valid playlist was created, adds a new playlistitem with a video to that playlist.
          insertPlaylistItem(playlistId, VIDEO_ID);
    
        } catch (GoogleJsonResponseException e) {
          System.err.println("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
          e.printStackTrace();
        } catch (IOException e) {
          System.err.println("IOException: " + e.getMessage());
          e.printStackTrace();
        } catch (Throwable t) {
          System.err.println("Throwable: " + t.getMessage());
          t.printStackTrace();
        }
      }
    
      /**
       * Creates YouTube Playlist and adds it to the authorized account.
       */
      private static String insertPlaylist() throws IOException {
    
        /*
         * We need to first create the parts of the Playlist before the playlist itself.  Here we are
         * creating the PlaylistSnippet and adding the required data.
         */
        PlaylistSnippet playlistSnippet = new PlaylistSnippet();
        playlistSnippet.setTitle("Test Playlist " + Calendar.getInstance().getTime());
        playlistSnippet.setDescription("A private playlist created with the YouTube API v3");
    
        // Here we set the privacy status (required).
        PlaylistStatus playlistStatus = new PlaylistStatus();
        playlistStatus.setPrivacyStatus("private");
    
        /*
         * Now that we have all the required objects, we can create the Playlist itself and assign the
         * snippet and status objects from above.
         */
        Playlist youTubePlaylist = new Playlist();
        youTubePlaylist.setSnippet(playlistSnippet);
        youTubePlaylist.setStatus(playlistStatus);
    
        /*
         * This is the object that will actually do the insert request and return the result.  The
         * first argument tells the API what to return when a successful insert has been executed.  In
         * this case, we want the snippet and contentDetails info.  The second argument is the playlist
         * we wish to insert.
         */
        YouTube.Playlists.Insert playlistInsertCommand =
            youtube.playlists().insert("snippet,status", youTubePlaylist);
        Playlist playlistInserted = playlistInsertCommand.execute();
    
        // Pretty print results.
    
        System.out.println("New Playlist name: " + playlistInserted.getSnippet().getTitle());
        System.out.println(" - Privacy: " + playlistInserted.getStatus().getPrivacyStatus());
        System.out.println(" - Description: " + playlistInserted.getSnippet().getDescription());
        System.out.println(" - Posted: " + playlistInserted.getSnippet().getPublishedAt());
        System.out.println(" - Channel: " + playlistInserted.getSnippet().getChannelId() + "\n");
        return playlistInserted.getId();
    
      }
    
      /**
       * Creates YouTube PlaylistItem with specified video id and adds it to the specified playlist id
       * for the authorized account.
       *
       * @param playlistId assign to newly created playlistitem
       * @param videoId YouTube video id to add to playlistitem
       */
      private static String insertPlaylistItem(String playlistId, String videoId) throws IOException {
    
        /*
         * The Resource type (video,playlist,channel) needs to be set along with the resource id. In
         * this case, we are setting the resource to a video id, since that makes sense for this
         * playlist.
         */
        ResourceId resourceId = new ResourceId();
        resourceId.setKind("youtube#video");
        resourceId.setVideoId(videoId);
    
        /*
         * Here we set all the information required for the snippet section.  We also assign the
         * resource id from above to the snippet object.
         */
        PlaylistItemSnippet playlistItemSnippet = new PlaylistItemSnippet();
        playlistItemSnippet.setTitle("First video in the test playlist");
        playlistItemSnippet.setPlaylistId(playlistId);
        playlistItemSnippet.setResourceId(resourceId);
    
        /*
         * Now that we have all the required objects, we can create the PlaylistItem itself and assign
         * the snippet object from above.
         */
        PlaylistItem playlistItem = new PlaylistItem();
        playlistItem.setSnippet(playlistItemSnippet);
    
        /*
         * This is the object that will actually do the insert request and return the result.  The
         * first argument tells the API what to return when a successful insert has been executed.  In
         * this case, we want the snippet and contentDetails info.  The second argument is the
         * playlistitem we wish to insert.
         */
        YouTube.PlaylistItems.Insert playlistItemsInsertCommand =
            youtube.playlistItems().insert("snippet,contentDetails", playlistItem);
        PlaylistItem returnedPlaylistItem = playlistItemsInsertCommand.execute();
    
        // Pretty print results.
    
        System.out.println("New PlaylistItem name: " + returnedPlaylistItem.getSnippet().getTitle());
        System.out.println(" - Video id: " + returnedPlaylistItem.getSnippet().getResourceId().getVideoId());
        System.out.println(" - Posted: " + returnedPlaylistItem.getSnippet().getPublishedAt());
        System.out.println(" - Channel: " + returnedPlaylistItem.getSnippet().getChannelId());
        return returnedPlaylistItem.getId();
    
      }
    }
    
  • 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-playlistupdates-sample</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>youtube-cmdline-playlistupdates-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_playlistupdates_sample.PlaylistUpdates</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 Client ID",
        "client_secret": "Enter Client Secret"
      }
    }
    

JavaScript

この例では、JavaScript クライアント ライブラリを使用しています。

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

// After the API loads, call a function to enable the playlist creation form.
function handleAPILoaded() {
  enableForm();
}

// Enable the form for creating a playlist.
function enableForm() {
  $('#playlist-button').attr('disabled', false);
}

// Create a private playlist.
function createPlaylist() {
  var request = gapi.client.youtube.playlists.insert({
    part: 'snippet,status',
    resource: {
      snippet: {
        title: 'Test Playlist',
        description: 'A private playlist created with the YouTube API'
      },
      status: {
        privacyStatus: 'private'
      }
    }
  });
  request.execute(function(response) {
    var result = response.result;
    if (result) {
      playlistId = result.id;
      $('#playlist-id').val(playlistId);
      $('#playlist-title').html(result.snippet.title);
      $('#playlist-description').html(result.snippet.description);
    } else {
      $('#status').html('Could not create playlist');
    }
  });
}

// Add a video ID specified in the form to the playlist.
function addVideoToPlaylist() {
  addToPlaylist($('#video-id').val());
}

// Add a video to a playlist. The "startPos" and "endPos" values let you
// start and stop the video at specific times when the video is played as
// part of the playlist. However, these values are not set in this example.
function addToPlaylist(id, startPos, endPos) {
  var details = {
    videoId: id,
    kind: 'youtube#video'
  }
  if (startPos != undefined) {
    details['startAt'] = startPos;
  }
  if (endPos != undefined) {
    details['endAt'] = endPos;
  }
  var request = gapi.client.youtube.playlistItems.insert({
    part: 'snippet',
    resource: {
      snippet: {
        playlistId: playlistId,
        resourceId: details
      }
    }
  });
  request.execute(function(response) {
    $('#status').html('<pre>' + JSON.stringify(response.result) + '</pre>');
  });
}

.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 playlist_updates
  {
    static void Main(string[] args)
    {
      CommandLine.EnableExceptionHandling();
      CommandLine.DisplayGoogleSampleHeader("YouTube Data API: Playlist Updates");

      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 newPlaylist = new Playlist();
      newPlaylist.Snippet = new PlaylistSnippet();
      newPlaylist.Snippet.Title = "Test Playlist";
      newPlaylist.Snippet.Description = "A playlist created with the YouTube API v3";
      newPlaylist.Status = new PlaylistStatus();
      newPlaylist.Status.PrivacyStatus = "public";
      newPlaylist = youtube.Playlists.Insert(newPlaylist, "snippet,status").Fetch();

      var newPlaylistItem = new PlaylistItem();
      newPlaylistItem.Snippet = new PlaylistItemSnippet();
      newPlaylistItem.Snippet.PlaylistId = newPlaylist.Id;
      newPlaylistItem.Snippet.ResourceId = new ResourceId();
      newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video";
      newPlaylistItem.Snippet.ResourceId.VideoId = "GNRMeaz6QRI";
      newPlaylistItem = youtube.PlaylistItems.Insert(newPlaylistItem, "snippet").Fetch();

      CommandLine.WriteLine(String.Format("Playlist item id {0} was added to playlist id {1}.", newPlaylistItem.Id, newPlaylist.Id));

      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.Youtube.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.cloud.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 {
    // This code creates a new, private playlist in the authorized user's
    // channel and adds a video to the playlist.

    // 1. Create the snippet for the playlist. Set its title and description.
    $playlistSnippet = new Google_Service_YouTube_PlaylistSnippet();
    $playlistSnippet->setTitle('Test Playlist  ' . date("Y-m-d H:i:s"));
    $playlistSnippet->setDescription('A private playlist created with the YouTube API v3');

    // 2. Define the playlist's status.
    $playlistStatus = new Google_Service_YouTube_PlaylistStatus();
    $playlistStatus->setPrivacyStatus('private');

    // 3. Define a playlist resource and associate the snippet and status
    // defined above with that resource.
    $youTubePlaylist = new Google_Service_YouTube_Playlist();
    $youTubePlaylist->setSnippet($playlistSnippet);
    $youTubePlaylist->setStatus($playlistStatus);

    // 4. Call the playlists.insert method to create the playlist. The API
    // response will contain information about the new playlist.
    $playlistResponse = $youtube->playlists->insert('snippet,status',
        $youTubePlaylist, array());
    $playlistId = $playlistResponse['id'];

    // 5. Add a video to the playlist. First, define the resource being added
    // to the playlist by setting its video ID and kind.
    $resourceId = new Google_Service_YouTube_ResourceId();
    $resourceId->setVideoId('SZj6rAYkYOg');
    $resourceId->setKind('youtube#video');

    // Then define a snippet for the playlist item. Set the playlist item's
    // title if you want to display a different value than the title of the
    // video being added. Add the resource ID and the playlist ID retrieved
    // in step 4 to the snippet as well.
    $playlistItemSnippet = new Google_Service_YouTube_PlaylistItemSnippet();
    $playlistItemSnippet->setTitle('First video in the test playlist');
    $playlistItemSnippet->setPlaylistId($playlistId);
    $playlistItemSnippet->setResourceId($resourceId);

    // Finally, create a playlistItem resource and add the snippet to the
    // resource, then call the playlistItems.insert method to add the playlist
    // item.
    $playlistItem = new Google_Service_YouTube_PlaylistItem();
    $playlistItem->setSnippet($playlistItemSnippet);
    $playlistItemResponse = $youtube->playlistItems->insert(
        'snippet,contentDetails', $playlistItem, array());

    $htmlBody .= "<h3>New Playlist</h3><ul>";
    $htmlBody .= sprintf('<li>%s (%s)</li>',
        $playlistResponse['snippet']['title'],
        $playlistResponse['id']);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>New PlaylistItem</h3><ul>";
    $htmlBody .= sprintf('<li>%s (%s)</li>',
        $playlistItemResponse['snippet']['title'],
        $playlistItemResponse['id']);
    $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 {
  // If the user hasn't authorized the app, initiate the OAuth flow
  $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>New Playlist</title>
</head>
<body>
  <?=$htmlBody?>
</body>
</html>

Python

この例では、Python クライアント ライブラリを使用しています。

#!/usr/bin/python

import httplib2
import os
import sys

from apiclient.discovery import build
from apiclient.errors import HttpError
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.cloud.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.cloud.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 full read/write access to the
# authenticated user's account.
YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
  message=MISSING_CLIENT_SECRETS_MESSAGE,
  scope=YOUTUBE_READ_WRITE_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()))

# This code creates a new, private playlist in the authorized user's channel.
playlists_insert_response = youtube.playlists().insert(
  part="snippet,status",
  body=dict(
    snippet=dict(
      title="Test Playlist",
      description="A private playlist created with the YouTube API v3"
    ),
    status=dict(
      privacyStatus="private"
    )
  )
).execute()

print "New playlist id: %s" % playlists_insert_response["id"]

エラー

次の表は、このメソッドを呼び出したときに API からレスポンスとして返される可能性のあるエラー メッセージの一覧です。詳細については、エラー メッセージのドキュメントを参照してください。

エラー タイプ エラーの詳細 説明
invalidValue invalidPlaylistSnippet リクエストに指定されている再生リスト スニペットは無効です。
required playlistTitleRequired リクエストでは、再生リストのタイトルを指定する必要があります。

実際に試してみる

API Explorer を使用し、ライブ データに対してこのメソッドを呼び出して、API リクエストとレスポンスを確認してください。