Playlists: update

Modifies a playlist. For example, you could change a playlist's title, description, or privacy status. Try it now.

Quota impact: A call to this method has a quota cost of 50 units in addition to the costs of the specified resource parts.

Usage

Request

HTTP request

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

Authorization

This request requires authorization with at least one of the following scopes (read more about authentication and authorization).

Scope
https://www.googleapis.com/auth/youtubepartner
https://www.googleapis.com/auth/youtube
https://www.googleapis.com/auth/youtube.force-ssl

Parameters

The following table lists the parameters that this query supports. All of the parameters listed are query parameters.

Parameters
Required parameters
part string
The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.

Note that this method will override the existing values for mutable properties that are contained in any parts that the request body specifies. For example, a playlist's description is contained in the snippet part, which must be included in the request body. If the request does not specify a value for the snippet.description property, the playlist's existing description will be deleted.

The following list contains the part names that you can include in the parameter value and the quota cost for each part:
  • contentDetails: 2
  • id: 0
  • localizations: 2
  • player: 0
  • snippet: 2
  • status: 2
Optional parameters
onBehalfOfContentOwner string
This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.

The onBehalfOfContentOwner parameter indicates that the request's authorization credentials identify a YouTube CMS user who is acting on behalf of the content owner specified in the parameter value. This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and get access to all their video and channel data, without having to provide authentication credentials for each individual channel. The CMS account that the user authenticates with must be linked to the specified YouTube content owner.

Request body

Provide a playlist resource in the request body. For that resource:

  • You must specify a value for these properties:

    • id
    • snippet.title

  • You can set values for these properties:

    • snippet.title
    • snippet.description
    • status.privacyStatus
    • snippet.tags[]
    • snippet.defaultLanguage
    • localizations.(key)
    • localizations.(key).title
    • localizations.(key).description

    If you are submitting an update request, and your request does not specify a value for a property that already has a value, the property's existing value will be deleted.

Response

If successful, this method returns a playlist resource in the response body.

Examples

Note: The following code samples may not represent all supported programming languages. See the client libraries documentation for a list of supported languages.

Java

This sample demonstrates how to use the following API methods to set and retrieve localized metadata for a playlist:
  • It calls the playlists.update method to update the default language of a playlist's metadata and to add a localized version of this metadata in a selected language.
  • It calls the playlists.list method with the hl parameter set to a specific language to retrieve localized metadata in that language.
  • It calls the playlists.list method and includes localizations in the part parameter value to retrieve all of the localized metadata for that playlist.

This example uses the Java client library.

/*
 * Copyright (c) 2015 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.client.util.ArrayMap;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Playlist;
import com.google.api.services.youtube.model.PlaylistListResponse;
import com.google.api.services.youtube.model.PlaylistLocalization;
import com.google.common.collect.Lists;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

/**
 * This sample sets and retrieves localized metadata for a playlist by:
 *
 * 1. Updating language of the default metadata and setting localized metadata
 *   for a playlist via "playlists.update" method.
 * 2. Getting the localized metadata for a playlist in a selected language using the
 *   "playlists.list" method and setting the "hl" parameter.
 * 3. Listing the localized metadata for a playlist using the "playlists.list" method
 *   and including "localizations" in the "part" parameter.
 *
 * @author Ibrahim Ulukaya
 */
public class PlaylistLocalizations {

    /**
     * Define a global instance of a YouTube object, which will be used to make
     * YouTube Data API requests.
     */
    private static YouTube youtube;


