Subscriptions: insert

Adds a subscription for the authenticated user's channel. Try it now.

Quota impact: A call to this method has a quota cost of 50 units in addition to the costs of the specified resource parts.



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.

Required parameters
part string
The part parameter serves two purposes in this operation. It identifies the properties that the write operation will set as well as the properties that the API response will include.

The following list contains the part names that you can include in the parameter value and the quota cost for each part:
  • contentDetails: 2
  • id: 0
  • snippet: 2
  • subscriberSnippet: 2

Request body

Provide a subscription resource in the request body. For that resource:

  • You must specify a value for these properties:

    • snippet.resourceId

  • You can set values for these properties:

    • snippet.resourceId


If successful, this method returns a subscription 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.

Apps Script

This sample subscribes the active user to the GoogleDevelopers YouTube channel, specified by the channelId.
function addSubscription() {
  // Replace this channel ID with the channel ID you want to subscribe to
  var channelId = 'UC9gFih9rw0zNCK3ZtoKQQyA';

  var resource = {
    snippet: {
      resourceId: {
        kind: 'youtube#channel',
        channelId: channelId

  try {
    var response = YouTube.Subscriptions.insert(resource, 'snippet');
  } catch (e) {
    if(e.message.match('subscriptionDuplicate')) {
      Logger.log('Cannot subscribe; already subscribed to channel: ' + channelId);
    } else {
      Logger.log('Error adding subscription: ' + e.message);


This sample calls the API's subscriptions.insert method to add a subscription to a specified channel.

This example uses the Java client library.

 * 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
 * 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.



import java.util.List;

 * Subscribe a user to a channel using the YouTube Data API (v3). Use
 * OAuth 2.0 for authorization.
 * @author Ibrahim Ulukaya
public class AddSubscription {

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

     * Subscribe the user's YouTube account to a user-selected channel.
     * @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("");

        try {
            // Authorize the request.
            Credential credential = Auth.authorize(scopes, "addsubscription");

            // This object is used to make YouTube Data API requests.
            youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential).setApplicationName(

            // We get the user selected channel to subscribe.
            // Retrieve the channel ID that the user is subscribing to.
            String channelId = getChannelId();
            System.out.println("You chose " + channelId + " to subscribe.");

            // Create a resourceId that identifies the channel ID.
            ResourceId resourceId = new ResourceId();

            // Create a snippet that contains the resourceId.
            SubscriptionSnippet snippet = new SubscriptionSnippet();

            // Create a request to add the subscription and send the request.
            // The request identifies subscription metadata to insert as well
            // as information that the API server should return in its response.
            Subscription subscription = new Subscription();
            YouTube.Subscriptions.Insert subscriptionInsert =
                    youtube.subscriptions().insert("snippet,contentDetails", subscription);
            Subscription returnedSubscription = subscriptionInsert.execute();

            // Print information from the API response.
            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());

        } catch (IOException e) {
            System.err.println("IOException: " + e.getMessage());
        } catch (Throwable t) {
            System.err.println("Throwable: " + t.getMessage());

     * Prompt the user to enter a channel ID and return it.
    private static String getChannelId() throws IOException {

        String channelId = "";

        System.out.print("Please enter a channel id: ");
        BufferedReader bReader = new BufferedReader(new InputStreamReader(;
        channelId = bReader.readLine();

        if (channelId.length() < 1) {
            // If nothing is entered, defaults to "YouTube For Developers."
            channelId = "UCtVd0c0tGXuTSbU5d8cSBUg";
        return channelId;


This sample calls the API's subscriptions.insert method to add a subscription to a specified channel.

This example uses the PHP client library.


 * 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 = '';
  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();

    // Create a snippet object and set its resource ID.
    $subscriptionSnippet = new Google_Service_YouTube_SubscriptionSnippet();

    // Create a subscription request that contains the snippet object.
    $subscription = new Google_Service_YouTube_Subscription();

    // 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>',
    $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 has not authorized the application, start the OAuth 2.0 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>Returned Subscription</title>


This sample calls the API's subscriptions.insert method to add a subscription to a specified channel.

This example uses the Python client library.


# This code sample shows how to add a channel subscription.
# The default channel-id is for the GoogleDevelopers YouTube channel.
# Sample usage:
# python --channel-id=UC_x5XG1OV2P6uZZ5FSM9Ttw

import argparse
import os
import re

import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow

# 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 Cloud Console }} at
# {{ }}.
# 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:
# For more information about the client_secrets.json file format, see:
CLIENT_SECRETS_FILE = 'client_secret.json'

# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account.
SCOPES = ['']
API_SERVICE_NAME = 'youtube'

def get_authenticated_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)

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

  return add_subscription_response['snippet']['title']

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='Process arguments.')
  parser.add_argument('--channel-id', help='ID of the channel to subscribe to.',
  args = parser.parse_args()

  youtube = get_authenticated_service()
    channel_title = add_subscription(youtube, args.channel_id)
  except HttpError, e:
    print 'An HTTP error %d occurred:\n%s' % (e.resp.status, e.content)
    print 'A subscription to \'%s\' was added.' % channel_title


This sample calls the API's subscriptions.insert method to add a subscription to a specified channel.

This example uses the Ruby client library.


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.

def get_authenticated_service
  client =
    :application_name => $PROGRAM_NAME,
    :application_version => '1.0.0'
  youtube = client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION)

  file_storage ="#{$PROGRAM_NAME}-oauth2.json")
  if file_storage.authorization.nil?
    client_secrets = Google::APIClient::ClientSecrets.load
    flow =
      :client_id => client_secrets.client_id,
      :client_secret => client_secrets.client_secret,
      :scope => [YOUTUBE_SCOPE]
    client.authorization = flow.authorize(file_storage)
    client.authorization = file_storage.authorization

  return client, youtube

def main
  opts = Trollop::options do
    opt :channel_id, 'ID of the channel to subscribe to.', :type => String,
          :default => 'UCtVd0c0tGXuTSbU5d8cSBUg'

  client, youtube = get_authenticated_service

    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 '#{}' was added."
  rescue Google::APIClient::TransmissionError => e
    puts e.result.body



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) subscriptionDuplicate The subscription that you are trying to create already exists.
badRequest (400) subscriptionForbidden You have reached your maximum number of subscriptions.
badRequest (400) subscriptionForbidden Subscribing to your own channel is not supported.
badRequest (400) subscriptionForbidden Too many recent subscriptions. Please try again in a few hours.
forbidden (403) subscriptionForbidden The request is not properly authenticated or not supported for this channel.
notFound (404) publisherNotFound The resource specified by the request's snippet.resourceId property cannot be found.
notFound (404) subscriberNotFound The subscriber identified with the request cannot be found.
required (400) publisherRequired The subscription resource specified in the request must use the snippet.resourceId property to identify the channel that is being subscribed to.

Send feedback about...

YouTube Data API
YouTube Data API