Spotipy

2.26.0 · active · verified Tue Apr 14

Spotipy is a lightweight Python library for the Spotify Web API, providing full access to music data and user authorization features. It offers abstractions for both Client Credentials and Authorization Code flows, making interactions with the Spotify platform straightforward. Maintained actively, it receives frequent updates to align with Spotify API changes and address security concerns.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use Spotipy with the Client Credentials Flow for server-to-server authentication, allowing access to public Spotify data without user interaction. It retrieves artist information and their albums. Ensure you have your Spotify API Client ID and Client Secret set as environment variables or replace the placeholders.

import os
from spotipy import Spotify
from spotipy.oauth2 import SpotifyClientCredentials

# Set your Spotify API credentials as environment variables
# SPOTIPY_CLIENT_ID='your_client_id'
# SPOTIPY_CLIENT_SECRET='your_client_secret'

client_id = os.environ.get('SPOTIPY_CLIENT_ID', 'YOUR_CLIENT_ID')
client_secret = os.environ.get('SPOTIPY_CLIENT_SECRET', 'YOUR_CLIENT_SECRET')

if client_id == 'YOUR_CLIENT_ID' or client_secret == 'YOUR_CLIENT_SECRET':
    print("Please set SPOTIPY_CLIENT_ID and SPOTIPY_CLIENT_SECRET environment variables.")
else:
    auth_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
    sp = Spotify(auth_manager=auth_manager)

    # Example: Search for an artist
    try:
        results = sp.search(q='artist:Queen', type='artist')
        if results['artists']['items']:
            artist = results['artists']['items'][0]
            print(f"Found artist: {artist['name']} (ID: {artist['id']})")
            albums = sp.artist_albums(artist['id'], album_type='album')
            print("Latest albums:")
            for album in albums['items'][:3]:
                print(f"- {album['name']}")
        else:
            print("Artist not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

view raw JSON →