+

Youtube Data API Subscription | Set-3

In previous articles Set 2 we discussed three methods:

  • To get a list of subscriptions associated with the channel ID
  • To get my subscriptions, i.e. associated with an authorized user account
  • To check if a subscription exists or not.

In this article, we will discuss the following two methods —

  • To insert a subscription
  • To remove a subscription

Before proceeding, we will first discuss how to create OAuth credentials ... Follow the steps below to create a Client ID and Secret.

  1. Go to Developer Console Google Google and click Sign In in the top right corner of the page. Sign in with your valid Google account credentials. If you do not have a Google account, first set up an account and then use your login details on the Google Developers homepage.
  2. Now navigate to developer toolbars and create a new project.
  3. Click on the Enable API option .
  4. In the search box, search for Youtube Data API and select the Youtube Data API option that appears in the dropdown.
  5. You will be redirected to the Youtube Data API information screen along with two options: ENABLE and TRY API .
  6. Click on the ENABLE, option to start working with the API.
  7. On the sidebar, under the "API and services "select" Credentials ".
  8. At the top of the page, select the OAuth consent screen tab. Select an email address, enter a product name if not already set, and click Save.
  9. On the tab Credentials, select the Create Credentials drop-down list and select OAuth Client ID . OAuth is typically used where authorization is required, such as retrieving a user`s favorite videos.
  10. Select the application type Other, enter the name YouTube Myvideos Data API, click the Create button, and click OK .
  11. Click the Download button to the right of the client ID to download the JSON file.
  12. Save and rename the file as client_secret.json and move it to your working directory.

Install additional libraries using the pip command:

pip install –upgrade google -auth google-auth-oauthlib google-auth-httplib2

Note We need to know the channel ID to insert and remove a subscription. Follow these steps to find the channel ID:

  1. Log into your Youtube account.
  2. Find the channel you want to subscribe to.
  3. Click and open channel. In the URL, you will see the channel ID after the keyword channel /
  4. Code to insert a subscription. This example shows how to insert a subscription to a Youtube channel identified by the channel ID specified in the parameter list. You can change the subscription by changing the snippet.resourceId.channelId property. This example adds a subscription to Derek Banas` channel.

    import os

    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 the file that contains
    # client_id and client_secret.

    CLIENT_SECRETS_FILE = "client_secret.json"

     
    # This area allows full read / write access
    # to the authenticated user account and
    # requires requests to use an SSL connection.

    SCOPES = [ ` https://www.googleapis.com/auth/youtube .force-ssl ` ]

    API_SERVICE_NAME = `youtube`

    API_VERSION = `v3`

      

    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)

     

    def print_response (response):

    print (response)

     
    # Create a resource based on a list
    # properties specified as key-value pairs.
    # Leave properties with empty values ​​outside
    # of the inserted resource.

    def build_resource (properties):

    resource = {}

    for p in properties:

    # Given a key like" snippet.title ", divide by

      #“ fragment "and" title ", where the" fragment "will be

      # object and title will be a property this object.

    prop_array = p.split ( `.` )

    ref = resource

    for pa in range ( 0 , len (prop_a rray)):

    is_array = False

    key = prop_array [pa]

     

    # For properties that have array values, convert the name as

    # & quot; snippet.tags [] & quot; for snippet.tags and set the flag for processing

    # array value.

    if key [ - 2 :] = = `[]` :

    key = key [ 0 : len (key) - 2 :]

    is_array = True

     

      if pa = = ( len (prop_array) - 1 ):

    # Leave properties without values ​​

    # from the inserted resource.

    if properties [p]:

    if is_array:

      ref [key] = properties [p] .split ( `, ` )

      else :

    ref [key ] = properties [p]

    elif key not in ref:

    # For example , property & quot; snippet.title & quot ;,

    # but the resource does not have a snippet yet ;

    # object. Create a snippet object here.

    # Setting & quot; ref = ref [key] & quot; means in

    # next time through a for loop in range ...

    # we will set the property to

    # fragment of the "object".

    ref [key] = {}

    ref = ref [key ]

    else :

    # For example, property & quot; snippet.description & quot ;,

    # and the resource already has a snippet object т & quot ;.

    ref = ref [key]

    return resource

     
    # Remove arguments keywords not set

    def remove_empty_kwargs ( * * kwargs):

      good_kwargs = {}

    if kwargs is not None :

      for key, value in kwargs.items ():

    if value:

    good_kwargs [key] = value

    return good_kwargs

     

    def subscriptions_insert (client, properties, * * kwargs):

    resource = build_resource (properties)

    kwargs = remove_empty_kwargs ( * * kwargs)

     

    response = client.subscriptions (). insert (

    body = resource, * * kwargs) .execute ()

     

    return print_response (response)

     

     

    if __ name__ = = `__main__` :

      # When running locally, disable OAuthlib

      # HTTP check. When in production

    # * do not * leave this option enabled.

    os.environ [ `OAUTHLIB_INSECURE_TRANSPORT` ] = `1`

    client = get_authenticated_service ()

     

    subscriptions_insert (client, 

    { ` snippet.resourceId.kind` : `youtube # channel` ,

    `s nippet.resourceId.channelId` : `UCwRXb5dUK4cvsHbx-rGzSgw` },

    part = `snippet` )

    Logout:
    During the execution of the code, you will be prompted to enter an authorization code. To get the code, you must follow the link indicated on the command line screen above the line: Enter the authorization code.

    Now follow the link and copy and paste the authorization code that you will receive by granting permission.

    If you can see from the above output it is clear that I am successful subscribed to the channel.

    Code to remove the subscription. this example shows how to delete a subscription. The id parameter is the subscription identifier, i.e. you can write on the command line while inserting the subscription, or alternatively run the code to list all subscriptions and write down the subscription ID for the subscription you want. In this example, I am deleting the subscription that I added in the code above.

    import os

    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 the file that contains the client_id
    # and client_secret.

    CLIENT_SECRETS_FILE = " client_secret.json "

      
    # This area allows full read / write access
    # to the authenticated user`s account and
    # Requires requests to use an SSL connection.

    SCOPES = [ ` https://www.googleapis.com/auth/youtube.force-ssl ` ]

    API_SERVICE_NAME = `youtube`

    API_VERSION = `v3`

      

    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)

     

    def print_response (response):

      print (response)

     
    # Create a resource based on a list of properties
    # given as key-value pairs. Leave properties with
    # empty values ​​from the inserted resource.

    def build_resource (properties):

    resource = {}

    for p in properties:

    # Given a key like & quot; snippet.title & quot;, divide by

    # "fragment" and "title" where the "fragment" will be

    # the object and title will be a property of this object.

    prop_array = p.split ( `.` )

    ref = resource

    for pa in range ( 0 , len (prop_array)) :

    is_array = False

    key = prop_array [pa]

     

    # For properties that have array values, convert the name as

    # & quot; snippet.tags [] & quot; for snippet.tags and set the flag for processing

    # array value.

    if key [ - 2 :] = = `[]` :

    key = key [ 0 : len (key) - 2 :]

    is_array = True

     

      if pa = = ( len (prop_array) - 1 ):

    # Leave properties without values ​​from the inserted resource.

    if properties [p]:

    if is_array:

    ref [key] = properties [p] .split ( `,` )

      else :

      ref [key] = properties [p]

    elif key not in ref:

      # For example, property & quot; snippet.title & quot ;,

    # but the resource does not yet have a "snippet"

    # object. Create a snippet object here.

    # Setting & quot; ref = ref [key] & quot; means in

    # next time through a for loop in range ...

    # we will set the property to

    # fragment of the "object".

    ref [key] = {}

    ref = ref [key ]

    else :

    # For example, property & quot; snippet.description & quot ;,

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             # and the resource already has a snippet object.

    ref = ref [key]

    return resource

     
    # Remove keyword arguments not set

    def remove_empty_kwargs ( * * kwargs ):