カスタムの動画サムネイルを YouTube にアップロードして、動画に設定します。 例を見る。
このメソッドはメディア アップロードをサポートしています。アップロードされるファイルには、以下の制約が適用されます。
- 最大ファイル サイズ: 2 MB
- 利用可能なメディアの MIME タイプ:
image/jpeg
、image/png
、application/octet-stream
リクエスト
HTTP リクエスト
POST https://www.googleapis.com/youtube/v3/thumbnails/set
承認
このリクエストは、最低でも以下のスコープの 1 つによって承認される必要があります(認証と承認の詳細については、こちらをご覧ください)。
スコープ |
---|
https://www.googleapis.com/auth/youtubepartner |
https://www.googleapis.com/auth/youtube.upload |
https://www.googleapis.com/auth/youtube |
パラメータ
下記の表は、このクエリでサポートされているパラメータの一覧です。このリストのパラメータはすべてクエリ パラメータです。
パラメータ | ||
---|---|---|
必須パラメータ | ||
videoId |
string videoId パラメータには、カスタム動画サムネイルを設定する YouTube 動画 ID を指定します。 |
|
省略可能なパラメータ | ||
onBehalfOfContentOwner |
string このパラメータは、適切に承認されたリクエストでのみ使用できます。注: このパラメータは、YouTube コンテンツ パートナー専用です。 onBehalfOfContentOwner パラメータは、リクエストの承認用認証情報が、パラメータ値で指定されたコンテンツ所有者の代理人である YouTube CMS ユーザーのものであることを示します。このパラメータは、さまざまな YouTube チャンネルを所有、管理している YouTube コンテンツ パートナーを対象にしています。このパラメータを使用すると、コンテンツ所有者は一度認証されれば、すべての動画やチャンネル データにアクセスできるようになります。チャンネルごとに認証情報を指定する必要はありません。ユーザー認証に使用する CMS アカウントは、指定された YouTube コンテンツ所有者にリンクされていなければなりません。 |
リクエストの本文
このメソッドを呼び出す場合は、リクエストの本文を指定しないでください。
レスポンス
成功すると、このメソッドは次の構造を持つレスポンスの本文を返します。
{ "kind": "youtube#thumbnailSetResponse", "etag": etag, "items": [ thumbnails リソース ] }
プロパティ
次の表は、このリソースで使用されているプロパティの定義を示したものです。
プロパティ | |
---|---|
kind |
string API リソースのタイプ。値は youtube#thumbnailSetResponse です。 |
etag |
etag このリソースの Etag。 |
items[] |
list サムネイルのリスト。 |
例
注: 以下のコード サンプルは、サポートされているプログラミング言語すべてについて表したものではありません。サポートされている言語の一覧については、クライアント ライブラリのドキュメントを参照してください。
PHP
この例では、PHP クライアント ライブラリを使用しています。
<?php /** * This sample uploads and sets a custom thumbnail for a video. * * 1. It uploads an image using the "Google_MediaFileUpload" class. * 2. It sets the uploaded image as a custom thumbnail to the video by * calling the API's "youtube.thumbnails.set" 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 this value with the video ID of the video being updated. $videoId = "VIDEO_ID"; // REPLACE this value with the path to the image file you are uploading. $imagePath = "/path/to/file.png"; // 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); // Create a request for the API's thumbnails.set method to upload the image and associate // it with the appropriate video. $setRequest = $youtube->thumbnails->set($videoId); // Create a MediaFileUpload object for resumable uploads. $media = new Google_Http_MediaFileUpload( $client, $setRequest, 'image/png', 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['items'][0]['default']['url']; $htmlBody .= "<h3>Thumbnail Uploaded</h3><ul>"; $htmlBody .= sprintf('<li>%s (%s)</li>', $videoId, $thumbnailUrl); $htmlBody .= sprintf('<img src="%s">', $thumbnailUrl); $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>Claim Uploaded</title> </head> <body> <?=$htmlBody?> </body> </html>
Python
この例では、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 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 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)) 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 thumbnails.set method to upload the thumbnail image and # associate it with the appropriate video. def upload_thumbnail(youtube, video_id, file): youtube.thumbnails().set( videoId=video_id, media_body=file ).execute() if __name__ == "__main__": # The "videoid" option specifies the YouTube video ID that uniquely # identifies the video for which the thumbnail image is being updated. argparser.add_argument("--video-id", required=True, help="ID of video whose thumbnail you're updating.") # The "file" option specifies the path to the thumbnail image file. argparser.add_argument("--file", required=True, help="Path to thumbnail 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_thumbnail(youtube, args.video_id, args.file) except HttpError, e: print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content) else: print "The custom thumbnail was successfully set."
エラー
次の表は、このメソッドを呼び出したときに API からレスポンスとして返される可能性のあるエラー メッセージの一覧です。詳細については、エラー メッセージのドキュメントを参照してください。
エラー タイプ | エラーの詳細 | 説明 |
---|---|---|
badRequest |
mediaBodyRequired |
リクエストに画像コンテンツが含まれていません。 |
forbidden |
forbidden |
指定された動画には、サムネイルを設定できません。リクエストが適切に認証されない可能性があります。 |
forbidden |
forbidden |
この認証済みユーザーには、カスタムの動画のサムネイルをアップロードし、設定する権限がありません。 |
notFound |
videoNotFound |
サムネイル画像の挿入先動画が見つかりません。リクエストの videoId パラメータの値が正しいことを確認してください。 |