18 – YouTube Data API – Channel Sections – list function

This is article 18 of the YouTube API With PHP series.

A ChannelSection resource contains information about a set of videos that a channel has chosen to feature. For example, a section could feature a channel’s latest uploads, most popular uploads, or videos from one or more playlists. A channel’s sections are only visible if the channel displays content in a browse view (rather than a feed view).

A channel can create a maximum of 10 sections without setting targeting data and can create a maximum of 100 sections with targeting data.

What is Targeting data? When you set restrictions on a ChannelSection by region and/or language, then it becomes a targeted ChannelSection. For instance if you want a section of your Channel called “Latest Music” to be only visible to viewers in France, then you will set the target country to “fr”. So then only viewers from France will be able to view the ChannelSection.

The following functions are available:

  • list
  • insert
  • update
  • delete

 

1.list

Returns a list of ChannelSections based on the API filters. You can use this to get data for any Channel.

The Request URL is

GET https://www.googleapis.com/youtube/v3/channelSections

Parameters

  • key (string) required. Your API key
  • access_token (string) required in certain cases. This is the user Access token.
  • part (string) required. One or all of the following , comma separated:
    • “contentDetails”
    • “id”
    • “localizations”
    • “snippet”
    • “targeting”
  • Filters – any one of the following:
    • channelId (string) Any valid channel id
    • id (string) a single or comma separated channelsection ids.
    • mine (boolean) when set to true retrieves the Channelsections of the current user’s Channel. Requires authentication
  • hl (string) optional. Specify a two-letter international language in which to return the localized resources of the channel. If no valid resources are available, then the data is returned in the default language.
  • onBehalfOfContentOwner (string) optional. This is relevant only for YouTube Channel Partners. For this parameter, the API request URL should have user authentication.We will not be exploring this option.

Example Requests

Get all ChannelSections of a Channel

https://www.googleapis.com/youtube/v3/channelSections?key=xxx&part=id,contentDetails,localizations,snippet,targeting&channelId=xxxx

Get all ChannelSections of current user

https://www.googleapis.com/youtube/v3/channelSections?key=xxx&access_token=xxx&part=id,contentDetails,localizations,snippet,targeting&mine=true

 

Get details of a single ChannelSection using its id

https://www.googleapis.com/youtube/v3/channelSections?key=xxx &part=id,contentDetails,localizations,snippet,targeting&id=xxxx

 

Response

A successful request will return an array of ChannelSection resources

{
  "kind": "youtube#channelSectionListResponse",
  "etag": etag,
  "items": [
    (channelSection Resource)
  ]
}

The Response components are explained below:

  • kind (string) “youtube#channelSectionListResponse.”
  • etag (string) See ETags Explained section
  • items (array) array of Channel Resource items returned

 

The JSON structure of a ChannelSection Resource is shown below:

 {

  "kind": "youtube#channelSection",
  "etag": etag,
  "id": string,
  "snippet": {
     "type": string,
     "style": string,
     "channelId": string,
     "title": string,
     "position": unsigned integer,
     "defaultLanguage": string,
     "localized": {
     "title": string
     }
  },
  "contentDetails": {
     "playlists": [
     string
     ],
     "channels": [
     string
     ]
  },
  "localizations": {
     (key): {
     "title": string
     }
  },
  "targeting": {
     "languages": [
     string
     ],
     "regions": [
     string
     ],
     "countries": [
     string
     ]
  }
}

 

