Skip to content

Commit 692ccae

Browse files
committed
YouTube API Tutorial
1 parent ed3c42f commit 692ccae

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import os
2+
from googleapiclient.discovery import build
3+
4+
api_key = os.environ.get('YT_API_KEY')
5+
6+
youtube = build('youtube', 'v3', developerKey=api_key)
7+
8+
playlist_id = 'PL8uoeex94UhHFRew8gzfFJHIpRFWyY4YW'
9+
10+
videos = []
11+
12+
nextPageToken = None
13+
while True:
14+
pl_request = youtube.playlistItems().list(
15+
part='contentDetails',
16+
playlistId=playlist_id,
17+
maxResults=50,
18+
pageToken=nextPageToken
19+
)
20+
21+
pl_response = pl_request.execute()
22+
23+
vid_ids = []
24+
for item in pl_response['items']:
25+
vid_ids.append(item['contentDetails']['videoId'])
26+
27+
vid_request = youtube.videos().list(
28+
part="statistics",
29+
id=','.join(vid_ids)
30+
)
31+
32+
vid_response = vid_request.execute()
33+
34+
for item in vid_response['items']:
35+
vid_views = item['statistics']['viewCount']
36+
37+
vid_id = item['id']
38+
yt_link = f'https://youtu.be/{vid_id}'
39+
40+
videos.append(
41+
{
42+
'views': int(vid_views),
43+
'url': yt_link
44+
}
45+
)
46+
47+
nextPageToken = pl_response.get('nextPageToken')
48+
49+
if not nextPageToken:
50+
break
51+
52+
videos.sort(key=lambda vid: vid['views'], reverse=True)
53+
54+
for video in videos[:10]:
55+
print(video['url'], video['views'])

0 commit comments

Comments
 (0)