Skip to content

Instantly share code, notes, and snippets.

@rhulha
Last active March 4, 2019 11:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhulha/985a1d95dbcd0e5fb9c4b3b9e782d144 to your computer and use it in GitHub Desktop.
Save rhulha/985a1d95dbcd0e5fb9c4b3b9e782d144 to your computer and use it in GitHub Desktop.
A Python script that uses the Google Youtube API to retrieve one's own playlists
import os
import json
import os.path
import google.oauth2.credentials
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow
CLIENT_SECRETS_FILE = "client_secret.json"
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'
def get_authenticated_service():
if os.path.isfile("credentials.json"):
with open("credentials.json", 'r') as f:
creds_data = json.load(f)
creds = Credentials(creds_data['token'])
else:
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
creds = flow.run_console()
creds_data = {
'token': creds.token,
'refresh_token': creds.refresh_token,
'token_uri': creds.token_uri,
'client_id': creds.client_id,
'client_secret': creds.client_secret,
'scopes': creds.scopes
}
print(creds_data)
with open("credentials.json", 'w') as outfile:
json.dump(creds_data, outfile)
return build(API_SERVICE_NAME, API_VERSION, credentials = creds)
def dump_channels(service):
results = service.channels().list(part='snippet,contentDetails,statistics', mine=True).execute()
with open("channels.json", 'w') as outfile:
json.dump(results, outfile)
print('This channel\'s ID is %s. Its title is %s, and it has %s views.' %
(results['items'][0]['id'],
results['items'][0]['snippet']['title'],
results['items'][0]['statistics']['viewCount']))
if __name__ == '__main__':
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
service = get_authenticated_service()
#results = service.subscriptions().list(part='snippet', mine=True)
results = service.playlists().list(part='snippet', mine=True, maxResults=50).execute();
for item in results['items']:
print (item['snippet']['title']);
results = service.playlists().list(part='snippet', mine=True, maxResults=50, pageToken=results['nextPageToken']).execute();
for item in results['items']:
print (item['snippet']['title']);
#with open("playlists.json", 'w') as outfile:
#json.dump(results, outfile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment