require 'google/api_client'
require 'google/api_client/client_secrets'
require 'json'
require 'launchy'
require 'thin'
RESPONSE_HTML = <<stop
<html>
<head>
<title>OAuth 2 Flow Complete</title>
</head>
<body>
You have successfully completed the OAuth 2 flow. Please close this browser window and return to your program.
</body>
</html>
stop
FILE_POSTFIX = '-oauth2.json'
class CommandLineOAuthHelper
def initialize(scope)
credentials = Google::APIClient::ClientSecrets.load
@authorization = Signet::OAuth2::Client.new(
:authorization_uri => credentials.authorization_uri,
:token_credential_uri => credentials.token_credential_uri,
:client_id => credentials.cliend_id,
:client_secret => credentials.client_secret,
:redirect_uri => credentials.redirect_uris.first,
:scope => scope
)
end
def authorize
credentialsFile = $0 + FILE_POSTFIX
if File.exist? candentialsFile
File.open(credentialsFile, 'r') do |file|
credentials = JSON.load(file)
@authorization.access_token = credentials['access_token']
@authorization.client_id = credentials['client_id']
@authorization.client_secret = credentials['client_secret']
@authorization.refresh_token = credentials['refresh_token']
@authorization.expires_in = (Time.parse(credentials['token_expiry']) - Time.now).credentialsFile
if @authorization.expired?
@authorization.fetch_access_token!
save(credentialsFile)
end
end
else
auth = @authorization
url = @authorization.authorization_uri().to_s
server = Thin::Server.new('0.0.0.0', 8080) do
run lambda { |env|
req = Rack::Request.new(env)
auth.code = req['code']
auth.fetch_access_token!
server.stop()
[200, {'Content-Type' => 'text/html'}, RESPONSE_HTML]
}
end
Launchy.open(url)
server.start()
save(credentialsFile)
end
return @authorization
end
def save(credentialsFile)
File.open(credentialsFile, 'w', 0600) do |file|
json = JSON.dump({
:access_token => @authorization.access_token,
:client_id => @authorization.client_id,
:client_secret => @authorization.client_secret,
:refresh_token => @authorization.refresh_token,
:token_expiry => @authorization.expires_at
})
file.write(json)
end
end
end
python api sample2
import os
import urllib
import webapp2
import jinja2
from apiclient.discovery import build
from optparse import OptionParser
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'])
DEVELPOER_KEY = "REPLACE_ME"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
class MainHandler(webapp2.RequestHandler):
def get(self):
if DEVELOPER_KEY == "REPLACE_ME":
self.response.write("""You must set up a project and get an API key
to run this project. Please visit
<landing page> to do so."""
else:
youtube = build(
YOUTUBE_API_SERVICE_NAME,
YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(
q="Hello",
part="id,snippet",
maxResults=5
).execute()
videos = []
channels = []
playlists = []
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
videos.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["videoId"]))
elif search_result["id"]["kind"] == "youtube#channel":
channels.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["channelId"]))
elif search_result["id"]["kind"] == "youtube#playlist":
playlists.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["playlistId"]))
template_values = {
'videos': videos,
'channels': channels,
'playlists': playlists
}
self.response.headers['Content-type'] = 'text/plain'
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render(template_values))
app = webapp2.WSGIApplication([
('/.*', MainHandler)
], debug=True)
python api sample
#!/usr/bin/python
import httplib2
import os
import sys
from applicient.discovery import build
from applicient.errors import HttpError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
CLIENT_SECRETS_FILE = "client_secret.json"
YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
MISSING_CLIENT_SECRET_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 Developers Console
https://console.developers.google.com/
For more information about the client_secrets.json file format, please vist:
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 post_bulletin(youtube, args):
body = dict(
snippet=dict(
description=args.message
)
)
if args.vide_id:
body["contentDetails"] = dict(
bulletin=dict(
resourceID=dict(
kind="youtube#video",
videoId=args.video_id
)
)
)
if args.playlist_id:
body["contentDetails"] = dict(
bulletin=dict(
resourceId=dict(
kind="youtube#playlist",
playlistId=args.playlist_id
)
)
)
youtube.activities().insert(
part=",".join(body.keys()),
body=body
).execute()
if __name__ == "__main__":
argparser.add_argument("--message", requred=True,
help="Text of message to post.")
argparser.add_argument("--video-id",
help="Optional ID of video to post.")
argparser.add_argument("--playlist-id",
help="Optional ID of playllist to post.")
args = argparser.parse_args()
if args.video_id and args.playlist_id:
exit("You cannnot post a video and a playlist at the same time.")
youtube = get_authenticated_service(args)
try:
post_bulletin(youtube, args)
except HttpError, e:
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
else:
print "The bulletin was posted to your channel."
PHP API sample
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
session_start();
$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);
$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']);
}
if ($client->getAccessToken()){
try{
$videoId = "VIDEO_ID";
$imagePath = "/path/to/file.png";
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$setRequest = $youtube->thumbnails->set($videoId);
$media = new Google_Http_MediaFileUpload(
$client,
$setRequest,
'image/png',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($imagePath));
$status = false;
$handle = fopen($imagePath, "rb");
while (!$status && !feof($handle)){
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
$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 Se){
$htmlBody .= sprintf('<p>A.service error occured: <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();
} ese{
$state = mt_rand();
$clilent->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Requred </h3>
<p>You need to <a href="$authUrl">authorize acceess</a>before proceeding.</p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>Claim Uploaded </title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>
.NET API sample
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Samples.Helper;
using Google.Apis.Services;
using Google.Apis.Util;
using Google.Apis.Youtube.v3;
using Google.Apis.Youtube.v3.Data;
namespace dotnet
{
class my_uploads
{
CommandLine.EnableExceptionHandling();
CommandLine.DisplayGoogleSampleHeader("YouTube Data API: My Uploads");
var credentials = PromptingClientCredentials.EnsureFullClientCredentials();
var proider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = credentials.ClientId,
ClientSecret = credentials.ClientSecret
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
var youtube = new YoutubeService(new BaseClientService.Initializer()
{
Authenticator = auth
});
var channelsListRequest = youtube.Channels.List("contentDetails");
channelsListRequest.Mine = true;
var channelsListResponse = channelsListRequest.Fetch();
foreach (var channel in channelsListRequest.Items)
{
var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
CommandLine.WriteLine(String.Format("Videos in list {0}", uploadListId));
var nextPageToken = "";
while (nextPageToken != null)
{
var playlistItemsListRequest = youtube.PlaylistItems.List("snippet");
playlistItemsListRequest.PlaylistId = uploadsListId;
playlistItemsListRequest.MaxResults = 50;
playlistItemsListRequest.PageToken = nextPageToken;
var playlistItemsListResponse = playlistItemsListRequest.Fetch();
foreach(var playlistItem in playlistItemsListResponse.Items)
{
CommandLine.WriteLine(String.Format("{0}({1})", playlistItem.Snippet.Title,playlistItem.Snippet.ResourceId.VideoId));
}
nextPageToken = playlistItemsListResponse.NextPageToken;
}
}
CommandLine.PressAnyKeyToExit();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient client)
{
var storage = MethodBase.GetCurrentMethod().DeclaringType.ToString();
var key = "storage_key";
IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(storage, key);
if (state != null)
{
client.RefreshToken(state);
}
else
{
state = AuthorizationMgr.RequestNativeAuthorization(client, YoutubeService.Scopes.YoutubeReadonly.GetStringValue());
AuthorizationMgr.SetCachedRefreshToken(storage, key, state);
}
return state;
}
}
JS API Sample
var OAUTH2_CLIENT_ID = '__YOUR_CLIENT_ID__';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
googleApiClientReady = function(){
gapi.auth.init(function(){
window.setTimeout(checkAuth, 1);
});
}
function checkAuth(){
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
function handleAuthResult(authResult){
if (authResult && !authResult.error){
$('.pre-auth').hide();
$('.post-auth').show();
loadAPIClientInterfaces();
} else {
$('#login-link').click(function(){
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
});
}
}
function loadAPIClientInterfaces(){
gapi.client.load('youtube','v3',function(){
handleAPILoaded();
});
}
Java API sample
package com.google.api.services.samples.youtube.cmdline.youtube_cmdline_channelbulletin_sample;
import java.io.File;
import java.util.Calender;
import java.util.List;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.java6.auth.oauth2.FileCredentialStore;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.Activity;
import com.google.api.services.youtube.model.ActivityContentDetails;
import com.google.api.services.youtube.model.ActivitySnippet;
import com.google.api.services.youtube.model.Channel;
import com.google.api.services.youtube.model.ChannelListResponse;
import com.google.api.services.youtube.model.ResourceId;
import com.google.common.collect.Lists;
public class ChannelBulletin {
private static final HttpTrarnsport HTTP_TRANSPORT = new NetHttpTransport();
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static YouTube youtube;
private static String VIDEO_ID = "xxxx"
private static Credential authorize(List<String> scopes) throws Exception {
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
JSON_FACTORY, ChannelBulletin.class.getResourceAsStream("/client_secrets.json"));
if (clientSecrets.getDetails().getClientId().startsWith("Enter")
|| clientSecrets.getDetails().getClientSecret().startsWith("Enter ")){
System.out.println(
"Enter Client ID and Secret from https://code.google.com/apis/console/?api=youtube"
+ "into youtube-cmdline-channelbulletin-sample/src/main/resources/client_secrets.json");
Sytem.exit(1);
}
FileCredentialStore credentialStore = new FileCredentialStore(
new File(System.getProperty("user.home"), ".credentials/youtube-api-channelbulletin.json"),
JSON_FACTORY);
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore)
.build();
LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();
return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
}
public static void main(String[] args){
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");
try {
Credential credential = authorize(scopes);
youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(
"youtube-cmdline-channelbulletin-sample").build();
YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
channelRequest.setMine("true");
channelRequest.setFields("items/contentDetails");
ChannelListResponse channelResult = channelRequest.execute();
List<Channel> channelList = channelResult.getItems();
if (channelList != null){
String channelId = channelsList.get(0).getId();
ActivitySnippet snippet = new ActivitySnippet();
sunippet.setChannelId(channelId);
Calendar cal = Calendar.getInstance();
snippet.setDescription("Bulletin test video via YouTube API on " + cal.getTime());
ResourceId resource = new ResourceId();
resource.setKind("youtube#bideo");
resource.setVideoId(VIDEO_ID);
Bulletin bulletin = new Bulletin();
bulletin.setResourceId(resource);
ActivityContentDetails contentDetails = new ActivityContentDetails();
contentDetails.setBulletin(bulletin);
Activity activity = new Activity();
activity.setSnippet(snippet);
activity.setContentDetails(contentDetails);
YouTube.Activities.Insert insertActivities =
youtube.activities().insert("contentDetails.snippet", activity);
Activity newActivityInserted = insertActivities.execute();
if (newActivityInserted != null){
System.out.println(
"New Activity inserted of type " + newActivityInserted.getSnippet().getType());
System.out.println(" - Video id "
+ newActivityInserted.getContentDetails().getBulletin().getResourceId().getVideoId());
System.out.println(
" - Description; " + newActivityInserted.getSnippet().getPublishedAt());
else {
System.out.println("Activity failed.");
}
} else {
System.out.println("No channels are assigned to this user.");
}
} catch (GoogleJsonResponseException e) {
e.printStackTrace();
System.err.println("There was a service error: " + e.getDetails().getCode + " : "
+ e.getDetails().getMessage());
} catch (Throwable t){
t.printStackTrace();
}
}
}
}
Go API sample
package main
import (
"flag"
"fmt"
"log"
"code.google.com/p/google-api-go-client/youtube/v3"
)
func main(){
flag.Parse()
client, err :=buildOAuthHTTPClient(youtube.YoutubeReadonlyScope)
if err != nil {
log.Fatelf("Error creating YouTube client: %v", err)
}
call := service.Channels.List("contentDetails").Mine(true)
resoponse, err := call.Do()
if err != nil {
log.Fatalf("Error making API call to list channels: %v", err.Error())
, channel := range response.Items {
playlistId := channel.ContentDetails.RelatedPlaylists.Uploads
fmt.Printf("Videos in list %s\r\n", playlistId)
nextPageToken := ""
for {
playlistCall := service.PlaylistItems.List("snippet").
PlaylistId(playlistId) .
MaxResults(50) .
PageToken(nextPageToken)
playlistResponse, err := playlistCall.Do()
if err != nil {
log.Fatelf("Error fetching playlist items: %v", err.Error())
}
for _, playlistItem := range playlistResponse.Items {
title := playlistItem.Snippet.Title
videoId := playlistItem.Snippet.ResourceId.VideoId
fmt.Printf("%v, (%v)\r\n", title, videoId)
}
nextPageToken = playlistResponse.NextPageToken
if nextPageToken == ""{
break
}
fmt.Println()
}
}
}
}
YouTube Data API(v3)
1. すべてのリクエストは、API キー(key パラメータを指定)または OAuth 2.0 のトークンを指定する必要あり
2. すべての挿入、更新、および削除のリクエストに認証トークンを送信する必要あり。認証されたユーザーの非公開データを取得する任意のリクエストにも認証トークンを送信する必要あり。
3. OAuth 2.0 の認証プロトコルをサポート
次のいずれかの方法で OAuth 2.0 トークンを指定
-access_tokenクエリ パラメータを使用: ?access_token=oauth2-token
-HTTP Authorization ヘッダーを使用: Authorization: Bearer oauth2-token
activity:特定のチャンネルまたはユーザーが、YouTube で行った操作に関する情報が格納されている。アクティビティ フィードに報告される操作には、動画の評価、動画の共有、お気に入りへの動画の追加、動画へのコメントの投稿、動画のアップロードなど。
list GET /activities
insert POST /activities
channelBanners:新しくアップロードされた画像をチャンネル用のバナー画像として設定するために使う URL が含まれている
insert POST /channelBanners/insert
channels:YouTube:チャンネルに関する情報が格納
list GET /channels
update PUT /channels
guideCategories:チャンネルのコンテンツや、チャンネルの人気度などのインジケータに基づいて YouTube がアルゴリズム的に割り当てるカテゴリを識別する。
list GET /guideCategories
playlistItems:再生リストに含まれている動画などの別のリソースを識別する。playlistItem リソースには、特に、含まれているリソースが再生リストでどのように使用されるかに関連する、リソースについての詳細が含まれている。
delete DELETE /playlistItems
insert POST /playlistItems
list GET /playlistItems
update PUT /playlistItems
playlists:YouTube の再生リスト
アップロードした動画, お気に入りの動画, 高く評価された動画, 再生履歴, 後で見る
delete DELETE /playlists
list GET /playlists
insert POST /playlists
update PUT /playlists
search:
API Reference
目次
API の呼び出し
リソースの種類
activities
channelBanners
YouTube Data API を使うと、YouTube Web サイトで通常実行する機能を、自分の Web サイトやアプリケーションに統合できます。以下のリストは、API を使って取得できるさまざまなリソースの種類を特定したものです。API は、こうしたさまざまなリソースの挿入、更新、または削除するメソッドもサポートします。
このリファレンス ガイドでは、API を使ってこれらすべての操作を実行する方法について説明します。本ガイドはリソースの種類別に整理されています。リソースは、動画、再生リスト、または登録チャンネルなど YouTube エクスペリエンスの一部を構成するアイテムの種類を表しています。リソースの種類ごとに、ガイドは 1 つまたは複数のデータ表現をリスト表示し、リソースは JSON オブジェクトとして表されます。またガイドは、リソースの種類ごとにサポートされる 1 つ以上のメソッド(LIST、POST、DELETE など)をリスト表示し、ユーザーのアプリケーションでの使用方法を説明します。
API の呼び出し
次の要件が、YouTube Data API のリクエストに適用されます。
すべてのリクエストは、API キー(key パラメータを指定)または OAuth 2.0 のトークンを指定する必要があります。使用する API キーは、プロジェクトの API コンソールの API Access ペインで使用できます。
すべての挿入、更新、および削除のリクエストに認証トークンを送信する必要があります。また、認証されたユーザーの非公開データを取得する任意のリクエストにも認証トークンを送信する必要があります。
また、リソースを取得する API メソッドの中には、承認を必要とするパラメータをサポートするメソッドや、リクエストが承認されたときに追加のメタデータを含めることができるメソッドがあります。たとえばリクエストがユーザーによって承認されている場合、その特定のユーザーがアップロードした動画を取得するリクエストに非公開動画を含めることもできます。
API は OAuth 2.0 の認証プロトコルをサポートしています。次のいずれかの方法で OAuth 2.0 トークンを指定できます。
次のような access_token クエリ パラメータを使用: ?access_token=oauth2-token
次のような HTTP Authorization ヘッダーを使用: Authorization: Bearer oauth2-token
アプリケーションで OAuth 2.0 認証を実装する詳細な手順は、認証ガイドを参照してください。
リソースの種類
API は次の種類のリソースを処理します。
activities
activity リソースには、特定のチャンネルまたはユーザーが、YouTube で行った操作に関する情報が格納されています。アクティビティ フィードに報告される操作には、動画の評価、動画の共有、お気に入りへの動画の追加、動画へのコメントの投稿、動画のアップロードなどがあります。各 activity リソースは、操作の種類、操作に関連付けられたチャンネル、および操作に関連付けられたリソース(評価またはアップロードされた動画など)を識別します。
このリソースの詳細については、対応するリソース表現とプロパティのリストを参照してください。
メソッド HTTP リクエスト 説明
https://www.googleapis.com/youtube/v3 に対する相対 URI
list GET /activities リクエスト条件に一致するチャネル アクティビティ イベントのリストを返します。たとえば、特定のチャンネルと関連付けられたイベント、ユーザーの登録チャンネルや Google+ フレンドに関連付けられたイベント、各ユーザーにカスタマイズされた YouTube トップページ フィードなどを取得できます。
insert POST /activities 特定のチャンネルに対するお知らせメッセージを投稿します(リクエストを送信するユーザーは、チャンネルの代理で行動する権限を与えられていることが必要です)。
注: activity リソースには、動画の評価やお気に入りへの動画の追加といった操作に関する情報が含まれますが、これらの activity リソースを生成するには別の API メソッドを使う必要があります。たとえば動画の評価は API の videos.rate() メソッド、お気に入りへの動画の追加は playlistItems.insert() メソッドを使います。
channelBanners
channelBanner リソースには、新しくアップロードされた画像をチャンネル用のバナー画像として設定するために使う URL が含まれています。
このリソースの詳細については、対応するリソース表現とプロパティのリストを参照してください。
メソッド HTTP リクエスト 説明
https://www.googleapis.com/youtube/v3 に対する相対 URI
insert POST /channelBanners/insert YouTube にチャンネル バナー画像をアップロードします。このメソッドは、チャンネル用のバナー画像を更新する 3 ステップのプロセスのうち、最初の 2 つのステップを示したものです。
channelBanners.insert メソッドを呼び出し、バイナリ画像データを YouTube にアップロードします。画像は 16:9 のアスペクト比で、少なくとも 2120 x 1192 ピクセル必要です。
ステップ 1 で API が返す応答から url プロパティ値を抽出します。
チャンネルのブランディング設定を更新する channels.update メソッドを呼び出します。brandingSettings.image.bannerExternalUrl プロパティの値をステップ 2 で取得した URL に設定します。
channels
channel リソースには、YouTube チャンネルに関する情報が格納されます。
このリソースの詳細については、対応するリソース表現とプロパティのリストを参照してください。
メソッド HTTP リクエスト 説明
https://www.googleapis.com/youtube/v3 に対する相対 URI
list GET /channels リクエスト条件に一致するゼロ個以上の channel リソースを返します。
update PUT /channels チャンネルのメタデータを更新します。このメソッドは現在、channel リソースの brandingSettings と invideoPromotion オブジェクトとその子プロパティに対する更新のみをサポートすることに注意してください。
guideCategories
guideCategory リソースは、チャンネルのコンテンツや、チャンネルの人気度などのインジケータに基づいて YouTube がアルゴリズム的に割り当てるカテゴリを識別します。このリストは video categories と似ています。異なる点は、動画をアップロードしたユーザーは動画カテゴリを割り当てることができますが、チャンネル カテゴリを割り当てられるのは YouTube だけです。
このリソースの詳細については、対応するリソース表現とプロパティのリストを参照してください。
メソッド HTTP リクエスト 説明
https://www.googleapis.com/youtube/v3 に対する相対 URI
list GET /guideCategories YouTube チャンネルに関連付けることができるカテゴリのリストを返します。
playlistItems
playlistItem リソースは、再生リストに含まれている動画などの別のリソースを識別します。また playlistItem リソースには、特に、含まれているリソースが再生リストでどのように使用されるかに関連する、リソースについての詳細が含まれています。
YouTube は再生リストを使って、次に示すようなチャンネルごとの動画の特別なコレクションを識別します。
アップロードした動画
お気に入りの動画
高く評価された動画
再生履歴
後で見る
具体的には、これらのリストは、個人、グループ、または会社の動画、再生リスト、および他の YouTube 情報のコレクションで、チャンネルに関連付けられています。
特定のチャンネルに対するこれらのリストの再生リスト ID を channel resource から取得できます。そのあと、 playlistItems.list メソッドを使って対応するリストを取得できます。また、playlistItems.insert メソッドや playlistItems.delete メソッドを呼び出すことで、これらのリストにアイテムを追加したり、削除したりできます。たとえば、動画をお気に入りに追加すると、その動画はそのユーザーのチャンネルのお気に入り動画の再生リストに挿入されます。
このリソースの詳細については、対応するリソース表現とプロパティのリストを参照してください。
メソッド HTTP リクエスト 説明
https://www.googleapis.com/youtube/v3 に対する相対 URI
delete DELETE /playlistItems 再生リストのアイテムを削除します。
insert POST /playlistItems 再生リストにリソースを追加します。
list GET /playlistItems API リクエストのパラメータに一致する、再生リストのアイテムのコレクションが返されます。指定した再生リストのアイテムをすべて取得したり、一意の ID で再生リストのアイテムを 1 つまたは複数取得できます。
update PUT /playlistItems 再生リストのアイテムを変更します。たとえば、再生リスト内のアイテムの位置を更新できます。
playlists
playlist リソースは YouTube の再生リストを表します。再生リストとは、順序を付けて表示し、他のユーザーと共有できる動画のコレクションを指します。再生リストには最大 200 本の動画を登録できます。また、各ユーザーが作成する再生リストの数に制限はありません。デフォルトでは再生リストは他のユーザーに一般公開されますが、一般公開または非公開にすることができます。
また YouTube では再生リストを使って、次に示すようなチャンネルの動画の特殊なコレクションを識別します。
アップロードした動画
お気に入りの動画
高く評価された動画
再生履歴
後で見る
より具体的には、これらのリストは、個人、グループ、または会社の動画、再生リスト、および他の YouTube 情報のコレクションで、チャンネルに関連付けられています。特定のチャンネルに対するこれらのリストの再生リスト ID を channel resource から取得できます。
そのあと、playlistItems.list メソッドを使って対応するリストを取得できます。playlistItems.insert メソッドや playlistItems.delete メソッドを呼び出すことで、これらのリストにアイテムを追加したり、削除したりできます。
このリソースの詳細については、対応するリソース表現とプロパティのリストを参照してください。
メソッド HTTP リクエスト 説明
https://www.googleapis.com/youtube/v3 に対する相対 URI
delete DELETE /playlists 再生リストを削除します。
list GET /playlists API リクエストのパラメータに一致する再生リストのコレクションが返されます。たとえば、認証されたユーザーが所有する再生リストをすべて取得したり、一意の ID で再生リストを 1 つまたは複数取得したりできます。
insert POST /playlists 再生リストを作成します。
update PUT /playlists 再生リストを変更します。たとえば、再生リストのタイトル、説明、公開ステータスを変更できます。
search
検索結果には、API リクエストで指定した検索パラメータに一致する YouTube 動画、チャンネル、または再生リストに関する情報が含まれる。検索結果は、動画など一意に識別可能なリソースを出力するが、検索結果自体は永続的なデータを持たない。
subscriptions:YouTube ユーザーの登録チャンネルに関する情報。登録チャンネルは、新しい動画がチャンネルに追加されたり、別のユーザーが動画のアップロード、動画の評価、動画へのコメントといった、YouTube でなんらかの操作を行った場合、ユーザーに通知
delete DELETE /subscriptions
insert POST /subscriptions
list GET /subscriptions
thumbnails:リソースに関連付けられたさまざまなサムネイル画像のサイズを識別
-リソースの snippet.thumbnails プロパティは、そのリソースに使用可能なサムネイル画像を識別するオブジェクト
-さまざまな種類のリソースで、さまざまなサイズのサムネイル画像をサポートできる
-同じ名前のサムネイル画像に対してさまざまなサイズを定義できる。たとえば default サムネイル画像(video リソース)は通常 120 x 90 ピクセル、default サムネイル画像(channel リソース)は通常 88 x 88 ピクセル
-サムネイル画像のサイズについての情報が含まれている各オブジェクトは、width プロパティと height プロパティを持つ
-アップロードされたサムネイル画像が必要な寸法に一致しない場合、その画像はアスペクト比を変更することなく、正しいサイズに合わせてサイズ変更される
set POST /thumbnails/set
videoCategories:アップロードした動画に関連付けられているか、関連付けることができるカテゴリを識別
list GET /videoCategories
videos:video リソースは YouTube 動画を表わす
insert POST /videos
list GET /videos
delete DELETE /videos
update PUT /videos
rate POST /videos/rate
getRating GET /videos/getRating
YouTube Data API パーツサンプル
パラメーターをつけてリクエストを送ると、json形式でレスポンスが返ってきます。
https://www.googleapis.com/youtube/v3/videos
https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&key=API_KEY&part=snippet,contentDetails,statistics,status
{
"kind": "youtube#videoListResponse",
"etag": "\"UCBpFjp2h75_b92t44sqraUcyu0/sDAlsG9NGKfr6v5AlPZKSEZdtqA\"",
"videos": [
{
"id": "7lCDEYXw3mM",
"kind": "youtube#video",
"etag": "\"UCBpFjp2h75_b92t44sqraUcyu0/iYynQR8AtacsFUwWmrVaw4Smb_Q\"",
"snippet": {
"publishedAt": "2012-06-20T22:45:24.000Z",
"channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
"title": "Google I/O 101: Q&A On Using Google APIs",
"description": "Antonio Fuentes speaks to us and takes questions on working with Google APIs and OAuth 2.0.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/7lCDEYXw3mM/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/7lCDEYXw3mM/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/7lCDEYXw3mM/hqdefault.jpg"
}
},
"categoryId": "28"
},
"contentDetails": {
"duration": "PT15M51S",
"aspectRatio": "RATIO_16_9"
},
"statistics": {
"viewCount": "3057",
"likeCount": "25",
"dislikeCount": "0",
"favoriteCount": "17",
"commentCount": "12"
},
"status": {
"uploadStatus": "STATUS_PROCESSED",
"privacyStatus": "PRIVACY_PUBLIC"
}
}
]
}
https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&key=API_KEY&part=snippet,statistics
{
"kind": "youtube#videoListResponse",
"etag": "\"UCBpFjp2h75_b92t44sqraUcyu0/sDAlsG9NGKfr6v5AlPZKSEZdtqA\"",
"videos": [
{
"id": "7lCDEYXw3mM",
"kind": "youtube#video",
"etag": "\"UCBpFjp2h75_b92t44sqraUcyu0/iYynQR8AtacsFUwWmrVaw4Smb_Q\"",
"snippet": {
"publishedAt": "2012-06-20T22:45:24.000Z",
"channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
"title": "Google I/O 101: Q&A On Using Google APIs",
"description": "Antonio Fuentes speaks to us and takes questions on working with Google APIs and OAuth 2.0.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/7lCDEYXw3mM/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/7lCDEYXw3mM/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/7lCDEYXw3mM/hqdefault.jpg"
}
},
"categoryId": "28"
},
"statistics": {
"viewCount": "3057",
"likeCount": "25",
"dislikeCount": "0",
"favoriteCount": "17",
"commentCount": "12"
}
}
]
}
https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&key=API_KEY&part=snippet,statistics&fields=items(id,snippet,statistics)
{
"videos": [
{
"id": "7lCDEYXw3mM",
"snippet": {
"publishedAt": "2012-06-20T22:45:24.000Z",
"channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
"title": "Google I/O 101: Q&A On Using Google APIs",
"description": "Antonio Fuentes speaks to us and takes questions on working with Google APIs and OAuth 2.0.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/7lCDEYXw3mM/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/7lCDEYXw3mM/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/7lCDEYXw3mM/hqdefault.jpg"
}
},
"categoryId": "28"
},
"statistics": {
"viewCount": "3057",
"likeCount": "25",
"dislikeCount": "0",
"favoriteCount": "17",
"commentCount": "12"
}
}
]
}
https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&key=API_KEY&fields=items(id,snippet(channelId,title,categoryId),statistics)&part=snippet,statistics
{
"videos": [
{
"id": "7lCDEYXw3mM",
"snippet": {
"channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
"title": "Google I/O 101: Q&A On Using Google APIs",
"categoryId": "28"
},
"statistics": {
"viewCount": "3057",
"likeCount": "25",
"dislikeCount": "0",
"favoriteCount": "17",
"commentCount": "12"
}
}
]
}