DEV Community

Alex Spinov
Alex Spinov

Posted on

Spotify Has a Free API — Search Tracks, Get Audio Features, and Build Playlists Programmatically

Spotify has over 100 million tracks. And their API is free, well-documented, and surprisingly powerful.

You can search tracks, analyze audio features (danceability, energy, tempo), get artist data, and even create playlists — all programmatically.

Here is how.


Step 1: Get Your API Credentials (2 minutes)

  1. Go to developer.spotify.com/dashboard
  2. Create an app (any name)
  3. Copy your Client ID and Client Secret

Step 2: Get an Access Token

import requests
import base64

CLIENT_ID = 'your_client_id'
CLIENT_SECRET = 'your_client_secret'

# Get token
auth_string = base64.b64encode(f'{CLIENT_ID}:{CLIENT_SECRET}'.encode()).decode()
response = requests.post('https://accounts.spotify.com/api/token', 
    headers={'Authorization': f'Basic {auth_string}'},
    data={'grant_type': 'client_credentials'}
)
token = response.json()['access_token']
headers = {'Authorization': f'Bearer {token}'}
Enter fullscreen mode Exit fullscreen mode

This token lasts 1 hour. No user login needed for search and public data.


Search for Tracks

def search_tracks(query, limit=5):
    response = requests.get('https://api.spotify.com/v1/search', 
        headers=headers,
        params={'q': query, 'type': 'track', 'limit': limit}
    )
    tracks = response.json()['tracks']['items']
    return [{
        'name': t['name'],
        'artist': t['artists'][0]['name'],
        'album': t['album']['name'],
        'popularity': t['popularity'],
        'preview_url': t['preview_url'],
        'spotify_url': t['external_urls']['spotify']
    } for t in tracks]

results = search_tracks('lofi hip hop')
for track in results:
    print(f"{track['name']}{track['artist']} (popularity: {track['popularity']})")
Enter fullscreen mode Exit fullscreen mode

Get Audio Features (The Cool Part)

Spotify analyzes every track and provides features like:

def get_audio_features(track_id):
    response = requests.get(
        f'https://api.spotify.com/v1/audio-features/{track_id}',
        headers=headers
    )
    features = response.json()
    return {
        'danceability': features['danceability'],  # 0.0 to 1.0
        'energy': features['energy'],              # 0.0 to 1.0
        'tempo': features['tempo'],                # BPM
        'valence': features['valence'],            # 0.0 (sad) to 1.0 (happy)
        'acousticness': features['acousticness'],  # 0.0 to 1.0
        'instrumentalness': features['instrumentalness']
    }
Enter fullscreen mode Exit fullscreen mode

Real use case: I built a mood-based playlist generator. User picks "energetic" or "chill", and the app filters tracks by energy and valence scores.


Get an Artist's Top Tracks

def get_artist_top_tracks(artist_id, market='US'):
    response = requests.get(
        f'https://api.spotify.com/v1/artists/{artist_id}/top-tracks',
        headers=headers,
        params={'market': market}
    )
    return [{
        'name': t['name'],
        'popularity': t['popularity']
    } for t in response.json()['tracks'][:5]]
Enter fullscreen mode Exit fullscreen mode

Get Recommendations

def get_recommendations(seed_tracks, limit=10):
    response = requests.get('https://api.spotify.com/v1/recommendations',
        headers=headers,
        params={
            'seed_tracks': ','.join(seed_tracks[:5]),
            'limit': limit,
            'target_energy': 0.8,
            'target_danceability': 0.7
        }
    )
    return [{
        'name': t['name'],
        'artist': t['artists'][0]['name']
    } for t in response.json()['tracks']]
Enter fullscreen mode Exit fullscreen mode

You can set targets for any audio feature — find tracks with specific BPM, energy, or mood.


What You Can Build

  1. Mood-based playlist generator — filter by valence and energy
  2. Music discovery tool — find similar tracks using recommendations API
  3. DJ helper — find tracks at specific BPM for smooth transitions
  4. Analytics dashboard — visualize your listening patterns
  5. Workout playlist builder — high energy + high BPM tracks only

API Limits

  • Free tier: no hard rate limit, but Spotify may throttle at ~100 requests/30 seconds
  • Client credentials flow: access to all public data (no user data)
  • User auth flow: access to private playlists, listening history, saved tracks

What would you build with the Spotify API?

I am always looking for creative project ideas. Have you built anything with music data? Or is there a Spotify feature you wish existed? Drop it in the comments.


I write about free APIs, Python automation, and developer tools. Follow for weekly discoveries.

More APIs: 8 Free APIs That Are Genuinely Useful | arXiv API Guide


More from me: 10 Dev Tools I Use Daily | 77 Scrapers on a Schedule | 150+ Free APIs

Top comments (0)