ChannelSections: insert

Adds a channel section to the authenticated user's channel. A channel can create a maximum of 10 shelves without setting targeting data and can create a maximum of 100 shelves with targeting data. 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.

Request

HTTP request

POST 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.
onBehalfOfContentOwnerChannel string
This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners.

The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel ID of the channel to which a video is being added. This parameter is required when a request specifies a value for the onBehalfOfContentOwner parameter, and it can only be used in conjunction with that parameter. In addition, the request must be authorized using a CMS account that is linked to the content owner that the onBehalfOfContentOwner parameter specifies. Finally, the channel that the onBehalfOfContentOwnerChannel parameter value specifies must be linked to the content owner that the onBehalfOfContentOwner parameter specifies.

This parameter is intended for YouTube content partners that own and manage many different YouTube channels. It allows content owners to authenticate once and perform actions on behalf of the channel specified in the parameter value, without having to provide authentication credentials for each separate channel.

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[]

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.

PHP

This sample calls the API's channelSections.insert method to create channel sections. The code accepts a number of command line arguments that let you specify the section's type, display style, title, position, and content.

This sample also updates the channel's brandingSettings.channel.showBrowseView property so that the channel displays content in a browse view (rather than a feed view). A channel's sections are only visible if the channel displays content in a browse view.

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

This example uses the PHP client library.

<?php

/**
 * This sample creates a channel section by :
 *
 * 1. Getting the active user's channel branding settings via "channels.list" method.
 * 2. Updating the active user's channel to show "browse view" via "channel.update" method.
 * 3. Creating a channel section in the active user's channel via "channelSections->insert" 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($file = __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();

// Valid section types.
$SECTION_TYPES = array("allPlaylists", "completedEvents", "likedPlaylists",
  "likes", "liveEvents", "multipleChannels", "multiplePlaylists",
  "popularUploads", "recentActivity", "recentPosts", "recentUploads",
  "singlePlaylist", "upcomingEvents");

// Valid section styles.
$SECTION_STYLES = array("horizontalRow", "verticalList");

// Replace with section title of your choice.
$SECTION_TITLE = 'YOUR_SECTION_TITLE';

// The section's position on the channel page. This property uses a 0-based index.
// If you do not specify a value for this property when inserting a channel section,
// the default behavior is to display the new section last.
$SECTION_POSITION = 0;

// A list of playlist IDs that will be featured in a channel section.
$PLAYLISTS = '';

// A list of channel IDs that will be  featured in a channel section.
$CHANNELS = '';

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

    /*
     * Before channel shelves will appear on your channel's web page, browse
     * view needs to be enabled. If you know that your channel already has
     * it enabled, or if you want to add a number of sections before enabling it,
     * you can skip the call to enable_browse_view().
     */

    // Call the YouTube Data API's channels.list method to retrieve your channel.
    $listResponse = $youtube->channels->listChannels('brandingSettings', array('mine' => true));
    $channel = $listResponse['items'][0];
    $channel['brandingSettings']['channel']['showBrowseView'] = true;

    // Call the YouTube Data API's channels.update method to update your channel.
    $updateResponse = $youtube->channels->update('brandingSettings', $channel);

    // Create a channel section snippet object with type, style, title and position.
    $channelSectionSnippet = new Google_Service_YouTube_ChannelSectionSnippet();
    $channelSectionSnippet->setType($SECTION_TYPES[0]);
    $channelSectionSnippet->setStyle($SECTION_STYLES[0]);
    $channelSectionSnippet->setTitle($SECTION_TITLE);
    $channelSectionSnippet->setPosition($SECTION_POSITION);

    // Create a channel section contentDetails object with channels and playlists.
    $channelSectionContentDetails = new Google_Service_YouTube_ChannelSectionContentDetails();
    $channelSectionContentDetails->setChannels($CHANNELS);
    $channelSectionContentDetails->setPlaylists($PLAYLISTS);

    // Create a channel section with snippet and contentDetails.
    $channelSection = new Google_Service_YouTube_ChannelSection();
    $channelSection->setSnippet($channelSectionSnippet);
    $channelSection->setContentDetails($channelSectionContentDetails);

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

    $htmlBody = "<h2>Section Created</h2><ul>";
    $htmlBody .= sprintf('<li>%s "%s"</li>',
        $insertResponse['id'], $insertResponse['snippet']['title']);
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>with channels</h3><ul>";
    foreach ($insertResponse['contentDetails']['channels'] as $channel) {
      $channels .= sprintf('<li>%s</li>', $channel);
    }
    $htmlBody .= '</ul>';

    $htmlBody .= "<h3>with playlists</h3><ul>";
    foreach ($insertResponse['contentDetails']['playlists'] as $playlist) {
      $channels .= sprintf('<li>%s</li>', $playlist);
    }
    $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>Section Created</title>
    </head>
    <body>
      <?=$htmlBody?>
    </body>
    </html>

