ChannelBanners: insert

Uploads a channel banner image to YouTube. This method represents the first two steps in a three-step process to update the banner image for a channel:

  1. Call the channelBanners.insert method to upload the binary image data to YouTube. The image must have a 16:9 aspect ratio and be at least 2048x1152 pixels. We recommend uploading a 2560px by 1440px image.
  2. Extract the url property's value from the response that the API returns for step 1.
  3. Call the channels.update method to update the channel's branding settings. Set the brandingSettings.image.bannerExternalUrl property's value to the URL obtained in step 2.

This method supports media upload. Uploaded files must conform to these constraints:

  • Maximum file size: 6MB
  • Accepted Media MIME types: image/jpeg, image/png, application/octet-stream

Quota impact: A call to this method has a quota cost of approximately 50 units.


HTTP request



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



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

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

Do not provide a request body when calling this method.


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


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


This sample calls the API's channelBanners.insert method to upload an image. With the returned URL, the sample calls channels.update method to update the channel's banner to this image.

This example uses the PHP client library.


 * This sample sets a custom banner for a user's channel by:
 * 1. Uploading a banner image with "youtube.channelBanners.insert" method via resumable upload
 * 2. Getting user's channel object with "youtube.channels.list" method and "mine" parameter
 * 3. Updating channel's banner external URL with "youtube.channels.update" method
 * @author Ibrahim Ulukaya

 * Library Requirements
 * 1. Install composer (
 * 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';

 * You can acquire an OAuth 2.0 client ID and client secret from the
 * {{ Google Cloud Console }} <{{ }}>
 * For more information about using OAuth 2.0 to access Google APIs, please see:
 * <>
 * Please ensure that you have enabled the YouTube Data API for your project.

$client = new Google_Client();
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],

// 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.');

  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
  header('Location: ' . $redirect);