    /**
     * Set and retrieve localized metadata for a 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, "localizations");

            // This object is used to make YouTube Data API requests.
            youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                    .setApplicationName("youtube-cmdline-localizations-sample").build();

            // Prompt the user to specify the action of the be achieved.
            String actionString = getActionFromUser();
            System.out.println("You chose " + actionString + ".");
            //Map the user input to the enum values.
            Action action = Action.valueOf(actionString.toUpperCase());

            switch (action) {
                case SET:
                    setPlaylistLocalization(getId("playlist"), getDefaultLanguage(),
                            getLanguage(), getMetadata("title"), getMetadata("description"));
                    break;
                case GET:
                    getPlaylistLocalization(getId("playlist"), getLanguage());
                    break;
                case LIST:
                    listPlaylistLocalizations(getId("playlist"));
                    break;
            }
        } catch (GoogleJsonResponseException e) {
            System.err.println("GoogleJsonResponseException code: " + 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();
        }
    }

    /**
     * Updates a playlist's default language and sets its localized metadata.
     *
     * @param playlistId The id parameter specifies the playlist ID for the resource
     * that is being updated.
     * @param defaultLanguage The language of the playlist's default metadata
     * @param language The language of the localized metadata
     * @param title The localized title to be set
     * @param description The localized description to be set
     * @throws IOException
     */
    private static void setPlaylistLocalization(String playlistId, String defaultLanguage,
        String language, String title, String description) throws IOException {
        // Call the YouTube Data API's playlists.list method to retrieve playlists.
        PlaylistListResponse playlistListResponse = youtube.playlists().
            list("snippet,localizations").setId(playlistId).execute();

        // Since the API request specified a unique playlist ID, the API
        // response should return exactly one playlist. If the response does
        // not contain a playlist, then the specified playlist ID was not found.
        List<Playlist> playlistList = playlistListResponse.getItems();
        if (playlistList.isEmpty()) {
            System.out.println("Can't find a playlist with ID: " + playlistId);
            return;
        }
        Playlist playlist = playlistList.get(0);

        // Modify playlist's default language and localizations properties.
        // Ensure that a value is set for the resource's snippet.defaultLanguage property.
        playlist.getSnippet().setDefaultLanguage(defaultLanguage);

        // Preserve any localizations already associated with the playlist. If the
        // playlist does not have any localizations, create a new array. Append the
        // provided localization to the list of localizations associated with the playlist.
        Map<String, PlaylistLocalization> localizations = playlist.getLocalizations();
        if (localizations == null) {
            localizations = new ArrayMap<String, PlaylistLocalization>();
            playlist.setLocalizations(localizations);
        }
        PlaylistLocalization playlistLocalization = new PlaylistLocalization();
        playlistLocalization.setTitle(title);
        playlistLocalization.setDescription(description);
        localizations.put(language, playlistLocalization);

        // Update the playlist resource by calling the playlists.update() method.
        Playlist playlistResponse = youtube.playlists().update("snippet,localizations", playlist)
            .execute();

        // Print information from the API response.
        System.out.println("\n================== Updated Playlist ==================\n");
        System.out.println("  - ID: " + playlistResponse.getId());
        System.out.println("  - Default Language: " +
            playlistResponse.getSnippet().getDefaultLanguage());
        System.out.println("  - Title(" + language + "): " +
            playlistResponse.getLocalizations().get(language).getTitle());
        System.out.println("  - Description(" + language + "): " +
            playlistResponse.getLocalizations().get(language).getDescription());
        System.out.println("\n-------------------------------------------------------------\n");
    }

    /**
     * Returns localized metadata for a playlist in a selected language.
     * If the localized text is not available in the requested language,
     * this method will return text in the default language.
     *
     * @param playlistId The id parameter specifies the playlist ID for the resource
     * that is being updated.
     * @param language The language of the localized metadata
     * @throws IOException
     */
    private static void getPlaylistLocalization(String playlistId, String language) throws IOException {
        // Call the YouTube Data API's playlists.list method to retrieve playlists.
        PlaylistListResponse playlistListResponse = youtube.playlists().
            list("snippet").setId(playlistId).set("hl", language).execute();

        // Since the API request specified a unique playlist ID, the API
        // response should return exactly one playlist. If the response does
        // not contain a playlist, then the specified playlist ID was not found.
        List<Playlist> playlistList = playlistListResponse.getItems();
        if (playlistList.isEmpty()) {
            System.out.println("Can't find a playlist with ID: " + playlistId);
            return;
        }
        Playlist playlist = playlistList.get(0);

        // Print information from the API response.
        System.out.println("\n================== Playlist ==================\n");
        System.out.println("  - ID: " + playlist.getId());
        System.out.println("  - Title(" + language + "): " +
            playlist.getLocalizations().get(language).getTitle());
        System.out.println("  - Description(" + language + "): " +
            playlist.getLocalizations().get(language).getDescription());
        System.out.println("\n-------------------------------------------------------------\n");
    }

