Do it your self hobby code

How to list my liked video—Python Youtube API

This tutorial will teach you to write a python code that will list all the videos you liked in Youtube. Before we start, you need to obtain authentication first. Please read my previous post.

Create a new python file and save it as list_my_likes.py

Let start importing the libraries:

import os, sys, json, httplib2
import google_auth_oauthlib.flow
import googleapiclient.discovery
#import googleapiclient.errors
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.tools import run_flow
from oauth2client.client import flow_from_clientsecrets

Global variables:

CLIENT_SECRETS_FILE = os.path.join(sys.path[0], "client_secret.json")
CLIENT_OAUTH2_FILE  = os.path.join(sys.path[0], "client-oauth2.json")
YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
MISSING_CLIENT_SECRETS_MESSAGE = ""

Authentication function:

def get_authenticated_service():
  flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
    scope=YOUTUBE_READ_WRITE_SCOPE,
    message=MISSING_CLIENT_SECRETS_MESSAGE)
  
  storage = Storage(CLIENT_OAUTH2_FILE)
  credentials = storage.get()
  
  if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage)

  return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    http=credentials.authorize(httplib2.Http()))

The function to make a API request:

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 check_my_likes(client, **kwargs):
  kwargs = remove_empty_kwargs(**kwargs)
  response = client.playlistItems().list(
    **kwargs
  ).execute()
  return response

This is the function where you can control the youtube response by changing the parameters:

def show_my_likes(client):
  #https://www.youtube.com/playlist?list=LLe-IpLuWZg23Li0Pr3dv75g #my likes
  myPlaylistID = "LLe-IpLuWZg23Li0Pr3dv75g"
  results = check_my_likes(client,
    part='snippet,contentDetails',
    playlistId=myPlaylistID,
    maxResults=5)

  return results

Displaying and saving the result:

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

def print_video_title(results):
  for sActivies in results['items']:
      title = sActivies['snippet']['title']
      print (title)

Finally, the main function:

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

Let’s run the code:

python list_my_likes.py

As a result, I got the JSON file that contain the first 5 likes and below is the output of my terminal

Leave a Comment

Your email address will not be published.