An explanation of the various fields are given below:

  • kind (string) This value is always “youtube#channelSection”
  • etag (string) See ETags Explained section
  • id (string) unique id of this ChannelSection
  • type (string) This will contain one of the following:
    • “allPlaylists”
    • “completedEvents”
    • “likedPlaylists”
    • “likes”
    • “liveEvents”
    • “multipleChannels”
    • “multiplePlaylists”
    • “popularUploads”
    • “postedPlaylists”
    • “postedVideos”
    • “recentActivity”
    • “recentPosts”
    • “recentUploads”
    • “singlePlaylist”
    • “subscriptions”
    • “upcomingEvents”
  • style (string) The format in which the channel section displays. Valid values are:
    • “horizontalRow”
    • “verticalList”
  • channelId (string) The ID that YouTube uses to uniquely identify the channel that published the channel section.
  • title (string) The section’s title. You can only set the title of a channel section that has a snippet.type value of either multiplePlaylists or multipleChannels, and, in fact, you must specify a title when inserting or updating either of those types of sections. If you specify a title for other types of channel sections, the value will be ignored. This property’s value has a maximum length of 100 characters and may contain all valid UTF-8 characters except < and >.
  • position (unsigned int) The section’s position on the channel page. This property uses a 0-based index. A value of 0 identifies the first section that appears on the channel, a value of 1 identifies the second section, and so forth. 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.
  • defaultLanguage (string) The language of the text in the channelSection resource’s snippet.title property.
  • localized (object) The snippet.localized object contains either a localized title for the channel section or the title in the default language for the channel section’s metadata. Localized text is returned if the channelSections.list request used the hl parameter to specify a language for which localized text should be returned and localized text is available in that language. Metadata for the default language is returned if an hl parameter value is not specified or a value is specified but localized metadata is not available for the specified language. The property contains a read-only value. Use the localizations object to add, update, or delete localized titles.
  • localized.title (string) The localized channel section title.
  • playlists (list) A list of one or more playlist IDs that are featured in a channel section. You must specify a list of playlist IDs if the channelSection resource’s snippet.type property is either singlePlaylist or multiplePlaylists, and this property should not be specified for other types of sections. If the type is singlePlaylist, this list must specify exactly one playlist ID.
  • channels (list) A list of one or more channel IDs that are featured in a channel section. You must specify a list of channel IDs if the channelSection resource’s snippet.type property is multipleChannels, and this property should not be specified for other types of sections. You cannot include your own channel in the list.
  • localizations (object) The localizations object encapsulates translations of the channel section’s metadata.
  • (key) (string) The language of the localized text associated with the key value. The value is the two letter code for that language.
  • (key).title (string) The localized channel section title.
  • targeting (object) The targeting object contains targeting settings for the channel section. Note that a user must meet all of the targeting settings for a channel section to be visible. The following examples help to explain the behavior:
    • If the targeting.languages[] property value is [‘en’,’es’], the channel section will be visible to users who have selected English or Spanish as their application language.
  • If the targeting.languages[] property value is [‘en’,’es’], and the targeting.regions[] property value is [‘CA’,’FR’], the channel section will be visible to users in Canada and France who also have selected English or Spanish as their application language.
  • languages (list) A list of application languages for which the channel section is visible. Use the i18nLanguages.list method to retrieve a list of application languages that YouTube support
  • regions (list) A list of content regions where the channel section is visible. Use the i18nRegions.list method to retrieve a list of content regions that YouTube supports.
  • countries (list) A list of two letter country codes where the channel section is visible.

 

Sample code to show channelSections of a channel:

<?php
    error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
    set_time_limit(60 * 3);
    
    $g_youtubeDataAPIKey = "**";
    $channelId = "UCIJ0lLcABPdYGp7pRMGccAQ";
    
   	 // make api request
   	 $url = "https://www.googleapis.com/youtube/v3/channelSections?key=" . $g_youtubeDataAPIKey .
   			 "&part=id,contentDetails,localizations,snippet,targeting&channelId=" . $channelId;


   	 $curl = curl_init();
   	 curl_setopt_array($curl, array(
   				 CURLOPT_RETURNTRANSFER => 1,
   				 CURLOPT_URL => $url,
   				 CURLOPT_USERAGENT => 'YouTube API Tester',
   				 CURLOPT_SSL_VERIFYPEER => 1,
   				 CURLOPT_SSL_VERIFYHOST=> 0,
   				 CURLOPT_CAINFO => "../../cert/cacert.pem",
   				 CURLOPT_CAPATH => "../../cert/cacert.pem",
   				 CURLOPT_FOLLOWLOCATION => TRUE
   				 ));
   	 $resp = curl_exec($curl);

   	 curl_close($curl);


   	 if ($resp) {
   		 $json = json_decode($resp);

   		 if ($json) {
   			 echo("JSON decoded<br>");

   			 $items = $json->items;

   			 foreach($items as $item) {
   				 $id = $item->id;
   				 $type = $item->snippet->type;
   				 $style = $item->snippet->style;
   				 $position = $item->snippet->position;
   				 $title = $item->snippet->title;

   				 echo("id :" . $id . ", title :" . $title . ",     type :" . $type . ", style :"
   					 . $style .     ", position :" . $position . "<br>");

   				 $playLists = $item->contentDetails->playlists;
   				 foreach($playLists as $pl) {
   					 $playlistId = $pl;
   					 echo("Playlist id" . $playlistId . " ");

   					 // get playlist name
   					 $url = "https://www.googleapis.com/youtube/v3/playlists?key=" .
   						 $g_youtubeDataAPIKey ."&part=id,contentDetails,localizations,snippet&id="
   						 . $playlistId ;

   					 $curl = curl_init();
   					 curl_setopt_array($curl, array(
   								 CURLOPT_RETURNTRANSFER => 1,
   								 CURLOPT_URL => $url,
   								 CURLOPT_USERAGENT => 'YouTube API Tester',
   								 CURLOPT_SSL_VERIFYPEER => 1,
   								 CURLOPT_SSL_VERIFYHOST=> 0,
   								 CURLOPT_CAINFO => "../../cert/cacert.pem",
   								 CURLOPT_CAPATH => "../../cert/cacert.pem",
   								 CURLOPT_FOLLOWLOCATION => TRUE
   								 ));
   					 $resp = curl_exec($curl);

   					 curl_close($curl);

   					 if ($resp) {
   						 $json2 = json_decode($resp);
   						 if ($json2) {
   							 $plItems = $json2->items;
   							 foreach($plItems as $pl) {
   								 $title = $pl->snippet->title;
   								 
   								 echo(", title :" . $title);
   							 }
   						 }
   					 }
   					 echo("<br>");
   				 } // foreach (Playlists)
   				 echo("<hr>");    
   			 }

   		 
   		 } else
   			 exit("Error. could not parse JSON." . json_last_error_msg());

    	 } // if resp
     