    /**
     * Returns a list of localized metadata for a playlist.
     *
     * @param playlistId The id parameter specifies the playlist ID for the resource
     * that is being updated.
     * @throws IOException
     */
    private static void listPlaylistLocalizations(String playlistId) throws IOException {
        // Call the YouTube Data API's playlists.list method to retrieve playlists.
        PlaylistListResponse playlistListResponse = youtube.playlists().
            list("snippet,localizations").setId(playlistId).execute();

        // Since the API request specified a unique playlist ID, the API
        // response should return exactly one playlist. If the response does
        // not contain a playlist, then the specified playlist ID was not found.
        List<Playlist> playlistList = playlistListResponse.getItems();
        if (playlistList.isEmpty()) {
            System.out.println("Can't find a playlist with ID: " + playlistId);
            return;
        }
        Playlist playlist = playlistList.get(0);
        Map<String, PlaylistLocalization> localizations = playlist.getLocalizations();

        // Print information from the API response.
        System.out.println("\n================== Playlist ==================\n");
        System.out.println("  - ID: " + playlist.getId());
        for (String language : localizations.keySet()) {
            System.out.println("  - Title(" + language + "): " +
                localizations.get(language).getTitle());
            System.out.println("  - Description(" + language + "): " +
                localizations.get(language).getDescription());
        }
        System.out.println("\n-------------------------------------------------------------\n");
    }

