Channels: update

Atualiza os metadados de um canal. Este método atualmente suporta apenas atualizações dos objetos brandingSettings e invideoPromotion do recurso channel e suas propriedades filho. Faça um teste agora ou veja um exemplo.

Solicitação

Solicitação HTTP

PUT https://www.googleapis.com/youtube/v3/channels

Autorização

Esta solicitação requer autorização com pelo menos um dos seguintes escopos (saiba mais sobre autenticação e autorização).

Escopo
https://www.googleapis.com/auth/youtubepartner
https://www.googleapis.com/auth/youtube

Parâmetros

A tabela a seguir lista os parâmetros que esta consulta suporta. Todos os parâmetros listados são os parâmetros de consulta.

Parâmetros
Parâmetros obrigatórios
part string
O parâmetro part tem duas finalidades nesta operação: identifica as propriedades que serão definidas pela operação de gravação e as propriedades que serão incluídas pela resposta da API.

Atualmente, a API permite que apenas as partes id e invideoPromotion sejam incluídas no valor do parâmetro.

Este método substitui os valores existentes de todas as propriedades mutáveis contidas em todas as peças especificadas pelo valor do parâmetro.
Parâmetros opcionais
onBehalfOfContentOwner string
Este parâmetro pode ser usado apenas em uma solicitação autorizada adequadamente. O parâmetro onBehalfOfContentOwner indica que o usuário autenticado está agindo em nome do proprietário do conteúdo especificado no valor do parâmetro. Este parâmetro destina-se a parceiros de conteúdo do YouTube que possuem e gerenciam vários canais do YouTube diferentes. Ele permite que os proprietários de conteúdo autentiquem uma vez e tenham acesso a todos os dados de seu canal e de seus vídeos sem ter que fornecer credenciais de autenticação para cada canal. A conta do CMS real com a qual o usuário autentica precisa estar vinculada ao proprietário do conteúdo do YouTube especificado.

Corpo de solicitação

Forneça um recurso de canal no corpo da solicitação. Para esse recurso:

  • É necessário especificar um valor para essas propriedades:

    • id

  • Você pode definir valores para estas propriedades:

    • invideoPromotion.position.type
    • invideoPromotion.position.cornerPosition
    • brandingSettings.image.bannerExternalUrl
    • invideoPromotion.defaultTiming.type
    • invideoPromotion.defaultTiming.offsetMs
    • invideoPromotion.items[].id.type
    • invideoPromotion.items[].id.videoId
    • invideoPromotion.items[].timing.type
    • invideoPromotion.items[].timing.offsetMs

    Se você estiver enviando uma solicitação de atualização e ela não especificar um valor para uma propriedade que já tenha um, o valor existente da propriedade será excluído.

Resposta

Se for bem-sucedido, este método retorna um recurso de canal no corpo da resposta.

Exemplos

Observação: os exemplos de código a seguir não representam todas as linguagens de programação suportadas. Consulte a documentação bibliotecas clientes para uma lista das linguagens suportadas.

Java

Este exemplo usa a biblioteca cliente Java.

/*
 * Copyright (c) 2013 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.http.InputStreamContent;
import com.google.api.services.samples.youtube.cmdline.Auth;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.*;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.math.BigInteger;
import java.util.List;

/**
 * Add a featured video to a channel.
 *
 * @author Ikai Lan <ikai@google.com>
 */
public class InvideoProgramming {

    /**
     * Define a global instance of a Youtube object, which will be used
     * to make YouTube Data API requests.
     */
    private static YouTube youtube;

    /**
     * This sample video introduces WebM on YouTube Developers Live.
     */
    private static final String FEATURED_VIDEO_ID = "w4eiUiauo2w";