if (isset($_SESSION[$tokenSessionKey])) {

// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
  $htmlBody = '';

    // REPLACE with the path to your file that you want to upload for thumbnail
    $imagePath = "/path/to/file.jpg";

    // Specify the size of each chunk of data, in bytes. Set a higher value for
    // reliable connection as fewer chunks lead to faster uploads. Set a lower
    // value for better recovery on less reliable connections.
    $chunkSizeBytes = 1 * 1024 * 1024;

    // Setting the defer flag to true tells the client to return a request which can be called
    // with ->execute(); instead of making the API call immediately.

    $chan = new Google_Service_YouTube_ChannelBannerResource();

    // Create a request for the API's channelBanners.insert method to upload the banner.
    $insertRequest = $youtube->channelBanners->insert($chan);

    // Create a MediaFileUpload object for resumable uploads.
    $media = new Google_Http_MediaFileUpload(

    // Read the media file and upload it chunk by chunk.
    $status = false;
    $handle = fopen($imagePath, "rb");
    while (!$status && !feof($handle)) {
      $chunk = fread($handle, $chunkSizeBytes);
      $status = $media->nextChunk($chunk);


    // If you want to make other calls after the file upload, set setDefer back to false

    $thumbnailUrl = $status['url'];

    // Call the API's channels.list method with mine parameter to fetch authorized user's channel.
    $listResponse = $youtube->channels->listChannels('brandingSettings', array(
        'mine' => 'true',

    $responseChannel = $listResponse[0];

     // Call the API's channels.update method to update branding settings of the channel.
     $updateResponse = $youtube->channels->update('brandingSettings', $responseChannel);

     $bannerMobileUrl = $updateResponse["brandingSettings"]["image"]["bannerMobileImageUrl"];

     $htmlBody .= "<h3>Thumbnail Uploaded</h3><ul>";
     $htmlBody .= sprintf('<li>%s</li>',
     $htmlBody .= sprintf('<img src="%s">', $bannerMobileUrl);
     $htmlBody .= '</ul>';

  } catch (Google_Service_Exception $e) {
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
  } catch (Google_Exception $e) {
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',

  $_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'REPLACE_ME') {
  $htmlBody = <<<END
  <h3>Client Credentials Required</h3>
    You need to set <code>\$OAUTH2_CLIENT_ID</code> and
    <code>\$OAUTH2_CLIENT_ID</code> before proceeding.
} else {
  // If the user hasn't authorized the app, initiate the OAuth flow
  $state = mt_rand();
  $_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>

<!doctype html>
<title>Banner Uploaded and Set</title>


This sample calls the API's channelBanners.insert method to upload an image. With the returned URL, the sample calls channels.update method to update the channel's banner to that image.

This example uses the Python client library.


# This sample sets a custom banner to user's channel by:
# 1. Uploading a banner image with "youtube.channelBanners.insert" method via resumable upload
# 2. Getting user's channel object with "youtube.channels.list" method and "mine" parameter
# 3. Updating channel's banner external URL with "youtube.channels.update" method
# @author Ibrahim Ulukaya

import httplib
import httplib2
import os
import random
import sys
import time

from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from import argparser, run_flow

# Explicitly tell the underlying HTTP transport library not to retry, since
# we are handling retry logic ourselves.
httplib2.RETRIES = 1

# Maximum number of times to retry before giving up.

# Always retry when these exceptions are raised.
RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected,
  httplib.IncompleteRead, httplib.ImproperConnectionState,
  httplib.CannotSendRequest, httplib.CannotSendHeader,
  httplib.ResponseNotReady, httplib.BadStatusLine)

# Always retry when an apiclient.errors.HttpError with one of these status
# codes is raised.
RETRIABLE_STATUS_CODES = [500, 502, 503, 504]

# CLIENT_SECRETS_FILE, name of a file containing the OAuth 2.0 information for
# this application, including client_id and client_secret. You can acquire an
# ID/secret pair from the APIs & auth tab at
# For more information about using OAuth2 to access Google APIs, please visit:
# For more information about the client_secrets.json file format, please visit:
# Please ensure that you have enabled the YouTube Data API for your project.
CLIENT_SECRETS_FILE = "client_secrets.json"

# An OAuth 2 access scope that allows for full read/write access.

# Helpful message to display if the CLIENT_SECRETS_FILE is missing.
WARNING: Please configure OAuth 2.0

To make this sample run you will need to populate the client_secrets.json file
found at:


with information from the APIs Console

For more information about the client_secrets.json file format, please visit:
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),

def get_authenticated_service(args):
  flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,

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

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


def upload_banner(youtube, image_file):
  insert_request = youtube.channelBanners().insert(
    media_body = MediaFileUpload(image_file, chunksize=-1, resumable=True)

  image_url = resumable_upload(insert_request)

def resumable_upload(insert_request):
  response = None
  error = None
  retry = 0
  while response is None:
      print "Uploading file..."
      status, response = insert_request.next_chunk()
      if 'url' in response:
        print "Banner was successfully uploaded to '%s'." % (
        exit("The upload failed with an unexpected response: %s" % response)
    except HttpError, e:
      if e.resp.status in RETRIABLE_STATUS_CODES:
        error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
      error = "A retriable error occurred: %s" % e

    if error is not None:
      print error
      retry += 1
      if retry > MAX_RETRIES:
        exit("No longer attempting to retry.")

      max_sleep = 2 ** retry
      sleep_seconds = random.random() * max_sleep
      print "Sleeping %f seconds and then retrying..." % sleep_seconds

  return response['url']

def set_banner(banner_url):
  channels_response = youtube.channels().list(

  if "brandingSettings" not in channels_response["items"][0]:
    channels_response["items"][0]["brandingSettings"]["image"]["bannerExternalUrl"] = []

  channel_brandingSettings = channels_response["items"][0]["brandingSettings"]

  channel_brandingSettings["image"]["bannerExternalUrl"] = banner_url

  channels_update_response = youtube.channels().update(
      id = channels_response["items"][0]["id"]

  banner_mobile_url = channels_update_response["brandingSettings"]["image"]["bannerMobileImageUrl"]
  print "Banner is set to '%s'." % (banner_mobile_url)

if __name__ == "__main__":
  argparser.add_argument("--file", required=True,
    help="Path to banner image file.")
  args = argparser.parse_args()

  if not os.path.exists(args.file):
    exit("Please specify a valid file using the --file= parameter.")

  youtube = get_authenticated_service(args)
    upload_banner(youtube, args.file)
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
    print "The custom banner was successfully uploaded."


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) bannerAlbumFull Your YouTube Channel Art album has too many images. Please go to, navigate to the albums page, and remove some from images from that album.
badRequest (400) mediaBodyRequired The request does not include the image content.