Cria uma playlist. Faça um teste agora ou veja um exemplo.
Solicitação
Solicitação HTTP
POST https://www.googleapis.com/youtube/v3/playlists
Autorização
Esta solicitação requer autorização com pelo menos um dos seguintes escopos (saiba mais sobre autenticação e autorização).
Escopo |
---|
https://www.googleapis.com/auth/youtubepartner |
https://www.googleapis.com/auth/youtube |
Parâmetros
A tabela a seguir lista os parâmetros que esta consulta suporta. Todos os parâmetros listados são os parâmetros de consulta.
Parâmetros | ||
---|---|---|
Parâmetros obrigatórios | ||
part |
string O parâmetro part tem duas finalidades nesta operação: identifica as propriedades que serão definidas pela operação de gravação e as propriedades que serão incluídas pela resposta da API.Os nomes part que podem ser incluídos no valor do parâmetro são snippet e status . |
Corpo de solicitação
Forneça um recurso de playlist no corpo da solicitação. Para esse recurso:
-
É necessário especificar um valor para essas propriedades:
snippet.title
-
Você pode definir valores para estas propriedades:
snippet.title
snippet.description
status.privacyStatus
snippet.tags[]
Resposta
Se for bem-sucedido, este método retorna um recurso de playlist no corpo da resposta.
Exemplos
Observação: os exemplos de código a seguir não representam todas as linguagens de programação suportadas. Consulte a documentação bibliotecas clientes para uma lista das linguagens suportadas.
Java
O exemplo de código abaixo chama o método playlists.insert
da API para criar uma lista de reprodução privada de propriedade do canal que está autorizando a solicitação.
Este exemplo usa a biblioteca cliente 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.data; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.services.samples.youtube.cmdline.Auth; import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.model.*; import com.google.common.collect.Lists; import java.io.IOException; import java.util.Calendar; import java.util.List; /** * Creates a new, private playlist in the authorized user's channel and add * a video to that new playlist. * * @author Jeremy Walker */ public class PlaylistUpdates { /** * Define a global instance of a Youtube object, which will be used * to make YouTube Data API requests. */ private static YouTube youtube; /** * Define a global variable that identifies the video that will be added * to the new playlist. */ private static final String VIDEO_ID = "SZj6rAYkYOg"; /** * Authorize the user, create a playlist, and add an item to the playlist. * * @param args command line args (not used). */ public static void main(String[] args) { // This OAuth 2.0 access scope allows for full read/write access to the // authenticated user's account. List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube"); try { // Authorize the request. Credential credential = Auth.authorize(scopes, "playlistupdates"); // This object is used to make YouTube Data API requests. youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential) .setApplicationName("youtube-cmdline-playlistupdates-sample") .build(); // Create a new, private playlist in the authorized user's channel. String playlistId = insertPlaylist(); // If a valid playlist was created, add 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(); } } /** * Create a playlist and add it to the authorized account. */ private static String insertPlaylist() throws IOException { // This code constructs the playlist resource that is being inserted. // It defines the playlist's title, description, and privacy status. PlaylistSnippet playlistSnippet = new PlaylistSnippet(); playlistSnippet.setTitle("Test Playlist " + Calendar.getInstance().getTime()); playlistSnippet.setDescription("A private playlist created with the YouTube API v3"); PlaylistStatus playlistStatus = new PlaylistStatus(); playlistStatus.setPrivacyStatus("private"); Playlist youTubePlaylist = new Playlist(); youTubePlaylist.setSnippet(playlistSnippet); youTubePlaylist.setStatus(playlistStatus); // Call the API to insert the new playlist. In the API call, the first // argument identifies the resource parts that the API response should // contain, and the second argument is the playlist being inserted. YouTube.Playlists.Insert playlistInsertCommand = youtube.playlists().insert("snippet,status", youTubePlaylist); Playlist playlistInserted = playlistInsertCommand.execute(); // Print data from the API response and return the new playlist's // unique playlist ID. 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(); } /** * Create a playlist item with the specified video ID and add it to the * specified playlist. * * @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 { // Define a resourceId that identifies the video being added to the // playlist. ResourceId resourceId = new ResourceId(); resourceId.setKind("youtube#video"); resourceId.setVideoId(videoId); // Set fields included in the playlistItem resource's "snippet" part. PlaylistItemSnippet playlistItemSnippet = new PlaylistItemSnippet(); playlistItemSnippet.setTitle("First video in the test playlist"); playlistItemSnippet.setPlaylistId(playlistId); playlistItemSnippet.setResourceId(resourceId); // Create the playlistItem resource and set its snippet to the // object created above. PlaylistItem playlistItem = new PlaylistItem(); playlistItem.setSnippet(playlistItemSnippet); // Call the API to add the playlist item to the specified playlist. // In the API call, the first argument identifies the resource parts // that the API response should contain, and the second argument is // the playlist item being inserted. YouTube.PlaylistItems.Insert playlistItemsInsertCommand = youtube.playlistItems().insert("snippet,contentDetails", playlistItem); PlaylistItem returnedPlaylistItem = playlistItemsInsertCommand.execute(); // Print data from the API response and return the new playlist // item's unique playlistItem ID. 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(); } }
JavaScript
O código JavaScript abaixo executa as seguintes funções:
- Ele permite que o usuário crie uma lista de reprodução privada e veja informações sobre a lista de reprodução recém-criada.
- Ele permite que o usuário adicione um vídeo à lista de reprodução e veja a resposta da API dessa operação. O código JavaScript consegue especificar a posição em que o vídeo deve começar e parar de reproduzir, mas o HTML abaixo não fornece uma maneira de especificar esses valores.
Novamente, você precisa atualizar o ID do cliente no arquivo auth.js
para executar este código.
Este exemplo usa a biblioteca cliente 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
O exemplo de código abaixo chama o método playlists.insert
da API para criar uma lista de reprodução privada de propriedade do canal que está autorizando a solicitação.
Este exemplo usa a biblioteca cliente .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: create a playlist. /// 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 PlaylistUpdates { [STAThread] static void Main(string[] args) { Console.WriteLine("YouTube Data API: Playlist Updates"); Console.WriteLine("=================================="); try { new PlaylistUpdates().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 full read/write access to the // authenticated user's account. new[] { YouTubeService.Scope.Youtube }, "user", CancellationToken.None, new FileDataStore(this.GetType().ToString()) ); } var youtubeService = new YouTubeService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = this.GetType().ToString() }); // Create a new, private playlist in the authorized user's channel. 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 = await youtubeService.Playlists.Insert(newPlaylist, "snippet,status").ExecuteAsync(); // Add a video to the newly created playlist. 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 = await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync(); Console.WriteLine("Playlist item id {0} was added to playlist id {1}.", newPlaylistItem.Id, newPlaylist.Id); } } }
PHP
O exemplo de código abaixo chama o método playlists.insert
da API para criar uma lista de reprodução privada de propriedade do canal que está autorizando a solicitação.
Este exemplo usa a biblioteca cliente 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
O exemplo de código abaixo chama o método playlists.insert
da API para criar uma lista de reprodução privada de propriedade do canal que está autorizando a solicitação.
Este exemplo usa a biblioteca cliente 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"]
Erros
A tabela abaixo identifica as mensagens de erro que a API pode retornar em resposta a uma chamada para este método. Consulte a documentação mensagem de erro para mais detalhes.
Tipo de erro | Detalhe do erro | Descrição |
---|---|---|
invalidValue |
invalidPlaylistSnippet |
A solicitação fornece um snippet de playlist inválido. |
required |
playlistTitleRequired |
A solicitação deve especificar um título da playlist. |
Conheça agora.
Use o Explorador de API para chamar este método em dados ativos e ver a solicitação e a resposta da API.