認証されたユーザーのチャンネル登録を追加します。 今すぐ試すまたは、例をみる。
リクエスト
HTTP リクエスト
POST https://www.googleapis.com/youtube/v3/subscriptions
承認
このリクエストは、最低でも以下のスコープの 1 つによって承認される必要があります(認証と承認の詳細については、こちらをご覧ください)。
スコープ |
---|
https://www.googleapis.com/auth/youtubepartner |
https://www.googleapis.com/auth/youtube |
パラメータ
下記の表は、このクエリでサポートされているパラメータの一覧です。このリストのパラメータはすべてクエリ パラメータです。
パラメータ | ||
---|---|---|
必須パラメータ | ||
part |
string この操作では、 part パラメータは 2 つの目的で使用されます。書き込み操作で設定されるプロパティの特定と API レスポンスに含まれるプロパティの特定です。このパラメータ値に指定できる part 名は snippet と contentDetails です。 |
リクエストの本文
リクエストの本文には登録チャンネル リソースを指定します。 このリソースでは、次の点に注意してください。
-
以下のプロパティの値を指定する必要があります。
snippet.resourceId
-
以下のプロパティの値を設定することができます。
snippet.resourceId
レスポンス
成功すると、このメソッドはレスポンスの本文で登録チャンネル リソースを返します。
例
注: 以下のコード サンプルは、サポートされているプログラミング言語すべてについて表したものではありません。サポートされている言語の一覧については、クライアント ライブラリのドキュメントを参照してください。
Java
この例では、Java クライアント ライブラリを使用しています。
-
AddSubscription.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.youtube_cmdline_addsubscription_sample; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; 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.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.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.ResourceId; import com.google.api.services.youtube.model.Subscription; import com.google.api.services.youtube.model.SubscriptionSnippet; import com.google.common.collect.Lists; /** * Demo of subscribing user to a channel using the YouTube Data API (V3) with OAuth2 for * authorization. * * @author Ibrahim Ulukaya */ public class AddSubscription { /** Global instance of the HTTP transport. */ private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); /** Global instance of the JSON factory. */ private static final JsonFactory JSON_FACTORY = new JacksonFactory(); /** Global instance of Youtube object to make all API requests. */ private static YouTube youtube; /** * Authorizes the installed application to access user's protected data. * * @param scopes list of scopes needed to run youtube upload. */ private static Credential authorize(List<String> scopes) throws Exception { // Load client secrets. GoogleClientSecrets clientSecrets = GoogleClientSecrets.load( JSON_FACTORY, AddSubscription.class.getResourceAsStream("/client_secrets.json")); // Checks that the defaults have been replaced (Default = "Enter X here"). if (clientSecrets.getDetails().getClientId().startsWith("Enter") || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) { System.out.println( "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential" + "into youtube-cmdline-uploadvideo-sample/src/main/resources/client_secrets.json"); System.exit(1); } // Set up file credential store. FileCredentialStore credentialStore = new FileCredentialStore( new File(System.getProperty("user.home"), ".credentials/youtube-api-uploadvideo.json"), JSON_FACTORY); // Set up authorization code flow. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialStore(credentialStore) .build(); // Build the local server and bind it to port 8080 LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build(); // Authorize. return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user"); } /** * Subscribes user's YouTube account to a user selected channel using OAuth2 for authentication. * * @param args command line args (not used). */ public static void main(String[] args) { // An OAuth 2 access scope that allows for full read/write access. List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube"); try { // Authorization. Credential credential = authorize(scopes); // YouTube object used to make all API requests. youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName( "youtube-cmdline-addsubscription-sample").build(); // We get the user selected channel to subscribe. String channelId = getChannelId(); System.out.println("You chose " + channelId + " to subscribe."); // We create a resourceId with channel id. ResourceId resourceId = new ResourceId(); resourceId.setChannelId(channelId); resourceId.setKind("youtube#channel"); // We create a snippet with ResourceId. SubscriptionSnippet snippet = new SubscriptionSnippet(); snippet.setResourceId(resourceId); // We create a subscription request with snippet. Subscription subscription = new Subscription(); subscription.setSnippet(snippet); /* * The subscription insert command includes: 1. Information we want returned after file is * successfully uploaded. 2. Subscription metadata we want to insert. */ YouTube.Subscriptions.Insert subscriptionInsert = youtube.subscriptions().insert("snippet,contentDetails", subscription); // Execute subscription. Subscription returnedSubscription = subscriptionInsert.execute(); // Print out returned results. System.out.println("\n================== Returned Subscription ==================\n"); System.out.println(" - Id: " + returnedSubscription.getId()); System.out.println(" - Title: " + returnedSubscription.getSnippet().getTitle()); } 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(); } } /* * Returns a channel id (String) from user via the terminal. */ private static String getChannelId() throws IOException { String channelId = ""; System.out.print("Please enter a channel id: "); BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); channelId = bReader.readLine(); if (channelId.length() < 1) { // If nothing is entered, defaults to "YouTube For Developers." channelId = "UCtVd0c0tGXuTSbU5d8cSBUg"; } return channelId; } }
-
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.google.api.services.samples.youtube.cmdline</groupId> <artifactId>youtube-cmdline-addsubscription-sample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>youtube-cmdline-addsubscription-sample</name> <url>http://maven.apache.org</url> <properties> <project.youtube.version>v3-rev16-1.12.0-beta</project.youtube.version> <project.http.version>1.12.0-beta</project.http.version> <project.oauth.version>1.12.0-beta</project.oauth.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <repositories> <repository> <id>google-api-services</id> <url>http://google-api-client-libraries.appspot.com/mavenrepo</url> </repository> </repositories> <dependencies> <!-- YouTube Data V3 support --> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-youtube</artifactId> <version>${project.youtube.version}</version> </dependency> <dependency> <groupId>com.google.http-client</groupId> <artifactId>google-http-client-jackson2</artifactId> <version>${project.http.version}</version> </dependency> <dependency> <groupId>com.google.oauth-client</groupId> <artifactId>google-oauth-client-jetty</artifactId> <version>${project.oauth.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>com.google.api.services.samples.youtube.cmdline.youtube_cmdline_addsubscription_sample.AddSubscription</mainClass> </configuration> </plugin> <!-- Forces Maven to use Java 1.6 --> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument></compilerArgument> </configuration> </plugin> </plugins> </build> </project>
-
client_secrets.json
{ "installed": { "client_id": "Enter Client ID", "client_secret": "Enter Client Secret" } }
PHP
この例では、PHP クライアント ライブラリを使用しています。
<?php /** * 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 { // This code subscribes the authenticated user to the specified channel. // Identify the resource being subscribed to by specifying its channel ID // and kind. $resourceId = new Google_Service_YouTube_ResourceId(); $resourceId->setChannelId('UCtVd0c0tGXuTSbU5d8cSBUg'); $resourceId->setKind('youtube#channel'); // Create a snippet object and set its resource ID. $subscriptionSnippet = new Google_Service_YouTube_SubscriptionSnippet(); $subscriptionSnippet->setResourceId($resourceId); // Create a subscription request that contains the snippet object. $subscription = new Google_Service_YouTube_Subscription(); $subscription->setSnippet($subscriptionSnippet); // Execute the request and return an object containing information // about the new subscription. $subscriptionResponse = $youtube->subscriptions->insert('id,snippet', $subscription, array()); $htmlBody .= "<h3>Subscription</h3><ul>"; $htmlBody .= sprintf('<li>%s (%s)</li>', $subscriptionResponse['snippet']['title'], $subscriptionResponse['id']); $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 has not authorized the application, start the OAuth 2.0 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>Returned Subscription</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())) # This method calls the API's youtube.subscriptions.insert method to add a # subscription to the specified channel. def add_subscription(youtube, channel_id): add_subscription_response = youtube.subscriptions().insert( part='snippet', body=dict( snippet=dict( resourceId=dict( channelId=channel_id ) ) )).execute() return add_subscription_response["snippet"]["title"] if __name__ == "__main__": argparser.add_argument("--channel-id", help="ID of the channel to subscribe to.", default="UCtVd0c0tGXuTSbU5d8cSBUg") args = argparser.parse_args() youtube = get_authenticated_service(args) try: channel_title = add_subscription(youtube, args.channel_id) except HttpError, e: print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content) else: print "A subscription to '%s' was added." % channel_title
Ruby
この例では、Ruby クライアント ライブラリを使用しています。
#!/usr/bin/ruby require 'rubygems' gem 'google-api-client', '>0.7' require 'google/api_client' require 'google/api_client/client_secrets' require 'google/api_client/auth/file_storage' require 'google/api_client/auth/installed_app' require 'trollop' # 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' def get_authenticated_service client = Google::APIClient.new( :application_name => $PROGRAM_NAME, :application_version => '1.0.0' ) youtube = client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION) file_storage = Google::APIClient::FileStorage.new("#{$PROGRAM_NAME}-oauth2.json") if file_storage.authorization.nil? client_secrets = Google::APIClient::ClientSecrets.load flow = Google::APIClient::InstalledAppFlow.new( :client_id => client_secrets.client_id, :client_secret => client_secrets.client_secret, :scope => [YOUTUBE_SCOPE] ) client.authorization = flow.authorize(file_storage) else client.authorization = file_storage.authorization end return client, youtube end def main opts = Trollop::options do opt :channel_id, 'ID of the channel to subscribe to.', :type => String, :default => 'UCtVd0c0tGXuTSbU5d8cSBUg' end client, youtube = get_authenticated_service begin body = { :snippet => { :resourceId => { :channelId => opts[:channel_id] } } } # Call the API's youtube.subscriptions.insert method to add the subscription # to the specified channel. subscriptions_response = client.execute!( :api_method => youtube.subscriptions.insert, :parameters => { :part => body.keys.join(',') }, :body_object => body ) puts "A subscription to '#{subscriptions_response.data.snippet.title}' was added." rescue Google::APIClient::TransmissionError => e puts e.result.body end end main
エラー
次の表は、このメソッドを呼び出したときに API からレスポンスとして返される可能性のあるエラー メッセージの一覧です。詳細については、エラー メッセージのドキュメントを参照してください。
エラー タイプ | エラーの詳細 | 説明 |
---|---|---|
badRequest |
accountClosed |
チャンネル登録を作成しようとしているアカウントは閉じられています。 |
badRequest |
accountSuspended |
チャンネル登録を作成しようとしているアカウントは一時停止されています。 |
badRequest |
subscriptionDuplicate |
作成しようとしているチャンネル登録は既に存在しています。 |
forbidden |
subscriptionForbidden |
リクエストが適切に認証されていないか、このチャンネルではサポートされていません。 |
notFound |
publisherNotFound |
リクエストの snippet.resourceId プロパティで指定されたリソースが見つかりません。 |
notFound |
subscriberNotFound |
リクエストで特定されているチャンネル登録者が見つかりません。 |
required |
publisherRequired |
リクエストで指定されたチャンネル登録リソースは、snippet.resourceId プロパティを使用して、登録するチャンネルを特定する必要があります。 |
実際に試してみる
API Explorer を使用し、ライブ データに対してこのメソッドを呼び出して、API リクエストとレスポンスを確認してください。