Returns a collection of zero or more channel
resources that match the request criteria.
Try it now.
Quota impact: A call to this method has a quota cost of 1 unit in addition to the costs of the specified resource parts.
Request
HTTP request
GET https://www.googleapis.com/youtube/v3/channels
Authorization
A request that retrieves the auditDetails
part for a channel
resource must provide an authorization token that contains the https://www.googleapis.com/auth/youtubepartner-channel-audit
scope. In addition, any token that uses that scope must be revoked when the MCN decides to accept or reject the channel or within two weeks of the date that the token was issued.
Parameters
The table below lists the parameters that this query supports. All of the parameters listed are query parameters.
Parameters | ||
---|---|---|
Required parameters | ||
part |
string The part parameter specifies a comma-separated list of one or more channel resource properties that the API response will include.If the parameter identifies a property that contains child properties, the child properties will be included in the response. For example, in a channel resource, the contentDetails property contains other properties, such as the uploads properties. As such, if you set part=contentDetails , the API response will also contain all of those nested properties.The list below contains the part names that you can include in the parameter value and the quota cost for each part:
|
|
Filters (specify exactly one of the following parameters) | ||
categoryId |
string The categoryId parameter specifies a YouTube guide category, thereby requesting YouTube channels associated with that category. |
|
forUsername |
string The forUsername parameter specifies a YouTube username, thereby requesting the channel associated with that username. |
|
id |
string The id parameter specifies a comma-separated list of the YouTube channel ID(s) for the resource(s) that are being retrieved. In a channel resource, the id property specifies the channel's YouTube channel ID. |
|
managedByMe |
boolean This parameter can only be used in a properly authorized request. Note: This parameter is intended exclusively for YouTube content partners. Set this parameter's value to true to instruct the API to only return channels managed by the content owner that the onBehalfOfContentOwner parameter specifies. The user must be authenticated as a CMS account linked to the specified content owner and onBehalfOfContentOwner must be provided. |
|
mine |
boolean This parameter can only be used in a properly authorized request. Set this parameter's value to true to instruct the API to only return channels owned by the authenticated user. |
|
mySubscribers |
boolean This parameter has been deprecated. This parameter can only be used in a properly authorized request. Use the subscriptions.list method and its mySubscribers parameter to retrieve a list of subscribers to the authenticated user's channel. |
|
Optional parameters | ||
hl |
string The hl parameter instructs the API to retrieve localized resource metadata for a specific application language that the YouTube website supports. The parameter value must be a language code included in the list returned by the i18nLanguages.list method.If localized resource details are available in that language, the resource's snippet.localized object will contain the localized values. However, if localized details are not available, the snippet.localized object will contain resource details in the resource's default language. |
|
maxResults |
unsigned integer The maxResults parameter specifies the maximum number of items that should be returned in the result set. Acceptable values are 0 to 50 , inclusive. The default value is 5 . |
|
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. |
|
pageToken |
string The pageToken parameter identifies a specific page in the result set that should be returned. In an API response, the nextPageToken and prevPageToken properties identify other pages that could be retrieved. |
Request body
Do not provide a request body when calling this method.
Response
If successful, this method returns a response body with the following structure:
{ "kind": "youtube#channelListResponse", "etag": etag, "nextPageToken": string, "prevPageToken": string, "pageInfo": { "totalResults": integer, "resultsPerPage": integer }, "items": [ channel Resource ] }
Properties
The following table defines the properties that appear in this resource:
Properties | |
---|---|
kind |
string Identifies the API resource's type. The value will be youtube#channelListResponse . |
etag |
etag The Etag of this resource. |
nextPageToken |
string The token that can be used as the value of the pageToken parameter to retrieve the next page in the result set. |
prevPageToken |
string The token that can be used as the value of the pageToken parameter to retrieve the previous page in the result set. |
pageInfo |
object The pageInfo object encapsulates paging information for the result set. |
pageInfo.totalResults |
integer The total number of results in the result set. |
pageInfo.resultsPerPage |
integer The number of results included in the API response. |
items[] |
list A list of channels that match the request criteria. |
Examples
Note: The following code samples may not represent all supported programming languages. See the client libraries documentation for a list of supported languages.
Apps Script
This function retrieves the current script user's uploaded videos. To execute, it requires the OAuth read/write scope for YouTube as well as user authorization. In Apps Script's runtime environment, the first time a user runs a script, Apps Script will prompt the user for permission to access the services called by the script. After permissions are granted, they are cached for some periodF of time. The user running the script will be prompted for permission again once the permissions required change, or when they are invalidated by the ScriptApp.invalidateAuth() function.This script takes the following steps to retrieve the active user's uploaded videos: 1. Fetches the user's channels 2. Fetches the user's 'uploads' playlist 3. Iterates through this playlist and logs the video IDs and titles 4. Fetches a next page token (if any). If there is one, fetches the next page. GOTO Step 3
/** * This function retrieves the current script user's uploaded videos. To execute, * it requires the OAuth read/write scope for YouTube as well as user authorization. * In Apps Script's runtime environment, the first time a user runs a script, Apps * Script will prompt the user for permission to access the services called by the * script. After permissions are granted, they are cached for some periodF of time. * The user running the script will be prompted for permission again once the * permissions required change, or when they are invalidated by the * ScriptApp.invalidateAuth() function. * * This script takes the following steps to retrieve the active user's uploaded videos: * 1. Fetches the user's channels * 2. Fetches the user's 'uploads' playlist * 3. Iterates through this playlist and logs the video IDs and titles * 4. Fetches a next page token (if any). If there is one, fetches the next page. GOTO Step 3 */ function retrieveMyUploads() { var results = YouTube.Channels.list('contentDetails', {mine: true}); for(var i in results.items) { var item = results.items[i]; // Get the playlist ID, which is nested in contentDetails, as described in the // Channel resource: https://developers.google.com/youtube/v3/docs/channels var playlistId = item.contentDetails.relatedPlaylists.uploads; var nextPageToken = ''; // This loop retrieves a set of playlist items and checks the nextPageToken in the // response to determine whether the list contains additional items. It repeats that process // until it has retrieved all of the items in the list. while (nextPageToken != null) { var playlistResponse = YouTube.PlaylistItems.list('snippet', { playlistId: playlistId, maxResults: 25, pageToken: nextPageToken }); for (var j = 0; j < playlistResponse.items.length; j++) { var playlistItem = playlistResponse.items[j]; Logger.log('[%s] Title: %s', playlistItem.snippet.resourceId.videoId, playlistItem.snippet.title); } nextPageToken = playlistResponse.nextPageToken; } } }
Java
The following code sample demonstrates how to use the following API methods to set and retrieve localized metadata for a channel:
- It calls the
channels.update
method to update the default language of a channel's metadata and to add a localized version of this metadata in a selected language. Note that to set the default language for a channel resource, you actually need to update thebrandingSettings.channel.defaultLanguage
property. - It calls the
channels.list
method with thehl
parameter set to a specific language to retrieve localized metadata in that language. - It calls the
channels.list
method and includeslocalizations
in thepart
parameter value to retrieve all of the localized metadata for that channel.
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.Channel; import com.google.api.services.youtube.model.ChannelListResponse; import com.google.api.services.youtube.model.ChannelLocalization; 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 by: * * 1. Updating language of the default metadata and setting localized metadata * for a channel via "channels.update" method. * 2. Getting the localized metadata for a channel in a selected language using the * "channels.list" method and setting the "hl" parameter. * 3. Listing the localized metadata for a channel using "channels.list" method and * including "localizations" in the "part" parameter. * * @author Ibrahim Ulukaya */ public class ChannelLocalizations { /** * 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. * * @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: setChannelLocalization(getId("channel"), getDefaultLanguage(), getLanguage(), getMetadata("description")); break; case GET: getChannelLocalization(getId("channel"), getLanguage()); break; case LIST: listChannelLocalizations(getId("channel")); 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's default language and sets its localized metadata. * * @param channelId The id parameter specifies the channel ID for the resource * that is being updated. * @param defaultLanguage The language of the channel's default metadata * @param language The language of the localized metadata * @param description The localized description to be set * @throws IOException */ private static void setChannelLocalization(String channelId, String defaultLanguage, String language, String description) throws IOException { // Call the YouTube Data API's channels.list method to retrieve channels. ChannelListResponse channelListResponse = youtube.channels(). list("brandingSettings,localizations").setId(channelId).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<Channel> channelList = channelListResponse.getItems(); if (channelList.isEmpty()) { System.out.println("Can't find a channel with ID: " + channelId); return; } Channel channel = channelList.get(0); // Modify channel's default language and localizations properties. // Ensure that a value is set for the resource's snippet.defaultLanguage property. // To set the snippet.defaultLanguage property for a channel resource, // you actually need to update the brandingSettings.channel.defaultLanguage property. channel.getBrandingSettings().getChannel().setDefaultLanguage(defaultLanguage); // Preserve any localizations already associated with the channel. If the // channel does not have any localizations, create a new array. Append the // provided localization to the list of localizations associated with the channel. Map<String, ChannelLocalization> localizations = channel.getLocalizations(); if (localizations == null) { localizations = new ArrayMap<String, ChannelLocalization>(); channel.setLocalizations(localizations); } ChannelLocalization channelLocalization = new ChannelLocalization(); channelLocalization.setDescription(description); localizations.put(language, channelLocalization); // Update the channel resource by calling the channels.update() method. Channel channelResponse = youtube.channels() .update("brandingSettings,localizations", channel).execute(); // Print information from the API response. System.out.println("\n================== Updated Channel ==================\n"); System.out.println(" - ID: " + channelResponse.getId()); System.out.println(" - Default Language: " + channelResponse.getSnippet().getDefaultLanguage()); System.out.println(" - Description(" + language + "): " + channelResponse.getLocalizations().get(language).getDescription()); System.out.println("\n-------------------------------------------------------------\n"); } /** * Returns localized metadata for a channel 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 channelId The id parameter specifies the channel ID for the resource * that is being updated. * @param language The language of the localized metadata * @throws IOException */ private static void getChannelLocalization(String channelId, String language) throws IOException { // Call the YouTube Data API's channels.list method to retrieve channels. ChannelListResponse channelListResponse = youtube.channels(). list("snippet").setId(channelId).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<Channel> channelList = channelListResponse.getItems(); if (channelList.isEmpty()) { System.out.println("Can't find a channel with ID: " + channelId); return; } Channel channel = channelList.get(0); // Print information from the API response. System.out.println("\n================== Channel ==================\n"); System.out.println(" - ID: " + channel.getId()); System.out.println(" - Description(" + language + "): " + channel.getLocalizations().get(language).getDescription()); System.out.println("\n-------------------------------------------------------------\n"); } /** * Returns a list of localized metadata for a channel. * * @param channelId The id parameter specifies the channel ID for the resource * that is being updated. * @throws IOException */ private static void listChannelLocalizations(String channelId) throws IOException { // Call the YouTube Data API's channels.list method to retrieve channels. ChannelListResponse channelListResponse = youtube.channels(). list("snippet,localizations").setId(channelId).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<Channel> channelList = channelListResponse.getItems(); if (channelList.isEmpty()) { System.out.println("Can't find a channel with ID: " + channelId); return; } Channel channel = channelList.get(0); Map<String, ChannelLocalization> localizations = channel.getLocalizations(); // Print information from the API response. System.out.println("\n================== Channel ==================\n"); System.out.println(" - ID: " + channel.getId()); for (String language : localizations.keySet()) { 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
The following code sample displays a web form that uses the API to set and retrieve localized metadata for a channel:
- It calls the
channels.update
method to update the default language of a channel's metadata and to add a localized version of this metadata in a selected language. Note that to set the default language for a channel resource, you actually need to update thebrandingSettings.channel.defaultLanguage
property. - It calls the
channels.list
method with thehl
parameter set to a specific language to retrieve localized metadata in that language. - It calls the
channels.list
method and includeslocalizations
in thepart
parameter value to retrieve all of the localized metadata for that channel.
This example uses the PHP client library.
<?php /** * This sample sets and retrieves localized metadata for a channel by: * * 1. Updating language of the default metadata and setting localized metadata * for a channel via "channels.update" method. * 2. Getting the localized metadata for a channel in a selected language using the * "channels.list" method and setting the "hl" parameter. * 3. Listing the localized metadata for a channel using "channels.list" method and * including "localizations" in the "part" parameter. * * @author Ibrahim Ulukaya */ $htmlBody = <<<END <form method="GET"> <div> Action: <select id="action" name="action"> <option value="set">Set Localization - Fill in: channel ID, default language, language, description</option> <option value="get">Get Localization- Fill in: channel ID, language</option> <option value="list">List Localizations - Fill in: channel ID, language</option> </select> </div> <br> <div> Channel ID: <input type="text" id="channelId" name="channelId" placeholder="Enter Channel 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> Description: <input type="text" id="description" name="description" placeholder="Enter Description"> </div> <br> <input type="submit" value="GO!"> </form> END; // Call set_include_path() as needed to point to your client library. require_once 'Google/Client.php'; require_once 'Google/Service/YouTube.php'; session_start(); /* * You can acquire an OAuth 2.0 client ID and client secret from the * Google Developers Console <https://console.developers.google.com/> * For more information about using OAuth 2.0 to access Google APIs, please see: * <https://developers.google.com/youtube/v3/guides/authentication> * Please ensure that you have enabled the YouTube Data API for your project. */ $OAUTH2_CLIENT_ID = 'REPLACE_ME'; $OAUTH2_CLIENT_SECRET = 'REPLACE_ME'; $action = $_GET['action']; $resource = $_GET['resource']; $channelId = $_GET['channelId']; $language = $_GET['language']; $defaultLanguage = $_GET['defaultLanguage']; $description = $_GET['description']; $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); if (isset($_GET['code'])) { if (strval($_SESSION['state']) !== strval($_GET['state'])) { die('The session state did not match.'); } $client->authenticate($_GET['code']); $_SESSION['token'] = $client->getAccessToken(); header('Location: ' . $redirect); } if (isset($_SESSION['token'])) { $client->setAccessToken($_SESSION['token']); } // Check to ensure that the access token was successfully acquired. if ($client->getAccessToken()) { // This code executes if the user enters an action in the form // and submits the form. Otherwise, the page displays the form above. if ($_GET['action']) { try { switch ($action) { case 'set': setChannelLocalization($youtube, $channelId, $defaultLanguage, $language, $description, $htmlBody); break; case 'get': getChannelLocalization($youtube, $channelId, $language, $htmlBody); break; case 'list': listChannelLocalizations($youtube, $channelId, $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['token'] = $client->getAccessToken(); } 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's default language and sets its localized metadata. * * @param Google_Service_YouTube $youtube YouTube service object. * @param string $channelId The id parameter specifies the channel ID for the resource * that is being updated. * @param string $defaultLanguage The language of the channel's default metadata * @param string $language The language of the localized metadata * @param string $description The localized description to be set * @param $htmlBody - html body. */ function setChannelLocalization(Google_Service_YouTube $youtube, $channelId, $defaultLanguage, $language, $description, &$htmlBody) { // Call the YouTube Data API's channels.list method to retrieve channels. $channels = $youtube->channels->listChannels("brandingSettings,localizations", array( 'id' => $channelId )); // If $channels is empty, the specified channel was not found. if (empty($channels)) { $htmlBody .= sprintf('<h3>Can\'t find a channel with channel id: %s</h3>', $channelId); } else { // Since the request specified a channel ID, the response only // contains one channel resource. $updateChannel = $channels[0]; // Modify channel's default language and localizations properties. // Ensure that a value is set for the resource's snippet.defaultLanguage property. // To set the snippet.defaultLanguage property for a channel resource, // you actually need to update the brandingSettings.channel.defaultLanguage property. $updateChannel['brandingSettings']['channel']['defaultLanguage'] = $defaultLanguage; $localizations = $updateChannel['localizations']; if (is_null($localizations)) { $localizations = array(); } $localizations[$language] = array('description' => $description); $updateChannel['localizations'] = $localizations; // Call the YouTube Data API's channels.update method to update an existing channel. $channelUpdateResponse = $youtube->channels->update("brandingSettings,localizations", $updateChannel); $htmlBody .= "<h2>Updated channel</h2><ul>"; $htmlBody .= sprintf('<li>(%s) default language: %s</li>', $channelId, $channelUpdateResponse['brandingSettings']['channel']['defaultLanguage']); $htmlBody .= sprintf('<li>description(%s): %s</li>', $language, $channelUpdateResponse['localizations'][$language]['description']); $htmlBody .= '</ul>'; } } /** * Returns localized metadata for a channel 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 $channelId The channelId parameter instructs the API to return the * localized metadata for the channel specified by the channel id. * @param string language The language of the localized metadata. * @param $htmlBody - html body. */ function getChannelLocalization(Google_Service_YouTube $youtube, $channelId, $language, &$htmlBody) { // Call the YouTube Data API's channels.list method to retrieve channels. $channels = $youtube->channels->listChannels("snippet", array( 'id' => $channelId, 'hl' => $language )); // If $channels is empty, the specified channel was not found. if (empty($channels)) { $htmlBody .= sprintf('<h3>Can\'t find a channel with channel id: %s</h3>', $channelId); } else { // Since the request specified a channel ID, the response only // contains one channel resource. $localized = $channels[0]["snippet"]["localized"]; $htmlBody .= "<h3>Channel</h3><ul>"; $htmlBody .= sprintf('<li>description(%s): %s</li>', $language, $localized['description']); $htmlBody .= '</ul>'; } } /** * Returns a list of localized metadata for a channel. * * @param Google_Service_YouTube $youtube YouTube service object. * @param string $channelId The channelId parameter instructs the API to return the * localized metadata for the channel specified by the channel id. * @param $htmlBody - html body. */ function listChannelLocalizations(Google_Service_YouTube $youtube, $channelId, &$htmlBody) { // Call the YouTube Data API's channels.list method to retrieve channels. $channels = $youtube->channels->listChannels("snippet,localizations", array( 'id' => $channelId )); // If $channels is empty, the specified channel was not found. if (empty($channels)) { $htmlBody .= sprintf('<h3>Can\'t find a channel with channel id: %s</h3>', $channelId); } else { // Since the request specified a channel ID, the response only // contains one channel resource. $localizations = $channels[0]["localizations"]; $htmlBody .= "<h3>Channel</h3><ul>"; foreach ($localizations as $language => $localization) { $htmlBody .= sprintf('<li>description(%s): %s</li>', $language, $localization['description']); } $htmlBody .= '</ul>'; } } ?> <!doctype html> <html> <head> <title>Set and retrieve localized metadata for a channel</title> </head> <body> <?=$htmlBody?> </body> </html>
Python
The following code sample demonstrates how to use the following API methods to set and retrieve localized metadata for a channel:
- It calls the
channels.update
method to update the default language of a channel's metadata and to add a localized version of this metadata in a selected language. Note that to set the default language for a channel resource, you actually need to update thebrandingSettings.channel.defaultLanguage
property. - It calls the
channels.list
method with thehl
parameter set to a specific language to retrieve localized metadata in that language. - It calls the
channels.list
method and includeslocalizations
in thepart
parameter value to retrieve all of the localized metadata for that channel.
This example uses the Python client library.
#!/usr/bin/python # Usage example: # python channel_localizations.py --action='<action>' --channel_id='<channel_id>' --default_language='<default_language>' --language='<language>' --description='<description>' 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 Developers Console at # https://console.developers.google.com/. # Please ensure that you have enabled the YouTube Data API for your project. # For more information about using OAuth2 to access the YouTube Data API, see: # https://developers.google.com/youtube/v3/guides/authentication # For more information about the client_secrets.json file format, see: # https://developers.google.com/api-client-library/python/guide/aaa_client_secrets CLIENT_SECRETS_FILE = "client_secrets.json" # This 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 channels.update method to update an existing channel's default language, # and localized description in a specific language. def set_channel_localization(youtube, channel_id, default_language, language, description): results = youtube.channels().list( part="brandingSettings,localizations", id=channel_id ).execute() channel = results["items"][0] # Ensure that a value is set for the resource's snippet.defaultLanguage property. # To set the snippet.defaultLanguage property for a channel resource, # you actually need to update the brandingSettings.channel.defaultLanguage property. channel["brandingSettings"]["channel"]["defaultLanguage"] = default_language if "localizations" not in channel: channel["localizations"] = {} channel["localizations"][language] = { "description": description } update_result = youtube.channels().update( part="brandingSettings,localizations", body=channel ).execute() localization = update_result["localizations"][language] print ("Updated channel '%s' default language to '%s', localized description" " to '%s' in language '%s'" % (channel_id, localization["description"], language)) # Call the API's channels.list method to retrieve an existing channel localization. # If the localized text is not available in the requested language, # this method will return text in the default language. def get_channel_localization(youtube, channel_id, language): results = youtube.channels().list( part="snippet", id=channel_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 description is '%s' in language '%s'" % (localized["description"], language) # Call the API's channels.list method to list the existing channel localizations. def list_channel_localizations(youtube, channel_id): results = youtube.channels().list( part="snippet,localizations", id=channel_id ).execute() localizations = results["items"][0]["localizations"] for language, localization in localizations.iteritems(): print "Channel description is '%s' in language '%s'" % (localization["description"], language) if __name__ == "__main__": # The "action" option specifies the action to be processed. argparser.add_argument("--action", help="Action") # The "channel_id" option specifies the ID of the selected YouTube channel. argparser.add_argument("--channel_id", help="ID for channel for which the localization will be applied.") # The "default_language" option specifies the language of the channel's default metadata. argparser.add_argument("--default_language", help="Default language of the channel 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 "description" option specifies the localized description of the chanel to be set. argparser.add_argument("--description", help="Localized description of the channel to be set.", default="Localized Description") args = argparser.parse_args() if not args.channel_id: exit("Please specify channel id using the --channel_id= parameter.") youtube = get_authenticated_service(args) try: if args.action == 'set': set_channel_localization(youtube, args.channel_id, args.default_language, args.language, args.description) elif args.action == 'get': get_channel_localization(youtube, args.channel_id, args.language) elif args.action == 'list': list_channel_localizations(youtube, args.channel_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."
Errors
The table below 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) |
invalidCriteria |
A maximum of one of the following filters may be specified:id , mySubscribers , categoryId , mine , managedByMe , forUsername . In case of content owner authentication via the onBehalfOfContentOwner parameter, only the id or managedByMe may be specified. |
forbidden (403) |
channelForbidden |
The channel specified by the id parameter does not support the request or the request is not properly authorized. |
notFound (404) |
categoryNotFound |
The category identified by the categoryId parameter cannot be found. Use the guideCategories.list method to retrieve a list of valid values. |
notFound (404) |
channelNotFound |
The channel specified in the id parameter cannot be found. |
Try it!
Use the API Explorer to call this method on live data and see the API request and response.