    /**
     * This code sample demonstrates different ways that the API can be used to
     * promote your channel content. It includes code for the following tasks:
     * <ol>
     * <li>Feature a video.</li>
     * <li>Feature a link to a social media channel.</li>
     * <li>Set a watermark for videos on your channel.</li>
     * </ol>
     *
     * @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, "invideoprogramming");

            // This object is used to make YouTube Data API requests.
            youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                    .setApplicationName("youtube-cmdline-invideoprogramming-sample")
                    .build();

            // Construct a request to retrieve the current user's channel ID.
            // In the API response, only include channel information needed for
            // this use case. The channel's uploads playlist identifies the
            // channel's most recently uploaded video.
            // See https://developers.google.com/youtube/v3/docs/channels/list
            ChannelListResponse channelListResponse = youtube.channels().list("id,contentDetails")
                    .setMine(true)
                    .setFields("items(contentDetails/relatedPlaylists/uploads,id)")
                    .execute();

            // The user's default channel is the first item in the list. If the
            // user does not have a channel, this code should throw a
            // GoogleJsonResponseException explaining the issue.
            Channel myChannel = channelListResponse.getItems().get(0);
            String channelId = myChannel.getId();

            // The promotion appears 15000ms (15 seconds) before the video ends.
            InvideoTiming invideoTiming = new InvideoTiming();
            invideoTiming.setOffsetMs(BigInteger.valueOf(15000l));
            invideoTiming.setType("offsetFromEnd");

            // This is one type of promotion and promotes a video.
            PromotedItemId promotedItemId = new PromotedItemId();
            promotedItemId.setType("video");
            promotedItemId.setVideoId(FEATURED_VIDEO_ID);

            // Set a custom message providing additional information about the
            // promoted video or your channel.
            PromotedItem promotedItem = new PromotedItem();
            promotedItem.setCustomMessage("Check out this video about WebM!");
            promotedItem.setId(promotedItemId);

            // Construct an object representing the invideo promotion data, and
            // add it to the channel.
            InvideoPromotion invideoPromotion = new InvideoPromotion();
            invideoPromotion.setDefaultTiming(invideoTiming);
            invideoPromotion.setItems(Lists.newArrayList(promotedItem));

            Channel channel = new Channel();
            channel.setId(channelId);
            channel.setInvideoPromotion(invideoPromotion);

            Channel updateChannelResponse = youtube.channels()
                    .update("invideoPromotion", channel)
                    .execute();

            // Print data from the API response.
            System.out.println("\n================== Updated Channel Information ==================\n");
            System.out.println("\t- Channel ID: " + updateChannelResponse.getId());

            InvideoPromotion promotions = updateChannelResponse.getInvideoPromotion();
            promotedItem = promotions.getItems().get(0); // We only care about the first item
            System.out.println("\t- Invideo promotion video ID: " + promotedItem
                    .getId()
                    .getVideoId());
            System.out.println("\t- Promotion message: " + promotedItem.getCustomMessage());

            // In-video programming can also be used to feature links to
            // associated websites, merchant sites, or social networking sites.
            // The code below overrides the promotional video set above by
            // featuring a link to the YouTube Developers Twitter feed.
            PromotedItemId promotedTwitterFeed = new PromotedItemId();
            promotedTwitterFeed.setType("website");
            promotedTwitterFeed.setWebsiteUrl("https://twitter.com/youtubedev");

            promotedItem = new PromotedItem();
            promotedItem.setCustomMessage("Follow us on Twitter!");
            promotedItem.setId(promotedTwitterFeed);

            invideoPromotion.setItems(Lists.newArrayList(promotedItem));
            channel.setInvideoPromotion(invideoPromotion);

            // Call the API to set the in-video promotion data.
            updateChannelResponse = youtube.channels()
                    .update("invideoPromotion", channel)
                    .execute();

            // Print data from the API response.
            System.out.println("\n================== Updated Channel Information ==================\n");
            System.out.println("\t- Channel ID: " + updateChannelResponse.getId());

            promotions = updateChannelResponse.getInvideoPromotion();
            promotedItem = promotions.getItems().get(0);
            System.out.println("\t- Invideo promotion URL: " + promotedItem
                    .getId()
                    .getWebsiteUrl());
            System.out.println("\t- Promotion message: " + promotedItem.getCustomMessage());

            // This example sets a custom watermark for the channel. The image
            // used is the watermark.jpg file in the "resources/" directory.
            InputStreamContent mediaContent = new InputStreamContent("image/jpeg",
                    InvideoProgramming.class.getResourceAsStream("/watermark.jpg"));

            // Indicate that the watermark should display during the last 15
            // seconds of the video.
            InvideoTiming watermarkTiming = new InvideoTiming();
            watermarkTiming.setType("offsetFromEnd");
            watermarkTiming.setDurationMs(BigInteger.valueOf(15000l));
            watermarkTiming.setOffsetMs(BigInteger.valueOf(15000l));

            InvideoBranding invideoBranding = new InvideoBranding();
            invideoBranding.setTiming(watermarkTiming);
            youtube.watermarks().set(channelId, invideoBranding, mediaContent).execute();

        } 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();
        }
    }

}

PHP

Este exemplo usa a biblioteca cliente PHP.

<?php

/**
 * 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 (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 API Console <https://console.cloud.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';

$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{

    // 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.
    $client->setDefer(true);

    $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(
        $client,
        $insertRequest,
        'image/jpeg',
        null,
        true,
        $chunkSizeBytes
    );
    $media->setFileSize(filesize($imagePath));


    // 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);
    }

    fclose($handle);

    // If you want to make other calls after the file upload, set setDefer back to false
    $client->setDefer(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];
    $responseChannel['brandingSettings']['image']['bannerExternalUrl']=$thumbnailUrl;

     // 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>',
         $thumbnailUrl);
     $htmlBody .= sprintf('<img src="%s">', $bannerMobileUrl);
     $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>Banner Uploaded and Set</title>
</head>
<body>
  <?=$htmlBody?>
</body>
</html>

Python #1

O exemplo de código abaixo chama o método channels.update da API para definir propriedades invideoPromotion para o canal.

Este exemplo usa a biblioteca cliente Python.

#!/usr/bin/python

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 API Console at
# https://console.cloud.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 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 API Console
https://console.cloud.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))

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

# If offsetMs is not valid, the API will throw an error
VALID_OFFSET_TYPES = ("offsetFromEnd", "offsetFromStart",)

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 add_featured_video(youtube, options):
  add_video_request = youtube.channels().update(
    part="invideoPromotion",
    # You can use the API Explorer to test API requests:
    #    https://developers.google.com/youtube/v3/docs/channels/update#try-it
    body={
      "invideoPromotion": {
        "items": [{
          "id": {
            "type": "video",
            "videoId": options.video_id
          },
          "timing": {
            "offsetMs": options.offset_ms,
            "type": options.offset_type
          }
        }],
      },
      "id": options.channel_id
  }).execute()

if __name__ == '__main__':
  argparser.add_argument("--channel-id", required=True,
    help="Channel ID of the channel to add a featured video")
  argparser.add_argument("--video-id",  required=True,
    help="Video ID to feature on your channel")
  argparser.add_argument("--offset-ms",
    help="Offset in milliseconds to show video.",
    default="10000")
  argparser.add_argument("--offset-type", choices=VALID_OFFSET_TYPES,
    help="Whether the offset is from the beginning or end of video playback.",
    default=VALID_OFFSET_TYPES[0])
  args = argparser.parse_args()

  youtube = get_authenticated_service(args)
  try:
    add_featured_video(youtube, args)
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
  else:
    print "Added featured video %s to channel %s." % (
      args.video_id, args.channel_id)

Python #2

Este exemplo usa a biblioteca cliente Python.

#!/usr/bin/python


# 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 oauth2client.tools 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.
MAX_RETRIES = 10

# 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
#   https://cloud.google.com/console
# For more information about using OAuth2 to access Google APIs, please visit:
#   https://developers.google.com/accounts/docs/OAuth2
# For more information about the client_secrets.json file format, please visit:
#   https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
# 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.
YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

# Helpful 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://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))

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()))

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)
  set_banner(image_url)

def resumable_upload(insert_request):
  response = None
  error = None
  retry = 0
  while response is None:
    try:
      print "Uploading file..."
      status, response = insert_request.next_chunk()
      if 'url' in response:
        print "Banner was successfully uploaded to '%s'." % (
          response['url'])
      else:
        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,
                                                             e.content)
      else:
        raise
    except RETRIABLE_EXCEPTIONS, e:
      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
      time.sleep(sleep_seconds)

  return response['url']

def set_banner(banner_url):
  channels_response = youtube.channels().list(
    mine=True,
    part="brandingSettings"
  ).execute()

  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(
    part='brandingSettings',
    body=dict(
      brandingSettings=channel_brandingSettings,
      id = channels_response["items"][0]["id"]
    )).execute()

  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)
  try:
    upload_banner(youtube, args.file)
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
  else:
    print "The custom banner was successfully uploaded."

Erros

A tabela abaixo identifica as mensagens de erro que a API pode retornar em resposta a uma chamada para este método. Consulte a documentação mensagem de erro para mais detalhes.

Tipo de erro Detalhe do erro Descrição
badRequest brandingValidationError Um dos valores no objeto brandingSettings não passou na validação. Use o método channels.list para recuperar as configurações existentes para o canal e atualize os valores da propriedade seguindo as orientações contidas na documentação do recurso channels.
badRequest invalidBrandingOption Uma das configurações de marca que você especificou não existe. Use o método channels.list para recuperar valores válidos e não se esqueça de atualizá-los seguindo as orientações contidas na documentação do recurso channels.
badRequest invalidCornerPosition Os metadados da solicitação especificam uma posição de canto inválido para identificar o local em que o item promovido será exibido. Verifique o valor da propriedade invideoPromotion.position.cornerPosition no recurso que a solicitação enviou.
badRequest invalidItemType Os metadados da solicitação especificam um tipo de item inválido na parte invideoPromotion. Verifique o valor da propriedade invideoPromotion.items[].type no recurso que a solicitação enviou.
badRequest invalidPositionOffset Os metadados da solicitação especificam um tipo de posição inválido para determinar como o item promovido está posicionado no player de vídeo. Verifique o valor da propriedade invideoPromotion.position.type no recurso que a solicitação enviou.
badRequest invalidTimingOffset Os metadados da solicitação especificam um ajuste de horário inválido para determinar quando o item promovido deve ser exibido no player de vídeo. Verifique o valor da propriedade invideoPromotion.timing.offsetMs no recurso que a solicitação enviou.
badRequest invalidTimingType Os metadados da solicitação especificam um método de tempo inválido para determinar quando o item promovido deve ser exibido no player de vídeo. Verifique o valor da propriedade invideoPromotion.timing.type no recurso que a solicitação enviou.
forbidden channelForbidden O canal especificado no parâmetro id não suporta a solicitação ou a solicitação não está corretamente autorizada.
notFound channelNotFound O canal especificado pelo parâmetro id não pode ser encontrado ou não possui opções de marca.
notFound unknownChannelId O canal que a solicitação da API está tentando atualizar não pode ser encontrado. Verifique o valor da propriedade id no recurso channel que a solicitação enviou para assegurar que o ID do canal esteja correto.
notFound unknownVideoId O ID do vídeo especificado como um item promovido não pode ser encontrado.
required requiredCornerPosition Os metadados da solicitação devem especificar uma posição de canto para que o YouTube possa determinar onde exibir o item promovido no player. Defina o valor da propriedade invideoPromotion.position.cornerPosition no recurso que a solicitação envia.
required requiredItemType Os metadados da solicitação devem especificar o tipo de item promovido. Defina o valor da propriedade invideoPromotion.items[].type no recurso que a solicitação envia.
required requiredPositionOffset Os metadados da solicitação devem especificar um tipo de posição para que o YouTube possa determinar como exibir o item promovido. Defina o valor da propriedade invideoPromotion.position.type no recurso que a solicitação envia.
required requiredTimingOffset Os metadados da solicitação devem especificar um ajuste de horário para que o YouTube possa determinar quando exibir o item promovido. Defina o valor da propriedade invideoPromotion.timing.offsetMs no recurso que a solicitação envia.
required requiredTimingType Os metadados da solicitação devem especificar um método de horário para que o YouTube possa determinar quando exibir o item promovido. Defina o valor da propriedade invideoPromotion.timing.type no recurso que a solicitação envia.
required requiredVideoId Os metadados da solicitação devem especificar um ID de vídeo para identificar o item promovido.

Conheça agora.

Use o Explorador de API para chamar este método em dados ativos e ver a solicitação e a resposta da API.