Do it your self hobby code

How to list subscription—Python Youtube API

How to list subscription on Youtube API. This a continuation of Python Youtube API tutorial

Previously, we created a sample python program that authenticate a user.

How to list subscription

To list the users youtube subscription, we have to modify the previous code and save it as list_subscription.py

Add this code after def get_authenticated_service(args):

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

Next,

def list_my_subscriptions(client, **kwargs):
  kwargs = remove_empty_kwargs(**kwargs)
  response = client.subscriptions().list(
    **kwargs
  ).execute()
  return response

Subscription function

def show_subscriptions(client):
  results = list_my_subscriptions(client,
    part='snippet,contentDetails',
    mine=True)

  for subscription in results['items']:
      title = subscription['snippet']['title']
      channelid = subscription['snippet']['resourceId']['channelId']
      print (title,channelid)

  return results

Add the function on main

if __name__ == "__main__":
    client = get_authenticated_service()
    results = show_subscriptions(client)

Now run the code. This will print the subscriptions.

python list_subscription.py

Save Subscriptions as Json file

If you want to save the result as json file, add this code:

import json  #add this on the top

def write_json(data):
    filename  = os.path.join(sys.path[0], "subs.json")
    with open(filename, 'w') as outfile:
        json.dump(data, outfile)

On main, add the last line of code:

if __name__ == "__main__":
    client = get_authenticated_service()
    results = show_subscriptions(client)
    write_json(results)

This will save the results as subs.json file on the same directory.

Leave a Comment

Your email address will not be published.