Spotify API Interaction with Spotipy
This guide demonstrates how to interact with the Spotify Web API using the spotipy library. It covers authentication using the Client Credentials Flow (suitable for server-side scripts that don't access user-private data) and fetching artist information and top tracks.
Modules Used:
spotipy: A lightweight Python library for the Spotify Web API.- argparse: To handle command-line arguments.
Prerequisites
- Spotify Developer Account: Log in to the Spotify Developer Dashboard.
- Create an App: Click "Create an App", give it a name and description.
- Get Credentials: Note down your Client ID and Client Secret.
Installation
pip install spotipy
The Code
Save this as spotify_tool.py.
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import argparse
import os
import sys
def get_spotify_client(client_id=None, client_secret=None):
"""
Authenticates with Spotify using Client Credentials Flow.
Spotipy automatically looks for SPOTIPY_CLIENT_ID and SPOTIPY_CLIENT_SECRET
environment variables if arguments are not provided.
"""
try:
auth_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
sp = spotipy.Spotify(auth_manager=auth_manager)
return sp
except Exception as e:
print(f"Authentication Error: {e}")
return None
def search_artist(sp, name):
print(f"Searching for '{name}'...")
results = sp.search(q='artist:' + name, type='artist')
items = results['artists']['items']
if len(items) > 0:
artist = items[0]
print(f"\n--- Artist Info ---")
print(f"Name: {artist['name']}")
print(f"Followers: {artist['followers']['total']:,}")
print(f"Genres: {', '.join(artist['genres'])}")
print(f"Popularity: {artist['popularity']}%")
print(f"URL: {artist['external_urls']['spotify']}")
return artist['id']
else:
print(f"Artist '{name}' not found.")
return None
def get_top_tracks(sp, artist_id):
results = sp.artist_top_tracks(artist_id)
print("\n--- Top Tracks (US) ---")
for i, track in enumerate(results['tracks'][:10]):
print(f"{i+1}. {track['name']} - {track['album']['name']}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Spotify CLI Tool")
parser.add_argument("artist", help="Name of the artist to search for")
parser.add_argument("--id", help="Spotify Client ID")
parser.add_argument("--secret", help="Spotify Client Secret")
args = parser.parse_args()
# It is best practice to set environment variables:
# export SPOTIPY_CLIENT_ID='your_id'
# export SPOTIPY_CLIENT_SECRET='your_secret'
sp = get_spotify_client(args.id, args.secret)
if sp:
try:
artist_id = search_artist(sp, args.artist)
if artist_id:
get_top_tracks(sp, artist_id)
except Exception as e:
print(f"An error occurred: {e}")
print("Check your credentials.")
Usage
-
Set Environment Variables (Recommended):
# Linux/macOS export SPOTIPY_CLIENT_ID='your_client_id' export SPOTIPY_CLIENT_SECRET='your_client_secret' # Windows (PowerShell) $env:SPOTIPY_CLIENT_ID='your_client_id' $env:SPOTIPY_CLIENT_SECRET='your_client_secret' -
Run the script:
python spotify_tool.py "Daft Punk" -
Or pass credentials directly:
python spotify_tool.py "The Beatles" --id YOUR_ID --secret YOUR_SECRET