    /*
     * Prompt the user to enter a resource ID. Then return the ID.
     */
    private static String getId(String resource) throws IOException {

        String id = "";

        System.out.print("Please enter a " + resource + " id: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        id = bReader.readLine();

        System.out.println("You chose " + id + " for localizations.");
        return id;
    }

    /*
     * Prompt the user to enter the localized metadata. Then return the metadata.
     */
    private static String getMetadata(String type) throws IOException {

        String metadata = "";

        System.out.print("Please enter a localized " + type + ": ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        metadata = bReader.readLine();

        if (metadata.length() < 1) {
            // If nothing is entered, defaults to type.
          metadata = type + "(localized)";
        }

        System.out.println("You chose " + metadata + " as localized "+ type + ".");
        return metadata;
    }

    /*
     * Prompt the user to enter the language for the resource's default metadata.
     * Then return the language.
     */
    private static String getDefaultLanguage() throws IOException {

        String defaultlanguage = "";

        System.out.print("Please enter the language for the resource's default metadata: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        defaultlanguage = bReader.readLine();

        if (defaultlanguage.length() < 1) {
            // If nothing is entered, defaults to "en".
          defaultlanguage = "en";
        }

        System.out.println("You chose " + defaultlanguage +
            " as the language for the resource's default metadata.");
        return defaultlanguage;
    }

    /*
     * Prompt the user to enter a language for the localized metadata. Then return the language.
     */
    private static String getLanguage() throws IOException {

        String language = "";

        System.out.print("Please enter the localized metadata language: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        language = bReader.readLine();

        if (language.length() < 1) {
            // If nothing is entered, defaults to "de".
            language = "de";
        }

        System.out.println("You chose " + language + " as the localized metadata language.");
        return language;
    }

    /*
     * Prompt the user to enter an action. Then return the action.
     */
    private static String getActionFromUser() throws IOException {

        String action = "";

        System.out.print("Please choose action to be accomplished: ");
        System.out.print("Options are: 'set', 'get' and 'list' ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
        action = bReader.readLine();

        return action;
    }

    public enum Action {
      SET,
      GET,
      LIST
    }
}

PHP

This sample demonstrates how to use the following API methods to set and retrieve localized metadata for a playlist:
  • It calls the playlists.update method to update the default language of a playlist's metadata and to add a localized version of this metadata in a selected language.
  • It calls the playlists.list method with the hl parameter set to a specific language to retrieve localized metadata in that language.
  • It calls the playlists.list method and includes localizations in the part parameter value to retrieve all of the localized metadata for that playlist.

This example uses the PHP client library.

<?php

/**
 * This sample sets and retrieves localized metadata for a playlist by:
 *
 * 1. Updating language of the default metadata and setting localized metadata
 *   for a playlist via "playlists.update" method.
 * 2. Getting the localized metadata for a playlist in a selected language using the
 *   "playlists.list" method and setting the "hl" parameter.
 * 3. Listing the localized metadata for a playlist using the "playlists.list" method
 *   and including "localizations" in the "part" parameter.
 *
 * @author Ibrahim Ulukaya
 */

/**
 * 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();

$htmlBody = <<<END
<form method="GET">
  <div>
    Action:
    <select id="action" name="action">
      <option value="set">Set Localization - Fill in: playlist ID, default language, language, , title and description</option>
      <option value="get">Get Localization- Fill in: playlist ID, language</option>
      <option value="list">List Localizations - Fill in: playlist ID, language</option>
    </select>
  </div>
  <br>
  <div>
    Playlist ID: <input type="text" id="playlistId" name="playlistId" placeholder="Enter Playlist ID">
  </div>
  <br>
  <div>
    Default Language: <input type="text" id="defaultLanguage" name="defaultLanguage" placeholder="Enter Default Language (BCP-47 language code)">
  </div>
  <br>
  <div>
    Language: <input type="text" id="language" name="language" placeholder="Enter Local Language (BCP-47 language code)">
  </div>
  <br>
  <div>
    Title: <input type="text" id="title" name="title" placeholder="Enter Title">
  </div>
  <br>
  <div>
    Description: <input type="text" id="description" name="description" placeholder="Enter Description">
  </div>
  <br>
  <input type="submit" value="GO!">
</form>
END;

/*
 * You can acquire an OAuth 2.0 client ID and client secret from the
 * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
 * 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);

/*
 * This OAuth 2.0 access scope allows for full read/write access to the
 * authenticated user's account.
 */
$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()) {
  $htmlBody = '';
  // This code executes if the user enters an action in the form
  // and submits the form. Otherwise, the page displays the form above.
  if (isset($_GET['action'])) {
    $resource = $_GET['resource'];
    $playlistId = $_GET['playlistId'];
    $language = $_GET['language'];
    $defaultLanguage = $_GET['defaultLanguage'];
    $title = $_GET['title'];
    $description = $_GET['description'];
    try {
      switch ($_GET['action']) {
        case 'set':
          setPlaylistLocalization($youtube, $playlistId, $defaultLanguage,
              $language, $title, $description, $htmlBody);
          break;
        case 'get':
          getPlaylistLocalization($youtube, $playlistId, $language, $htmlBody);
          break;
        case 'list':
          listPlaylistLocalizations($youtube, $playlistId, $htmlBody);
          break;
      }
    } 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;
}


/**
 * Updates a playlist's default language and sets its localized metadata.
 *
 * @param Google_Service_YouTube $youtube YouTube service object.
 * @param string $playlistId The id parameter specifies the playlist ID for the resource
 * that is being updated.
 * @param string $defaultLanguage The language of the playlist's default metadata
 * @param string $language The language of the localized metadata
 * @param string $title The localized title to be set
 * @param string $description The localized description to be set
 * @param $htmlBody - html body.
 */
function setPlaylistLocalization(Google_Service_YouTube $youtube, $playlistId, $defaultLanguage,
    $language, $title, $description, &$htmlBody) {
  // Call the YouTube Data API's playlists.list method to retrieve playlists.
  $playlists = $youtube->playlists->listPlaylists("snippet,localizations", array(
      'id' => $playlistId
  ));

  // If $playlists is empty, the specified playlist was not found.
  if (empty($playlists)) {
    $htmlBody .= sprintf('<h3>Can\'t find a playlist with playlist id: %s</h3>', $playlistId);
  } else {
    // Since the request specified a playlist ID, the response only
    // contains one playlist resource.
    $updatePlaylist = $playlists[0];

    // Modify playlist's default language and localizations properties.
    // Ensure that a value is set for the resource's snippet.defaultLanguage property.
    $updatePlaylist['snippet']['defaultLanguage'] = $defaultLanguage;
    $localizations = $updatePlaylist['localizations'];

    if (is_null($localizations)) {
      $localizations = array();
    }
    $localizations[$language] = array('title' => $title, 'description' => $description);
    $updatePlaylist['localizations'] = $localizations;

    // Call the YouTube Data API's playlists.update method to update an existing playlist.
    $playlistUpdateResponse = $youtube->playlists->update("snippet,localizations", $updatePlaylist);

    $htmlBody .= "<h2>Updated playlist</h2><ul>";
    $htmlBody .= sprintf('<li>(%s) default language: %s</li>', $playlistId,
        $playlistUpdateResponse['snippet']['defaultLanguage']);
    $htmlBody .= sprintf('<li>title(%s): %s</li>', $language,
        $playlistUpdateResponse['localizations'][$language]['title']);
    $htmlBody .= sprintf('<li>description(%s): %s</li>', $language,
        $playlistUpdateResponse['localizations'][$language]['description']);
    $htmlBody .= '</ul>';
  }
}

/**
 * Returns localized metadata for a playlist in a selected language.
 * If the localized text is not available in the requested language,
 * this method will return text in the default language.
 *
 * @param Google_Service_YouTube $youtube YouTube service object.
 * @param string $playlistId The videoId parameter instructs the API to return the
 * localized metadata for the playlist specified by the playlist id.
 * @param string language The language of the localized metadata.
 * @param $htmlBody - html body.
 */
function getPlaylistLocalization(Google_Service_YouTube $youtube, $playlistId,
    $language, &$htmlBody) {
  // Call the YouTube Data API's playlists.list method to retrieve playlists.
  $playlists = $youtube->playlists->listPlaylists("snippet", array(
      'id' => $playlistId,
      'hl' => $language
  ));

  // If $playlists is empty, the specified playlist was not found.
  if (empty($playlists)) {
    $htmlBody .= sprintf('<h3>Can\'t find a playlist with playlist id: %s</h3>', $playlistId);
  } else {
    // Since the request specified a playlist ID, the response only
    // contains one playlist resource.
    $localized = $playlists[0]["snippet"]["localized"];

    $htmlBody .= "<h3>Playlist</h3><ul>";
    $htmlBody .= sprintf('<li>title(%s): %s</li>', $language, $localized['title']);
    $htmlBody .= sprintf('<li>description(%s): %s</li>', $language, $localized['description']);
    $htmlBody .= '</ul>';
  }
}

/**
 * Returns a list of localized metadata for a playlist.
 *
 * @param Google_Service_YouTube $youtube YouTube service object.
 * @param string $playlistId The videoId parameter instructs the API to return the
 * localized metadata for the playlist specified by the playlist id.
 * @param $htmlBody - html body.
 */
function listPlaylistLocalizations(Google_Service_YouTube $youtube, $playlistId, &$htmlBody) {
  // Call the YouTube Data API's playlists.list method to retrieve playlists.
  $playlists = $youtube->playlists->listPlaylists("snippet", array(
      'id' => $playlistId
  ));

  // If $playlists is empty, the specified playlist was not found.
  if (empty($playlists)) {
    $htmlBody .= sprintf('<h3>Can\'t find a playlist with playlist id: %s</h3>', $playlistId);
  } else {
    // Since the request specified a playlist ID, the response only
    // contains one playlist resource.
    $localizations = $playlists[0]["localizations"];

    $htmlBody .= "<h3>Playlist</h3><ul>";
    foreach ($localizations as $language => $localization) {
      $htmlBody .= sprintf('<li>title(%s): %s</li>', $language, $localization['title']);
      $htmlBody .= sprintf('<li>description(%s): %s</li>', $language, $localization['description']);
    }
    $htmlBody .= '</ul>';
  }
}
?>

<!doctype html>
<html>
<head>
<title>Set and retrieve localized metadata for a playlist</title>
</head>
<body>
  <?=$htmlBody?>
</body>
</html>

Python

This sample demonstrates how to use the following API methods to set and retrieve localized metadata for a playlist:
  • It calls the playlists.update method to update the default language of a playlist's metadata and to add a localized version of this metadata in a selected language.
  • It calls the playlists.list method with the hl parameter set to a specific language to retrieve localized metadata in that language.
  • It calls the playlists.list method and includes localizations in the part parameter value to retrieve all of the localized metadata for that playlist.

This example uses the Python client library.

#!/usr/bin/python

# Usage example:
# python playlist_localizations.py --action='<action>' --playlist_id='<playlist_id>' --default_language='<default_language>' --language='<language>' --title='<title>' --description='<description>'

import argparse
import os

import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow


# 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 Cloud Console }} at
# {{ https://cloud.google.com/console }}.
# 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_secret.json'

# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account.
SCOPES = ['https://www.googleapis.com/auth/youtube']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'

ACTIONS = ('get', 'list', 'set')

# Authorize the request and store authorization credentials.
def get_authenticated_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)

# Call the API's playlists.update method to update an existing playlist's default language,
# localized title and description in a specific language.
def set_playlist_localization(youtube, args):

  results = youtube.playlists().list(
    part='snippet,localizations',
    id=args.playlist_id
  ).execute()

  playlist = results['items'][0]

  # If the language argument is set, set the localized title and description
  # for that language. The "title" and "description" arguments have default
  # values to make the script simpler to run as a demo. In an actual app, you
  # would likely want to set those arguments also.
  if args.language and args.language != '':
    if 'localizations' not in playlist:
      playlist['localizations'] = {}

    playlist['localizations'][args.language] = {
      'title': args.title,
      'description': args.description
    }

  # If the default language is set AND there is localized metadata for that
  # language, set the video's title and description to match the localized
  # title and description for the newly set default language.
  if args.default_language:
    playlist['snippet']['defaultLanguage'] = args.default_language
    if args.default_language in playlist['localizations']:
      playlist['snippet']['title'] = (
          playlist['localizations'][args.default_language]['title'])
      playlist['snippet']['description'] = (
          playlist['localizations'][args.default_language]['description'])

  print(playlist)

  # Update the playlist resource
  update_result = youtube.playlists().update(
    part='snippet,localizations',
    body=playlist
  ).execute()

  # Print the actions taken by running the script.
  if args.language:
    for language in update_result['localizations']:
      # Languages with locales, like "pt-br" are returned as pt-BR in metadata.
      # This ensures that the language specified when running the script can be
      # matched to the language returned in the metadata.
      if language.lower() == args.language.lower():
        localization = update_result['localizations'][args.language]
        print ('Updated playlist \'%s\' localized title to \'%s\''
               ' and description to \'%s\' in language \'%s\'' %
               (args.playlist_id,
                localization['title'],
                localization['description'],
                args.language))
        break

  if (args.default_language and
      args.default_language == update_result['snippet']['defaultLanguage']):
    print 'Updated default language to %s' % args.default_language

# Call the API's playlists.list method to retrieve an existing playlist localization.
# If the localized text is not available in the requested language,
# this method will return text in the default language.
def get_playlist_localization(youtube, args):
  results = youtube.playlists().list(
    part='snippet',
    id=args.playlist_id,
    hl=args.language
  ).execute()

  # The localized object contains localized text if the hl parameter specified
  # a language for which localized text is available. Otherwise, the localized
  # object will contain metadata in the default language.
  localized = results['items'][0]['snippet']['localized']

  print ('Playlist title is "%s" and description is "%s" in language "%s"'
         % (localized['title'], localized['description'], args.language))


# Call the API's playlists.list method to list existing localizations
# for the playlist.
def list_playlist_localizations(youtube, args):
  results = youtube.playlists().list(
    part='snippet,localizations',
    id=args.playlist_id
  ).execute()

  if 'localizations' in results['items'][0]:
    localizations = results['items'][0]['localizations']

    for language, localization in localizations.iteritems():
      print ('Playlist title is "%s" and description is "%s" in language "%s"'
             % (localization['title'], localization['description'], language))
  else:
    print 'There aren\'t any localizations for this playlist yet.'


if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  # The action to be processed: 'get', 'list', and 'set' are supported.
  parser.add_argument('--action', required=True, help='Action', choices=ACTIONS)
  # The ID of the selected YouTube olaylist.
  parser.add_argument('--playlist_id',
    help='The playlist ID for which localizations are being set or retrieved.',
    required=True)
  # The langauge of the playlist's default metadata.
  parser.add_argument('--default_language',
    help='Default language to set for the playlist.')
  # The language of the localization that is being set or retrieved.
  parser.add_argument('--language', help='Language of the localization.')
  # The localized title to set in the specified language.
  parser.add_argument('--title',
    help='Localized title to be set for the playlist.',
    default='Localized Title')
  # The localized description to set in the specified language.
  parser.add_argument('--description',
    help='Localized description to be set for the playlist.',
    default='Localized Description')

  args = parser.parse_args()

  youtube = get_authenticated_service()

  try:
    if args.action == 'set':
      set_playlist_localization(youtube, args)
    elif args.action == 'get':
      get_playlist_localization(youtube, args)
    elif args.action == 'list':
      list_playlist_localizations(youtube, args)
  except HttpError, e:
    print 'An HTTP error %d occurred:\n%s' % (e.resp.status, e.content)

Errors

The following table identifies error messages that the API could return in response to a call to this method. Please see the error message documentation for more detail.

Error type Error detail Description
badRequest (400) defaultLanguageNotSetError The defaultLanguage must be set to update localizations.
badRequest (400) localizationValidationError One of the values in the localizations object failed validation. Use the playlists.list method to retrieve valid values and make sure to update them following the guidelines in the playlists resource documentation.
forbidden (403) playlistForbidden This operation is forbidden or the request is not properly authorized.
invalidValue (400) invalidPlaylistSnippet The request provides an invalid playlist snippet.
notFound (404) playlistNotFound The playlist identified with the request's id parameter cannot be found.
required (400) playlistTitleRequired The request must specify a playlist title.

Send feedback about...

YouTube Data API
YouTube Data API