This post is the first episode of the #getyourdata series. I will show you how to use Python to get data from Spotify. If you are a programmer, a Data Scientist, Engineer or anyone who works with Python, It could be interesting to learn some new API to improve and enrich your skills creating a new project to add to your portfolio. Here you will learn the basics to access and interact with Spotify through a Python library: Spotipy
Spotify in Python
Spotify provides Web API on which the Python community has developed an API wrapper called Spotipy. To install Spotipy, as is usual for python developers, you need pip running the following command from a terminal
> pip install spotipy
If you have any problems during installation you can consult the documentation on Github.
Before starting
Before starting let’s see the necessary steps to use Spotipy API successfully:
- Register an account on Spotify, it is not required premium account: Spotify
- Access to your Developer Dashboard: Developer Dashboard
- Create an app: Dashboard Spotify Developer
Register a Spotify account
It is easy to register on Spotify at the following link: Register Spotify Account
You can register a free account or premium, it is the same.
Access to Developer Dashboard
Now access your Developer Dashboard and click on Sign up for a free Spotify account here (if you need to register an account).
In case you already have an account, click on Login using your credentials.
Create an app
Once you arrived on your dashboard click on create an app, a dialogue box will appear asking you a name and a description. Then, you must accept terms and conditions and click on create, as a result, you’ll see your new application in your dashboard.
You have to click on the green box with your app’s name to access App’s Dashboard where you can look at insights and some other information. Especially, the most important one is the top-left section where are displayed the client id and client secret (do not spread these two keys).
Python Tutorial for Spotipy
Ok, no more words, it’s time for action.
Let’s start importing the necessary libraries and to set the variables CLIENT_ID and CLIENT_SECRET with the values provided by App’s Dashboard.
import spotipy from spotipy.oauth2 import SpotifyOAuth CLIENT_ID = 'XXXXXXXXXXXX' CLIENT_SECRET = 'XXXXXXXXXXXX'
Authentication Flow
Since it is not possible to use the Spotify API without authorization we need to get it through an authorization flow, no worry! Here is an example.
scopes = ["user-follow-read", 'ugc-image-upload', 'user-read-playback-state', 'user-modify-playback-state', 'user-read-currently-playing', 'user-read-private', 'user-read-email', 'user-follow-modify', 'user-follow-read', 'user-library-modify', 'user-library-read', 'streaming', 'app-remote-control', 'user-read-playback-position', 'user-top-read', 'user-read-recently-played', 'playlist-modify-private', 'playlist-read-collaborative', 'playlist-read-private', 'playlist-modify-public'] # L'auth flow si basa sul eseguire questo codice # Andare alla redirect uri e ricopiare l'intera url nel prompt in console sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri='http://127.0.0.1:9090', scope=scopes))
First, the variable scopes is a list of permissions that the user has to accept to authorize our application to access the information you desire. In few words, the scopes list contains all possible permissions from the documentation, for more details you can refer to the Scopes Documentation
Second, the Redirect URI parameter must match the value of Redirect URI set in your application. So that, go to Your Dashboard (navigate to your application and then [Edit Settings] on the top-right menu). The redirect URI can be any valid URI, it could be http://localhost:9090 as well as http://127.0.0.1:9090 or your website and so on.
Note: You can also set an environment variable SPOTIFY_REDIRECT_URI in your Pc’s settings, of course, the value of this variable should match the value in the app’s dashboard.
First Run!
You can run the snippet and you will be redirected to the specified URI, accept the requested permissions (specified by you with the scope parameter), you’ll be redirected to another page. Ok! Now, copy the generated URL from the address bar.
When you come back to the program in execution, you can see that it is asking for an URL, paste the URL copied in the previous step and press Enter.
Fiuuu! It was long but now you have a new .cache file in your project directory, this file is useful to regenerate the token just obtained through the Authorization Flow.
Access to your own data
You are ready! Now it’s time to access our data as I promise. Let’s start with user data
user_data = sp.current_user() print('My data:') print('Name:', user_data['display_name']) print('Followers:', user_data['followers']['total']) print('Link:', user_data['external_urls']['spotify']) print('Account:', user_data['product'])
My data: Name: Chaw359 Followers: 0 Link: https://open.spotify.com/user/hqep88qj40tzqtzoxcbsm371z Account: premium
You can see, it is possible to access our personal data and, in general, to the personal data of the user that uses our app.
Followed Artists
Moreover, it is possible to access to user’s followed artists
print('Followed Artists') artists = sp.current_user_followed_artists()['artists'] while artists: for i, artist in enumerate(artists['items']): print(f'{i} - {artist["name"]}') print(f'\tFollowers: {artist["followers"]["total"]}') print(f'\tPopularity: {artist["popularity"]}') print(f'\tGenres: {artist["genres"]}') if artists['next']: artists = sp.next(artists) else: artists = None
Followed Artists: 0 - Salmo Followers: 2123562 Popularity: 77 Genres: ['italian hip hop', 'italian underground hip hop', 'rap sardegna'] 1 - Marracash Followers: 1503078 Popularity: 82 Genres: ['italian hip hop', 'italian underground hip hop', 'rap napoletano'] 2 - Guè Followers: 1764304 Popularity: 80 Genres: ['italian hip hop'] 3 - Eminem Followers: 50330187 Popularity: 93 Genres: ['detroit hip hop', 'hip hop', 'rap']
Playlists
Furthermore, it is possible to access user’s playlists:
print('Playlists:') playlists = sp.current_user_playlists() while playlists: for i, playlist in enumerate(playlists['items']): print(f'{i} - {playlist["name"]}') print(f'\tNumber of tracks: {playlist["tracks"]["total"]}') print(f'\tUrl: {playlist["external_urls"]}') print(f'\tDescription: {playlist["description"]}') if playlists['next']: playlists = sp.next(playlists) else: playlists = None
Playlists: 0 - Italia Number of tracks: 4 Url: {'spotify': 'https://open.spotify.com/playlist/6iXzIY2WLVxDC8pUf05XKD'} Description: Favourite Italian songs 1 - Napule Number of tracks: 16 Url: {'spotify': 'https://open.spotify.com/playlist/3OPQo92siyKFYZNICmxTmC'} Description: Naples songs 2 - Rap Number of tracks: 155 Url: {'spotify': 'https://open.spotify.com/playlist/4tttzPBFW7LEaAEiVkj80E'} Description: Rap and hip pop songs
In addition, from each playlist item, it is possible to get the playlist id with which to obtain the playlist details. Here is an example.
playlist = sp.playlist(playlist_id='xxxxxxxxxxxxxxxxx') print('Playlist name:', playlist['name']) playlist_tracks = playlist['tracks'] while playlist_tracks: for i, track in enumerate(playlist_tracks['items']): print(f'{i} - {track["track"]["name"]}') print(f'\tAdded at: {track["added_at"]}') # from artists key you can access to artists details print(f'\tArtist: {track["track"]["artists"][0]["name"]}') # from album key you can access to album details print(f'\tAlbum: {track["track"]["album"]["name"]}') print(f'\tDuration: {round(track["track"]["duration_ms"] / 60000, 2)} minutes') print(f'\tPopularity: {track["track"]["popularity"]}') if playlist_tracks['next']: playlist_tracks = sp.next(playlist_tracks) else: playlist_tracks = None
Playlist name: Rap Motivazionale 0 - Veleno 8 (feat. Gemitaiz) Added at: 2021-11-19T00:01:00Z Artist: MadMan Album: MM Vol. 4 Duration: 3.04 minutes Popularity: 70 1 - LORO Added at: 2021-11-19T00:01:00Z Artist: Marracash Album: NOI, LORO, GLI ALTRI Duration: 3.3 minutes Popularity: 76 2 - Russell Crowe Added at: 2021-11-19T00:01:00Z Artist: Salmo Album: Midnite (Deluxe Version) Duration: 2.96 minutes Popularity: 3 ......
Recently Played
Of course, it is possible to access to user’s recently played songs (but only the 50 recently played).
print('Recently Played') recents = sp.current_user_recently_played() while recents: for i, track in enumerate(recents['items']): print(f'{i} - {track["track"]["name"]}') if recents['next']: recents = sp.next(recents) else: recents = None
0 - Driving Home for Christmas 1 - This Is Christmas Time 2 - Let It Snow 3 - My Christmas Baby (The Sweetest Gift) ....
Conclusion
To conclude, Spotipy API is a really simple and amazing Python library to use and gives the possibility to access a wide range of users’ data, songs, artists, playlists, podcasts and moreover. There are infinite ways to integrate this API everywhere. It’s up to you.
Just a minute to leave feedback, feel free to leave a comment or a like or both! See you in the next post: How to get data from your Strava’s account