Block Heap

Web Developer's Blog

Brief intro into Spotify Web API with Spotipy Python library

1. Login to the developer dashboard using your existing Spotify account or create a new one. You’ll need to review their terms of service.


2. Create a client ID on the applications page.

App or Hardware Name: blockheap-tut-mar-2018
App or Hardware Description: Tutorial
What are you building: Website
Commercial: No


3. You’ll get a Client ID and Client Secret. It is recommended that you don’t share, post, or upload your client ID or secret to Github or any other public space.


4. Setup project files and dependencies

i. Create directory and change to that directory

    cd /Users/Charlie/Documents
    mkdir spotify-part-1
    cd /spotify-part-1

ii. Create virtual environment (pip to install)

    pip install virtualenv
    virtualenv env
    cd env/
    source env/bin/activate

iii. Install and freeze dependencies with pip package installer

    pip install spotipy
    pip install pandas (we'll use these later)
    pip freeze > requirements.txt (for easy installation later)

iv. Create main working file



5. Set environment variables used for authorization. The redirect URI shown below is just an example.

    export SPOTIPY_CLIENT_ID='your-spotify-client-id'
    export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'

Add redirect URL in Spotify dashboard
ii. Open your app
iii. Edit settings and add Redirect URI(s)


6. Start programming

The purpose of this basic app is to get saved tracks and save into a CSV file. For the purpose of this tutorial, we’re explicitly setting the Spotify username on line 6.

    #!/usr/bin/env python3

    import os
    import csv
    import spotipy
    import spotipy.util as util

    username = 'your-username'  # <-- UPDATE WITH YOUR USERNAME
    scope = 'user-library-read'
    token = util.prompt_for_user_token(username, scope)

    if token:

        cwd = os.getcwd()
        fp = cwd + '/saved-tracks.csv'
        song_details = []
        sp = spotipy.Spotify(auth=token)
        results = sp.current_user_saved_tracks(limit=50, offset=0)

        for item in results['items']:
            track = item['track']
            audio = sp.audio_features(tracks=[track['id']])[0]
            sd = {
                'id': track['id'],
                'name': track['name'],
                'artists': track['artists'][0]['name'],
                'danceability': audio['danceability'],
                'energy': audio['energy'],
                'key': audio['key'],
                'loudness': audio['loudness'],
                'mode': audio['mode'],
                'speechiness': audio['speechiness'],
                'acousticness': audio['acousticness'],
                'instrumentalness': audio['instrumentalness'],
                'liveness': audio['liveness'],
                'valence': audio['valence'],
                'tempo': audio['tempo'],
                'duration_ms': audio['duration_ms'],
                'time_signature': audio['time_signature']

        if os.path.isfile(fp):
            open(fp, 'a').close()

        with open(fp, 'w') as csvfile:
            fieldnames = [
                'id', 'name', 'artists', 'danceability', 'energy', 'key',
                'loudness', 'mode', 'speechiness', 'acousticness',
                'instrumentalness', 'liveness', 'valence', 'tempo',
                'duration_ms', 'time_signature']
            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        print("Can't get token for", username)

Example Source Files

Leave a Reply

Your email address will not be published.