#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 3 22:42:36 2021 @author: fish Try to get and parse spotify playlists spotify:playlist:7hGGMcWOPgXj2qFw5DQyXP - likes_2021 spotify:playlist:2etpNxusBBUoXoxb3BOsF3 - likes_2020 Todo: ---- - extract the wanted info (track name, artist(s), picture url, track URI, etc) more elegantly - handle multiple artists - access token timeout? check if check is needed - find alternative to the kludge to prevent skipping first list Done: ---- 2021-04-04: handle longer playlists Outline: ------- - get playlist - extract playlist metadata - create playlist dictionary (---) - extract tracks & store - check if done, else iterate over next set of tracks (---) - store completed list, clean up. Playlist format: --------------- Playlist = {'name': '', 'image': '', 'uri': '', 'tracks': [ {'artist': '', 'name': '' }, {'artist': '' 'name': '' } ] } """ import json import requests # GLOBALS # kludge to avoid storing secrets in git repo with open('spotifyids') as f: CLIENT_ID, CLIENT_SECRET = f.readline().rstrip().split(',') AUTH_URL = 'https://accounts.spotify.com/api/token' BASE_URL = 'https://api.spotify.com/v1/' # base URL of all Spotify API endpoints PLAYLIST_ID = '37i9dQZF1EMdXVibVNv347' # temp def get_auth_response(client_id=CLIENT_ID, client_secret=CLIENT_SECRET): """ Get the auth response from the spotify servers, with token and timeout info """ auth_response = requests.post(AUTH_URL, { 'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret, }) if not auth_response.ok: raise SystemExit('Response from server not OK:\n %s' % auth_response.text) return auth_response.json() def get_access_token(): """ Get the temporary access token from the Spotify servers (POST request) """ auth_response_data = get_auth_response() # save the access token access_token = auth_response_data['access_token'] return access_token, auth_response_data def main(): """ main function """ token, auth_response = get_access_token() print(token) print("Token expires in {expires} seconds.".format( expires=auth_response['expires_in'])) if __name__ == '__main__': main()