Skip to content

Instantly share code, notes, and snippets.

@Mxhmovd
Created July 6, 2022 16:23
Show Gist options
  • Save Mxhmovd/500ef2b0e40df095fe8bef2d11cd5f59 to your computer and use it in GitHub Desktop.
Save Mxhmovd/500ef2b0e40df095fe8bef2d11cd5f59 to your computer and use it in GitHub Desktop.
Order/sort videos in YouTube playlist by views/popularity
#change KEY_PATH, API_KEY, LIST_ID
#API_KEY https://blog.hubspot.com/website/how-to-get-youtube-api-key
#KEY_PATH https://cloud.google.com/docs/authentication/getting-started
#LIST_ID for ex. list_id in https://www.youtube.com/watch?v=fjYptQjF1Tw&list=RDfjYptQjF1Tw&start_radio=1 is "RDfjYptQjF1Tw"
import os
from googleapiclient.discovery import build
credential_path = "KEY_PATH"
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path
api_key = os.environ.get('API_KEY')
youtube = build('youtube', 'v3', developerKey=api_key)
playlist_id = 'LIST_ID'
videos = []
nextPageToken = None
while True:
pl_request = youtube.playlistItems().list(
part='contentDetails',
playlistId=playlist_id,
maxResults=50,
pageToken=nextPageToken
)
pl_response = pl_request.execute()
vid_ids = []
for item in pl_response['items']:
vid_ids.append(item['contentDetails']['videoId'])
vid_request = youtube.videos().list(
part="statistics",
id=','.join(vid_ids)
)
vid_response = vid_request.execute()
for item in vid_response['items']:
vid_views = item['statistics']['viewCount']
vid_id = item['id']
yt_link = f'https://youtu.be/{vid_id}'
videos.append(
{
'views': int(vid_views),
'url': yt_link
}
)
nextPageToken = pl_response.get('nextPageToken')
if not nextPageToken:
break
videos.sort(key=lambda vid: vid['views'], reverse=True)
for video in videos: #you can control how many videos to retrieve
print(video['url'], video['views']) #check official doc to get more info
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment