ChannelSections: update

Updates a channel section. 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/channelSections

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.

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
  • snippet: 2
  • targeting: 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 channelSection resource in the request body. For that resource:

  • You must specify a value for these properties:

    • snippet.type
    • snippet.style

  • You can set values for these properties:

    • snippet.type
    • snippet.style
    • snippet.title
    • snippet.position
    • snippet.defaultLanguage
    • contentDetails.playlists[]
    • contentDetails.channels[]
    • localizations.(key)
    • localizations.(key).title
    • targeting.countries[]
    • targeting.languages[]
    • targeting.regions[]

    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 channelSection 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 channel section:
  • It calls the channelSections.update method to update the default language of a channel section's metadata and to add a localized version of this metadata in a selected language.
  • It calls the channelSections.list method with the hl parameter set to a specific language to retrieve localized metadata in that language.
  • It calls the channelSections.list method and includes localizations in the part parameter value to retrieve all of the localized metadata for that channel section.

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.ChannelSection;
import com.google.api.services.youtube.model.ChannelSectionListResponse;
import com.google.api.services.youtube.model.ChannelSectionLocalization;
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 channel section by:
 *
 * 1. Updating language of the default metadata and setting localized metadata
 *   for a channel section via "channelSections.update" method.
 * 2. Getting the localized metadata for a channel section in a selected language using the
 *   "channelSections.list" method and setting the "hl" parameter.
 * 3. Listing the localized metadata for a channel section using the "channelSections.list" method
 *   and including "localizations" in the "part" parameter.
 *
 * @author Ibrahim Ulukaya
 */
public class ChannelSectionLocalizations {