Python

This sample calls the API's channelSections.insert method to create channel sections. The code accepts a number of command line arguments that let you specify the section's type, display style, title, position, and content.

This sample also updates the channel's brandingSettings.channel.showBrowseView property so that the channel displays content in a browse view (rather than a feed view). A channel's sections are only visible if the channel displays content in a browse view.

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

SECTION_TYPES = ("allPlaylists", "completedEvents", "likedPlaylists",
  "likes", "liveEvents", "multipleChannels", "multiplePlaylists",
  "popularUploads", "recentActivity", "recentPosts", "recentUploads",
  "singlePlaylist", "upcomingEvents",)
SECTION_STYLES = ("horizontalRow", "verticalList",)

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 enable_browse_view(youtube):
  channels_list_response = youtube.channels().list(
    part="brandingSettings",
    mine=True
  ).execute()

  channel = channels_list_response["items"][0]
  channel["brandingSettings"]["channel"]["showBrowseView"] = True

  youtube.channels().update(
    part="brandingSettings",
    body=channel
  ).execute()

def add_channel_section(youtube, args):
  channels = None
  if args.channels:
    channels = re.split("\s*,\s*", args.channels)
  playlists = None
  if args.playlists:
    playlists = re.split("\s*,\s*", args.playlists)

  body = dict(
    snippet=dict(
      type=args.type,
      style=args.style,
      title=args.title,
      position=args.position
    ),
    contentDetails=dict(
      channels=channels,
      playlists=playlists
    )
  )

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

if __name__ == '__main__':
  argparser.add_argument("--type", choices=SECTION_TYPES, required=True,
    help="The type of the section to be added.")
  argparser.add_argument("--style", choices=SECTION_STYLES, required=True,
    help="The style of the section to be added.")
  argparser.add_argument("--title",
    help=("The title to display for the new section. This is only used "
          "with the multiplePlaylists or multipleChannels section types."))
  argparser.add_argument("--position", type=int,
    help=("The position of the new section. "
         "Use 0 for the top, or don't set a value for the bottom."))
  argparser.add_argument("--playlists",
    help="One or more playlist ids, comma-separated (e.g. PL...).")
  argparser.add_argument("--channels",
    help="One or more channel ids, comma-separated (e.g. UC...).")
  args = argparser.parse_args()

  youtube = get_authenticated_service(args)
  try:
    # Before channel shelves will appear on your channel's web page, browse
    # view needs to be enabled. If you know that your channel already has
    # it enabled, or if you want to add a number of sections before enabling it,
    # you can skip the call to enable_browse_view().
    enable_browse_view(youtube)

    add_channel_section(youtube, args)
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
  else:
    print "Added new channel section."

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 created.
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 inserting must contain a contentDetails object for this type of channel section.
invalidValue (400) inValidPosition The snippet.position property contains an invalid value.
invalidValue (400) maxChannelSectionExceeded The request cannot be completed because the channel already has the maximum number of channel sections.
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 create 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) playlistNotFound One or more of the specified playlists cannot be found.

Try it!

Use the API Explorer to call this method on live data and see the API request and response.