?>

Here is the output:

JSON decoded

id :UCIJ0lLcABPdYGp7pRMGccAQ.urH3q0Wn23U, title :,   type :singlePlaylist, style :horizontalRow, position :0

Playlist idPLMTp9RfQQN7NrIydb_MHVuzUew9gTcdav , title :BEST OF THE YEAR COMPILATIONS

id :UCIJ0lLcABPdYGp7pRMGccAQ.HvnTts3k8Fg, title :,   type :singlePlaylist, style :horizontalRow, position :1

Playlist idPLMTp9RfQQN7MU02i0MF1xLutY1bJRGGK8 , title :BEST OF THE MONTH & WEEK COMPILATIONS

id :UCIJ0lLcABPdYGp7pRMGccAQ.Zx4DA4xg9IM, title :,   type :singlePlaylist, style :horizontalRow, position :2

Playlist idPLMTp9RfQQN7OhFNnMN_VP60wRenSeBaTn , title :THEMED COMPILATIONS

id :UCIJ0lLcABPdYGp7pRMGccAQ.jpQSKxsnbc0, title :,   type :singlePlaylist, style :horizontalRow, position :3

Playlist idPLMTp9RfQQN7MxdKsRVgsAcsPE8I8BbvfM , title :PAA Originals

id :UCIJ0lLcABPdYGp7pRMGccAQ.-wsNFmLGN6o, title :,   type :singlePlaylist, style :horizontalRow, position :4

Playlist idPLMTp9RfQQN7Mdy7qQEMj6S6ZidYqdOgB7 , title :PEOPLE ARE AWESOME: TOP FIVE

id :UCIJ0lLcABPdYGp7pRMGccAQ.aqsRo9JYx5M, title :,   type :singlePlaylist, style :horizontalRow, position :5

Playlist idPLMTp9RfQQN7MromCERzxTX_tRl9vJSFK3 , title :More Awesome People

id :UCIJ0lLcABPdYGp7pRMGccAQ.0Qj_byWfaX0, title :,   type :singlePlaylist, style :horizontalRow, position :6

Playlist idPLOWSbqDrrI5QcSwCMBAwC1UGlB_pS1sPu , title :Favorite Fails

id :UCIJ0lLcABPdYGp7pRMGccAQ.j_S84EfePTc, title :,   type :singlePlaylist, style :horizontalRow, position :7

Playlist idPLz9JxPpKRG-TuS6igiPpSNby-TcvTQicy , title :See What JukinVideo Is All About

id :UCIJ0lLcABPdYGp7pRMGccAQ.oorjVv_HDVs, title :,   type :likes, style :horizontalRow, position :8

 

One thing to note here is that, though ChannelSection resource already has a title attribute, it does not hold the actual title of the section, if the section points to a Playlist, as in the example above. More often than not, ChannelSections will refer to a Playlist. In such a case, to get the title of the ChannelSection means getting the title of the Playlist. For that we execute another API call to run the list function of the PlayList resource, with the Playlist id as the parameter.

Sample code to get the ChannelSections of the current user’s Channel:

<?php
    error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED);
    set_time_limit(60 * 3);
    session_start();
    
    $g_youtubeDataAPIKey = "**";
    $channelId = "UCo6DJdltbIub80bLiyJRv3w";
    


    $_SESSION["code_id"] = $_SERVER["PHP_SELF"];
    
    if ($_SESSION["access_token"] == null || $_SESSION["access_token"] == "") {
   	 // check for oauth response
   	 header("Location: ../../init-login.php");
   	 exit;
    }
   	 
   	 
   	 $accessToken = $_SESSION["access_token"];

   	 // make api request
   	 $url = "https://www.googleapis.com/youtube/v3/channelSections?key=" . $g_youtubeDataAPIKey .
   			  "&access_token=" . $accessToken . "&part=id,contentDetails,localizations,snippet,targeting&mine=true";


   	 $curl = curl_init();
   	 curl_setopt_array($curl, array(
   				 CURLOPT_RETURNTRANSFER => 1,
   				 CURLOPT_URL => $url,
   				 CURLOPT_USERAGENT => 'YouTube API Tester',
   				 CURLOPT_SSL_VERIFYPEER => 1,
   				 CURLOPT_SSL_VERIFYHOST=> 0,
   				 CURLOPT_CAINFO => "../../cert/cacert.pem",
   				 CURLOPT_CAPATH => "../../cert/cacert.pem",
   				 CURLOPT_FOLLOWLOCATION => TRUE
   				 ));
   	 $resp = curl_exec($curl);

   	 curl_close($curl);


   	 if ($resp) {
   		 $json = json_decode($resp);

   		 if ($json) {
   			 echo("JSON decoded<br>");

   			 $items = $json->items;

   			 foreach($items as $item) {
   				 $id = $item->id;
   				 $type = $item->snippet->type;
   				 $style = $item->snippet->style;
   				 $position = $item->snippet->position;
   				 $title = $item->snippet->title;

   				 echo("id :" . $id . ", title :" . $title . ",     type :" . $type . ", style :"
   				 . $style .     ", position :" . $position . "<br>");

   				 $playLists = $item->contentDetails->playlists;
   				 foreach($playLists as $pl) {
   					 $playlistId = $pl;
   					 echo("Playlist id" . $playlistId . " ");

   					 // get playlist name
   					 $url = "https://www.googleapis.com/youtube/v3/playlists?key=" .
   						 $g_youtubeDataAPIKey ."&part=id,contentDetails,localizations,snippet&id="
   						 . $playlistId . "&maxResults=0";

   					 $curl = curl_init();
   					 curl_setopt_array($curl, array(
   								 CURLOPT_RETURNTRANSFER => 1,
   								 CURLOPT_URL => $url,
   								 CURLOPT_USERAGENT => 'YouTube API Tester',
   								 CURLOPT_SSL_VERIFYPEER => 1,
   								 CURLOPT_SSL_VERIFYHOST=> 0,
   								 CURLOPT_CAINFO => "../../cert/cacert.pem",
   								 CURLOPT_CAPATH => "../../cert/cacert.pem",
   								 CURLOPT_FOLLOWLOCATION => TRUE
   								 ));
   					 $resp = curl_exec($curl);

   					 curl_close($curl);

   					 if ($resp) {
   						 $json2 = json_decode($resp);
   						 if ($json2) {
   							 $plItems = $json2->items;
   							 foreach($plItems as $pl) {
   								 $title = $pl->snippet->title;
   								 
   								 echo(", title :" . $title);
   							 }
   						 }
   					 }
   					 echo("<br>");
   				 } // foreach (Playlists)
   				 echo("<hr>");
   				 
   			 }

   		 
   		 } else
   			 exit("Error. could not parse JSON." . json_last_error_msg());

   	 
   	 } // if resp

   	 
    
?>

Here is the output:

JSON decoded

id :UCnXmfpAZ1rLsg0Goh0bBHUA.jNQXAC9IVRw, title :,   type :recentUploads, style :horizontalRow, position :0

id :UCnXmfpAZ1rLsg0Goh0bBHUA.LeAltgu_pbM, title :,   type :singlePlaylist, style :horizontalRow, position :1

Playlist idPLLAs2gIR3bXMW8y-iPyIU04V92aYRHJ68 , title :symphonies

id :UCnXmfpAZ1rLsg0Goh0bBHUA.nGzAI5pLbMY, title :,   type :singlePlaylist, style :horizontalRow, position :2

Playlist idPLLAs2gIR3bXPIL1pIO5r0kv2kxaGBoS5C , title :Classical Piano

id :UCnXmfpAZ1rLsg0Goh0bBHUA.__WLXNpu6u8, title :,   type :recentPosts, style :horizontalRow, position :3

Be the first to comment

Leave a Reply

Your email address will not be published.


*