Building a Video View Count Ranking CLI with Python and the YouTube Data API
Introduction
In this article, I built a CLI tool using Python and the YouTube Data API v3.
The tool takes a YouTube channel as input and:
- Retrieves the latest 100 videos
- Retrieves the view count of each video
- Sorts the videos by view count in descending order
- Displays the top 10 videos in the terminal
π― Building a Minimal Working CLI Tool with Python
The goal of this project is to build a CLI tool that retrieves video information from a specified YouTube channel.
The tool can be launched from the terminal with:
python3 youtube_cli.py
π§© 1. Install the Required Libraries
First, install the libraries required to use the YouTube Data API from Python.
pip3 install google-api-python-client google-auth-oauthlib google-auth-httplib2
π§© 2. Enable the API in Google Cloud Console
To use the YouTube Data API, you first need to configure your project in Google Cloud.
- Open Google Cloud Console
- Create a new project
- Enable YouTube Data API v3
- Create an OAuth 2.0 Client ID
- Download
client_secret.json - Place
client_secret.jsonin your Python project directory
π§© 3. CLI Tool Implementation (youtube_cli.py)
Here is the Python CLI tool used in this project.
The user enters a YouTube channel name or handle, and the tool retrieves the latest 100 videos from that channel and displays the top 10 videos with the highest view counts.
youtube_cli.py
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"]
def get_channel_id_from_query(youtube, query):
# Search YouTube for the specified channel name or keyword
print(f"Searching for a channel matching: γ{query}γ")
response = youtube.search().list(
part="snippet",
q=query,
type="channel",
maxResults=1
).execute()
items = response.get("items", [])
if not items:
raise ValueError(f"Channel γ{query}γ was not found.")
channel_id = items[0]["snippet"]["channelId"]
channel_title = items[0]["snippet"]["title"]
print(f"Target channel: γ {channel_title} γ\n")
return channel_id
def main():
TOP_N = 10
MAX_VIDEOS = 100 # Maximum number of recent videos to retrieve
# OAuth authentication
flow = InstalledAppFlow.from_client_secrets_file(
"client_secret.json", SCOPES
)
creds = flow.run_local_server(port=0)
youtube = build("youtube", "v3", credentials=creds)
# 1. Ask the user for a channel name or keyword
user_query = input(
"Enter the name of the YouTube channel you want to analyze: "
).strip()
if not user_query:
print("No channel name was entered. Exiting.")
return
# Get the channel ID
try:
channel_id = get_channel_id_from_query(youtube, user_query)
except ValueError as e:
print(e)
return
# Get the channel's uploads playlist ID
channel_info = youtube.channels().list(
part="contentDetails",
id=channel_id
).execute()
uploads_playlist_id = (
channel_info["items"][0]
["contentDetails"]
["relatedPlaylists"]
["uploads"]
)
# Retrieve up to 100 recent video IDs
video_ids = []
next_page_token = None
print("Retrieving the latest videos...")
while True:
playlist_items = youtube.playlistItems().list(
part="contentDetails",
playlistId=uploads_playlist_id,
maxResults=50,
pageToken=next_page_token
).execute()
for item in playlist_items.get("items", []):
video_ids.append(item["contentDetails"]["videoId"])
# Stop when the maximum number of videos is reached
if len(video_ids) >= MAX_VIDEOS:
break
if len(video_ids) >= MAX_VIDEOS:
break
next_page_token = playlist_items.get("nextPageToken")
if not next_page_token:
break
videos = []
print(f"Retrieving data for the latest {len(video_ids)} videos...")
# Process videos in batches of up to 50
for i in range(0, len(video_ids), 50):
chunk_ids = video_ids[i:i+50]
ids_string = ",".join(chunk_ids)
stats = youtube.videos().list(
part="statistics,snippet",
id=ids_string
).execute()
for info in stats.get("items", []):
title = info["snippet"]["title"]
views = int(info["statistics"].get("viewCount", 0))
video_id = info["id"]
videos.append({
"title": title,
"views": views,
"id": video_id
})
# Sort by view count
videos.sort(key=lambda x: x["views"], reverse=True)
# Display the ranking
print(
f"\n--- View Count Ranking for γ{user_query}γ "
f"(Top {TOP_N}) ---"
)
for i, v in enumerate(videos[:TOP_N], start=1):
print(
f"{i}. {v['title']} - {v['views']:,} views "
f"(https://www.youtube.com/watch?v={v['id']})"
)
if __name__ == "__main__":
main()
Running the CLI Tool
Run the following command from the directory containing youtube_cli.py:
./scripts % python3 youtube_cli.py
A browser window will open, and you will be asked to select a Google account.

Select the account you want to use for authentication.
After authentication is completed, return to the terminal.
![]()
You should then see the following prompt:
Enter the name of the YouTube channel you want to analyze:
For example, enter:
Enter the name of the YouTube channel you want to analyze: @SaturdayNightLive
Output
The tool will search for the specified channel and retrieve its latest videos.
Searching for a channel matching: γ@SaturdayNightLiveγ
Target channel: γ Saturday Night Live γ
Retrieving the latest videos...
Retrieving data for the latest 100 videos...
--- View Count Ranking for γ@SaturdayNightLiveγ (Top 10) ---
1. you know what this song needs? - 12,489,263 views (https://www.youtube.com/watch?v=Q1ZabPOA76w)
2. cast list reveal - 6,404,227 views (https://www.youtube.com/watch?v=Uw9ub2NnMYY)
3. Jeffrey Epstein Ghost Cold Open - SNL - 5,039,611 views (https://www.youtube.com/watch?v=YzqJh6WnQOM)
4. some wires were crossed - 4,867,443 views (https://www.youtube.com/watch?v=HZtZATonxw8)
5. weekend update! - 3,381,263 views (https://www.youtube.com/watch?v=gROY9_gPA4Q)
6. the american dream - 3,258,007 views (https://www.youtube.com/watch?v=wCSDinZYJEQ)
7. finale joke swap! - 3,054,821 views (https://www.youtube.com/watch?v=WMRcO1VuUhw)
8. Weekend Update: Colin Jost and Michael Che Swap Jokes for Season 51 Finale - SNL - 3,041,289 views (https://www.youtube.com/watch?v=WY8lNAmso1Y)
9. talking to a mechanic be like - 2,916,902 views (https://www.youtube.com/watch?v=-VAQxjvYxZ8)
10. now kiss - 2,871,220 views (https://www.youtube.com/watch?v=ruX5XweYnOI)
π― Conclusion
The YouTube Data API CLI tool follows this flow:
Enable the API in Google Cloud
β
Create an OAuth 2.0 Client ID
β
Place client_secret.json in the Python project
β
Authenticate with a Google account
β
Call the YouTube Data API
β
Receive the response in JSON format
β
Process the required data with Python
β
Display the results in the terminal
In short:
Configure the API in Google Cloud, authenticate the Python application with OAuth, call the YouTube Data API, process the returned JSON data with Python, and display the results through a CLI.

Top comments (0)