    /**
     * 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 channel section.
     *
     * @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:
                    setChannelSectionLocalization(getId("channel section"),
                            getDefaultLanguage(), getLanguage(), getMetadata("title"));
                    break;
                case GET:
                    getChannelSectionLocalization(getId("channel section"), getLanguage());
                    break;
                case LIST:
                    listChannelSectionLocalizations(getId("channel section"));
                    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 channel section's default language and sets its localized metadata.
     *
     * @param channelSectionId The id parameter specifies the channel section ID for the resource
     * that is being updated.
     * @param defaultLanguage The language of the channel section's default metadata
     * @param language The language of the localized metadata
     * @param title The localized title to be set
     * @throws IOException
     */
    private static void setChannelSectionLocalization(String channelSectionId,
        String defaultLanguage, String language, String title) 
            throws IOException {
        // Call the YouTube Data API's channelSections.list method to retrieve channel sections.
        ChannelSectionListResponse channelSectionListResponse = youtube.channelSections().
            list("snippet,localizations").setId(channelSectionId).execute();

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

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

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

        // Update the channel section resource by calling the channelSections.update() method.
        ChannelSection channelSectionResponse = youtube.channelSections()
            .update("snippet,localizations", channelSection).execute();

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

    /**
     * Returns localized metadata for a channel section 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 channelSectionId The id parameter specifies the channel section ID for the resource
     * that is being updated.
     * @param language The language of the localized metadata
     * @throws IOException
     */
    private static void getChannelSectionLocalization(String channelSectionId, String language)
        throws IOException {
        // Call the YouTube Data API's channelSections.list method to retrieve channel sections.
        ChannelSectionListResponse channelSectionListResponse = youtube.channelSections().
            list("snippet").setId(channelSectionId).set("hl", language).execute();

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

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

    /**
     * Returns a list of localized metadata for a channel section.
     *
     * @param channelSectionId The id parameter specifies the channel section ID for the resource
     * that is being updated.
     * @throws IOException
     */
    private static void listChannelSectionLocalizations(String channelSectionId) throws IOException {
        // Call the YouTube Data API's channelSections.list method to retrieve channel sections.
        ChannelSectionListResponse channelSectionListResponse = youtube.channelSections().
            list("snippet,localizations").setId(channelSectionId).execute();

        // Since the API request specified a unique channel section ID, the API
        // response should return exactly one channel section. If the response does
        // not contain a channel section, then the specified channel section ID was not found.
        List<ChannelSection> channelSectionList = channelSectionListResponse.getItems();
        if (channelSectionList.isEmpty()) {
            System.out.println("Can't find a channel section with ID: " + channelSectionId);
            return;
        }
        ChannelSection channelSection = channelSectionList.get(0);
        Map<String, ChannelSectionLocalization> localizations = channelSection.getLocalizations();

        // Print information from the API response.
        System.out.println("\n================== Channel ==================\n");
        System.out.println("  - ID: " + channelSection.getId());
        for (String language : localizations.keySet()) {
            System.out.println("  - Title(" + language + "): " +
                localizations.get(language).getTitle());
        }
        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 #1

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

This example uses the PHP client library.

<?php

/**
 * This sample sets and retrieves localized metadata for a channel section by:
 *
 * 1. Updating language of the default metadata and setting localized metadata
 *   for a channel section via "channelSections.update" method.
 * 2. Getting the localized metadata for a channel section in a selected language using the
 *   "channelSections.list" method and setting the "hl" parameter.
 * 3. Listing the localized metadata for a channel section using the "channelSections.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: channel section ID, default language, language, title</option>
      <option value="get">Get Localization- Fill in: channel section ID, language</option>
      <option value="list">List Localizations - Fill in: channel section ID, language</option>
    </select>
  </div>
  <br>
  <div>
    Channel section ID: <input type="text" id="channelSectionId" name="channelSectionId" placeholder="Enter Channel Section ID">
  </div>
  <br>
  <div>
    Default Language: <input type="text" id="defaultLanguage" name="defaultLanguage" placeholder="Enter Default Language">
  </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>
  <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'];
    $channelSectionId = $_GET['channelSectionId'];
    $language = $_GET['language'];
    $defaultLanguage = $_GET['defaultLanguage'];
    $title = $_GET['title'];
    try {
      switch ($_GET['action']) {
        case 'set':
          setChannelSectionLocalization($youtube, $channelSectionId, $defaultLanguage,
              $language, $title, $htmlBody);
          break;
        case 'get':
          getChannelSectionLocalization($youtube, $channelSectionId, $language, $htmlBody);
          break;
        case 'list':
          listChannelSectionLocalizations($youtube, $channelSectionId, $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 channel section's default language and sets its localized metadata.
 *
 * @param Google_Service_YouTube $youtube YouTube service object.
 * @param string $channelSectionId The id parameter specifies the channel section ID
 * for the resource that is being updated.
 * @param string $defaultLanguage The language of the channel section's default metadata
 * @param string $language The language of the localized metadata
 * @param string $title The localized title to be set
 * @param $htmlBody - html body.
 */
function setChannelSectionLocalization(Google_Service_YouTube $youtube, $channelSectionId,
    $defaultLanguage, $language, $title, &$htmlBody) {
  // Call the YouTube Data API's channelSections.list method to retrieve channel sections.
  $channelSections = $youtube->channelSections->listChannelSections("snippet,localizations", array(
      'id' => $channelSectionId
  ));

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

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

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

    // Call the YouTube Data API's channelSections.update method to update an
    // existing channel section.
    $channelSectionUpdateResponse = $youtube->channels->update("snippet,localizations",
        $updateChannelSection);

    $htmlBody .= "<h2>Updated channel section</h2><ul>";
    $htmlBody .= sprintf('<li>(%s) default language: %s</li>', $channelSectionId,
        $channelSectionUpdateResponse['snippet']['defaultLanguage']);
    $htmlBody .= sprintf('<li>title(%s): %s</li>', $language,
        $channelSectionUpdateResponse['localizations'][$language]['title']);
    $htmlBody .= '</ul>';
  }
}

/**
 * Returns localized metadata for a channel section 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 $channelSectionId The channelSectionId parameter instructs the API to return the
 * localized metadata for the channel section specified by the channel section id.
 * @param string language The language of the localized metadata.
 * @param $htmlBody - html body.
 */
function getChannelSectionLocalization(Google_Service_YouTube $youtube, $channelSectionId,
    $language, &$htmlBody) {
  // Call the YouTube Data API's channelSections.list method to retrieve channel sections.
  $channelSections = $youtube->channelSections->listChannelSections("snippet", array(
      'id' => $channelSectionId,
      'hl' => $language
  ));

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

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

/**
 * Returns a list of localized metadata for a channel section.
 *
 * @param Google_Service_YouTube $youtube YouTube service object.
 * @param string $channelId The channelSectionId parameter instructs the API to return the
 * localized metadata for the channel section specified by the channel section id.
 * @param $htmlBody - html body.
 */
function listChannelSectionLocalizations(Google_Service_YouTube $youtube,
    $channelSectionId, &$htmlBody) {
  // Call the YouTube Data API's channelSections.list method to retrieve channel sections.
  $channelSections = $youtube->channelSections->listChannelSections("snippet", array(
      'id' => $channelSectionId
  ));

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

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

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

PHP #2

This sample calls the API's channelSections.list method to get the list of current channel sections, shuffles them, and then calls channelSections.update to change the position of each.

More information on channel sections is available in the YouTube Help Center.

This example uses the PHP client library.

<?php

/**
 * This sample shuffles user's existing channel sections by:
 *
 * 1. Getting the active user's channel sections via "channelSections.list" method.
 * 2. Shuffling channel sections offline.
 * 3. Saving the newly shuffled channel sections list via the "channelSections.update" method.
 *
 * @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();

/*
 * 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);
$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 = '';
  try {
    // Call the YouTube Data API's channelSections.list method to retrieve your channel sections.
    $listResponse = $youtube->channelSections->listChannelSections('snippet,contentDetails', array('mine' => true));
    $channelSections = $listResponse['items'];

    // This will randomly reorder the items in the channel_sections list.
    shuffle($channelSections);

    $htmlBody .= "<h2>Sections Shuffled</h2><ul>";

    foreach ($channelSections as $channelSection) {
      // Each section in the list of shuffled sections is sequentially
      // set to position 0, i.e. the top.
      $channelSection['snippet']['position'] = 0;

      // Call the YouTube Data API's channelSections.update method to update a channel section.
      $updateResponse = $youtube->channelSections->update('snippet,contentDetails', $channelSection);

      $htmlBody .= sprintf('<li>%s "%s"</li>',
          $updateResponse['id'], $updateResponse['snippet']['title']);
    }

    $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>Sections Shuffled</title>
</head>
<body>
  <?=$htmlBody?>
</body>
</html>

Python #1

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

This example uses the Python client library.

#!/usr/bin/python

# Usage example:
# python channel_sections_localizations.py --action='<action>' --channel_section_id='<channel_section_id>' --default_language='<default_language>' --language='<language>' --title='<title>'

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 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_secrets.json"

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

# 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 APIs 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))

# Authorize the request and store authorization credentials.
def get_authenticated_service(args):
  flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_READ_WRITE_SCOPE,
    message=MISSING_CLIENT_SECRETS_MESSAGE)

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

  if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage, args)

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


# Call the API's channelSections.update method to update an existing channel section's
# default language, and localized title in a specific language.
def set_channel_section_localization(youtube, channel_section_id, default_language, language, title):
  results = youtube.channelSections().list(
    part="snippet,localizations",
    id=channel_section_id
  ).execute()

  channel_section = results["items"][0]
  # Ensure that a value is set for the resource's snippet.defaultLanguage property.
  channel_section["snippet"]["defaultLanguage"] = default_language
  if "localizations" not in channel_section:
    channel_section["localizations"] = {}
  channel_section["localizations"][language] = {
    "title": title
  }

  update_result = youtube.channelSections().update(
    part="snippet,localizations",
    body=channel_section
  ).execute()

  localization = update_result["localizations"][language]

  print ("Updated channel section '%s' default language to '%s', localized title"
         " to '%s' in language '%s'" % (channel_section_id, localization["title"], language))


# Call the API's channelSections.list method to retrieve an existing channel section localization.
# If the localized text is not available in the requested language,
# this method will return text in the default language.
def get_channel_section_localization(youtube, channel_section_id, language):
  results = youtube.channelSections().list(
    part="snippet",
    id=channel_section_id,
    hl=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 "Channel section title is '%s' in language '%s'" % (localized["title"], language)


# Call the API's channelSections.list method to list the existing channel section localizations.
def list_channel_section_localizations(youtube, channel_section_id):
  results = youtube.channelSections().list(
    part="snippet,localizations",
    id=channel_section_id
  ).execute()

  localizations = results["items"][0]["localizations"]

  for language, localization in localizations.iteritems():
    print "Channel section title is '%s' in language '%s'" % (localization["title"], language)


if __name__ == "__main__":
  # The "action" option specifies the action to be processed.
  argparser.add_argument("--action", help="Action")
  # The "channel_section_id" option specifies the ID of the selected YouTube channel section.
  argparser.add_argument("--channel_section_id",
    help="ID for channel section for which the localization will be applied.")
  # The "default_language" option specifies the language of the channel section's default metadata.
  argparser.add_argument("--default_language",
    help="Default language of the channel section to update.", default="en")
  # The "language" option specifies the language of the localization that is being processed.
  argparser.add_argument("--language", help="Language of the localization.", default="de")
  # The "title" option specifies the localized title of the channel section to be set.
  argparser.add_argument("--title", help="Localized title of the channel section to be set.",
    default="Localized Title")

  args = argparser.parse_args()

  if not args.channel_section_id:
    exit("Please specify channel section id using the --channel_section_id= parameter.")

  youtube = get_authenticated_service(args)
  try:
    if args.action == 'set':
      set_channel_section_localization(youtube, args.channel_section_id, args.default_language, args.language, args.title)
    elif args.action == 'get':
      get_channel_section_localization(youtube, args.channel_section_id, args.language)
    elif args.action == 'list':
      list_channel_section_localizations(youtube, args.channel_section_id)
    else:
      exit("Please specify a valid action using the --action= parameter.")
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
  else:
    print "Set and retrieved localized metadata for a channel section."

Python #2

This sample calls the API's channelSections.list method to get the list of current channel sections. Then it shuffles the list and calls channelSections.update to change the position of each item.

More information on channel sections is available in the YouTube Help Center.

This example uses the Python client library.

#!/usr/bin/python

import httplib2
import os
import random
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 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_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 {{ Cloud Console }}
{{ https://cloud.google.com/console }}

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_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

def get_authenticated_service(args):
  flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_SCOPE,
    message=MISSING_CLIENT_SECRETS_MESSAGE)

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

  if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage, args)

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

def get_current_channel_sections(youtube):
  channel_sections_list_response = youtube.channelSections().list(
    part="snippet,contentDetails",
    mine=True
  ).execute()

  return channel_sections_list_response["items"]

def shuffle_channel_sections(youtube, channel_sections):
  # This will randomly reorder the items in the channel_sections list.
  random.shuffle(channel_sections)

  for channel_section in channel_sections:
    # Each section in the list of shuffled sections is sequentially
    # set to position 0, i.e. the top.
    channel_section["snippet"]["position"] = 0

    youtube.channelSections().update(
      part="snippet,contentDetails",
      body=channel_section
    ).execute()

if __name__ == '__main__':
  args = argparser.parse_args()

  youtube = get_authenticated_service(args)
  try:
    channel_sections = get_current_channel_sections(youtube)
    shuffle_channel_sections(youtube, channel_sections)
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
  else:
    print "The existing channel sections have been randomly shuffled."

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 channelSection resource's snippet.defaultLanguage property must be set to successfully insert or update the localizations object for that resource.
badRequest (400) invalidLanguage One of the language keys of the localizations object failed validation. Use the channelSections.list method to retrieve valid values and update them following the guidelines in the a href="/youtube/v3/docs/channelSections#resource">channelSections resource documentation.
badRequest (400) notEditable This channel section cannot be edited.
badRequest (400) styleRequired The channelSection resource must specify a value for the snippet.style field.
badRequest (400) targetInvalidCountry One of the values in the targeting.countries list failed validation. Use the channelSections.list method to retrieve valid values and update them following the guidelines in the a href="/youtube/v3/docs/channelSections#resource">channelSections resource documentation.
badRequest (400) targetInvalidLanguage One of the values in the targeting.languages list failed validation. Use the channelSections.list method to retrieve valid values and update them following the guidelines in the a href="/youtube/v3/docs/channelSections#resource">channelSections resource documentation.
badRequest (400) targetInvalidRegion One of the values in the targeting.regions list failed validation. Use the channelSections.list method to retrieve valid values and update them following the guidelines in the a href="/youtube/v3/docs/channelSections#resource">channelSections resource documentation.
badRequest (400) typeRequired The channelSection resource must specify a value for the snippet.type field.
forbidden (403) channelSectionForbidden The request is not properly authenticated or is not supported for this channel.
invalidValue (400) channelNotActive At least one of the specified channels is not active.
invalidValue (400) channelsDuplicated The request failed because it specified duplicate channels.
invalidValue (400) channelsNeeded If the snippet.type property has a value of multipleChannels, then the contentDetails.channels[] property must be specified and must specify at least one channel.
invalidValue (400) channelsNotExpected The resource provided with the request specified a value for the contentDetails.channels[] property, but channels are not expected for this type of channel section.
invalidValue (400) contentDetailsNeeded The resource you are updating must contain a contentDetails object for this type of channel section.
invalidValue (400) idInvalid The id property specifies an invalid channel section ID.
invalidValue (400) idRequired The id property must specify a value that identifies the channel section being updated.
invalidValue (400) inValidPosition The snippet.position property contains an invalid value.
invalidValue (400) maxChannelsExceeded The request failed because it attempted to include too many channels in the channel section.
invalidValue (400) maxPlaylistExceeded The request failed because it attempted to include too many playlists in the channel section.
invalidValue (400) onePlaylistNeeded If the snippet.type property has a value of singlePlaylist, then the contentDetails.playlists[] property must specify exactly one playlist.
invalidValue (400) ownChannelInChannels You cannot include your own channel in a channel section that appears on that channel.
invalidValue (400) playlistIsPrivate One or more of the specified playlists are private and, therefore, cannot be included in the channel section.
invalidValue (400) playlistsDuplicated The request failed because it specified duplicate playlists.
invalidValue (400) playlistsNeeded If the snippet.type property has a value of singlePlaylist or multiplePlaylists, then the contentDetails.playlists[] property must be specified.
invalidValue (400) playlistsNotExpected The resource provided with the request specified a value for the contentDetails.playlists[] property, but playlists are not expected for this type of channel section.
invalidValue (400) snippetNeeded You must specify a snippet to update the channel section.
invalidValue (400) titleLengthExceeded The value of the snippet.title property is too long.
invalidValue (400) titleRequired If the snippet.type property has a value of multiplePlaylists or multipleChannels, then you must set the section's title by specifying a value for the snippet.title property.
notFound (404) channelNotFound One or more of the specified channels cannot be found.
notFound (404) channelSectionNotFound The channel section you are trying to update cannot be found.
notFound (404) playlistNotFound One or more of the specified playlists cannot be found.

Send feedback about...

YouTube Data API
YouTube Data API