The problem: You’re going to a festival with more bands than you could ever hope to see. You need a playlist with songs of all the bands playing so you can decide what to go and see and what to give a miss.
The solution: From a list of the artists, query the Spotify Search API with the artist name and save the URIs of the five most popular tracks returned by Spotify. Simples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import requests # for querying the API import json # for interpreting the data returned by the API def top5(artist): # an empty list of tracks tracks = [] # set up for requests module query_params = {'q': 'artist:'+artist} # nospace after colon endpoint = 'http://ws.spotify.com/search/1/track.json' response = requests.get(endpoint, params= query_params) print response.status_code print artist if response.status_code == 200: # server responds nicely data = json.loads(response.content) # load the json data i = 0 while len(tracks) < 5: # check we have some results, or haven't reached the end of them if int(data['info']['num_results']) == i or 100 == i: break # construct our 'track' library track = {'name':data['tracks'][i]['name'], 'artist':data['tracks'][i]['artists'][0]['name'], 'uri':data['tracks'][i]['href']} # check the returned artist matches the queried artist if artist == track['artist']: add = True # Check the track is available in my territory -> GB if not 'GB' in data['tracks'][i]['album']['availability']['territories']: add = False # Check the track isn't included already, eliminates including single and album versions for t in tracks: if t['name'] == track['name']: add = False # Passed all the tests? if add: tracks.append(track) i = i + 1 return tracks else: # bad response from the server print artist+' caused an error' |
The code above is the function which you can pass each artist name to. It’s only a few more lines of code to feed a list of artists into the function and save a playlist
list of tracks
. I’ve deliberately saved more data than is needed for this task, as you never know when it will come in handy e.g. creating a script to query the playlist
for all the artists that were successfully found.
Once you have all the URIs in a text file, with appropriate line breaks, you can drag this into the Spotify client and into a new playlist and they’ll magically become the tracks you want!
Interesting! But you should have the code in a textfile for download, having a hard time getting the indents correct to try it.
Hi Patrik,
Thanks for the feedback, I should really learn the trick to span the code over two lines, but for the mean time I’ve added the corrected script to a text file which you can download.
Cheers,
Andy