Convert Figma logo to code with AI

spotipy-dev logospotipy

A light weight Python library for the Spotify Web API

5,008
953
5,008
83

Top Related Projects

5,008

A light weight Python library for the Spotify Web API

Open Source Spotify client library

Basic examples to authenticate and fetch data using the Spotify Web API

A Node.js wrapper for Spotify's Web API.

Quick Overview

Spotipy is a lightweight Python library for the Spotify Web API. It provides a simple and intuitive interface for developers to interact with Spotify's extensive music database, allowing them to search for tracks, albums, and artists, manage playlists, and access user-related data.

Pros

  • Easy to use and well-documented API
  • Supports both synchronous and asynchronous operations
  • Handles authentication and token refresh automatically
  • Covers most Spotify Web API endpoints

Cons

  • Limited support for some advanced features
  • Occasional issues with rate limiting for heavy usage
  • Dependency on Spotify's API, which may change over time
  • Requires Spotify developer account and credentials

Code Examples

  1. Searching for tracks:
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials())

results = sp.search(q='Bohemian Rhapsody', type='track')
for track in results['tracks']['items']:
    print(track['name'], '-', track['artists'][0]['name'])
  1. Creating a playlist:
from spotipy.oauth2 import SpotifyOAuth

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope="playlist-modify-public"))

playlist = sp.user_playlist_create(sp.me()['id'], "My Awesome Playlist", public=True)
print(f"Playlist created: {playlist['name']} ({playlist['id']})")
  1. Getting audio features for a track:
track_id = '6rqhFgbbKwnb9MLmUQDhG6'
features = sp.audio_features(track_id)
print(f"Danceability: {features[0]['danceability']}")
print(f"Energy: {features[0]['energy']}")
print(f"Tempo: {features[0]['tempo']}")

Getting Started

  1. Install Spotipy:

    pip install spotipy
    
  2. Set up your Spotify Developer account and create an app to get your client ID and secret.

  3. Set environment variables:

    export SPOTIPY_CLIENT_ID='your-client-id'
    export SPOTIPY_CLIENT_SECRET='your-client-secret'
    export SPOTIPY_REDIRECT_URI='http://localhost:8888/callback'
    
  4. Use Spotipy in your Python script:

    import spotipy
    from spotipy.oauth2 import SpotifyClientCredentials
    
    sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials())
    
    # Now you can use sp to make API calls
    results = sp.search(q='artist:Coldplay', type='track')
    for track in results['tracks']['items']:
        print(track['name'])
    

Competitor Comparisons

5,008

A light weight Python library for the Spotify Web API

Pros of spotipy

  • More actively maintained with frequent updates
  • Larger community and better documentation
  • Supports more Spotify API features

Cons of spotipy

  • Slightly more complex setup process
  • May have more dependencies

Code Comparison

spotipy:

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

client_credentials_manager = SpotifyClientCredentials(client_id, client_secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

results = sp.search(q='artist:' + name, type='artist')
items = results['artists']['items']

spotipy>:

from spotipy import Spotify
from spotipy.oauth2 import SpotifyClientCredentials

spotify = Spotify(auth_manager=SpotifyClientCredentials())

results = spotify.search(q='artist:' + name, type='artist')
items = results['artists']['items']

The code comparison shows that both libraries have similar usage patterns, with spotipy> offering a slightly more concise initialization process. However, the core functionality remains largely the same between the two libraries.

Open Source Spotify client library

Pros of librespot

  • Native Rust implementation, offering better performance and memory safety
  • Supports low-level Spotify protocol, enabling direct streaming without the official client
  • Can be used as a library or standalone player, providing more flexibility

Cons of librespot

  • Steeper learning curve due to Rust language and low-level implementation
  • Limited to core Spotify functionality, lacking some higher-level features
  • Requires more setup and configuration compared to Spotipy

Code Comparison

Spotipy (Python):

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials())
results = sp.search(q='weezer', limit=20)
for idx, track in enumerate(results['tracks']['items']):
    print(idx, track['name'])

librespot (Rust):

use librespot::core::authentication::Credentials;
use librespot::core::config::SessionConfig;
use librespot::core::session::Session;

let session_config = SessionConfig::default();
let credentials = Credentials::with_password("username", "password");
let session = Session::connect(session_config, credentials, None).await?;

While Spotipy provides a high-level Python interface for interacting with Spotify's Web API, librespot offers a low-level Rust implementation for direct communication with Spotify's streaming protocol. Spotipy is easier to use for common tasks, while librespot provides more control and performance at the cost of complexity.

Basic examples to authenticate and fetch data using the Spotify Web API

Pros of web-api-examples

  • Provides a wide range of examples covering various Spotify API endpoints
  • Includes examples in multiple programming languages (JavaScript, Python, Ruby)
  • Offers official, up-to-date examples directly from Spotify

Cons of web-api-examples

  • Lacks a comprehensive library structure for easy integration
  • Requires more manual implementation and error handling
  • May not cover all edge cases or complex scenarios

Code Comparison

web-api-examples (JavaScript):

const getArtist = async (id) => {
  const response = await fetch(`https://api.spotify.com/v1/artists/${id}`, {
    headers: { 'Authorization': 'Bearer ' + access_token }
  });
  return await response.json();
};

spotipy (Python):

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials())

def get_artist(id):
    return sp.artist(id)

The web-api-examples code demonstrates a raw API call, while spotipy provides a more abstracted and simplified approach, handling authentication and request details behind the scenes.

A Node.js wrapper for Spotify's Web API.

Pros of spotify-web-api-node

  • Built specifically for Node.js, offering better integration with Node.js projects
  • More comprehensive documentation and examples
  • Active community and regular updates

Cons of spotify-web-api-node

  • Limited to JavaScript/Node.js environments
  • Slightly more complex setup process compared to Spotipy

Code Comparison

spotify-web-api-node:

const SpotifyWebApi = require('spotify-web-api-node');

const spotifyApi = new SpotifyWebApi({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret'
});

spotifyApi.searchTracks('track name')
  .then(function(data) {
    console.log('Search by "track name"', data.body);
  }, function(err) {
    console.error(err);
  });

Spotipy:

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id="your-client-id", client_secret="your-client-secret"))

results = sp.search(q='track name', type='track')
print(results)

Both libraries provide similar functionality for interacting with the Spotify API. spotify-web-api-node is tailored for Node.js environments, offering more idiomatic JavaScript code and Promise-based operations. Spotipy, on the other hand, provides a more Pythonic approach with simpler setup and usage. The choice between the two largely depends on the programming language and environment of your project.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Spotipy

Spotipy is a lightweight Python library for the Spotify Web API. With Spotipy you get full access to all of the music data provided by the Spotify platform.

Integration tests Documentation Status Discord server

Table of Contents

Features

Spotipy supports all of the features of the Spotify Web API including access to all end points, and support for user authorization. For details on the capabilities you are encouraged to review the Spotify Web API documentation.

Installation

pip install spotipy

alternatively, for Windows users

py -m pip install spotipy

or upgrade

pip install spotipy --upgrade

Quick Start

A full set of examples can be found in the online documentation and in the Spotipy examples directory.

To get started, install spotipy, create a new account or log in on https://developers.spotify.com/. Go to the dashboard, create an app and add your new ID and SECRET (ID and SECRET can be found on an app setting) to your environment (step-by-step video):

Example without user authentication

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id="YOUR_APP_CLIENT_ID",
                                                           client_secret="YOUR_APP_CLIENT_SECRET"))

results = sp.search(q='weezer', limit=20)
for idx, track in enumerate(results['tracks']['items']):
    print(idx, track['name'])

Expected result:

0 Island In The Sun
1 Say It Ain't So
2 Buddy Holly
.
.
.
18 Troublemaker
19 Feels Like Summer

Example with user authentication

A redirect URI must be added to your application at My Dashboard to access user authenticated features.

import spotipy
from spotipy.oauth2 import SpotifyOAuth

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="YOUR_APP_CLIENT_ID",
                                               client_secret="YOUR_APP_CLIENT_SECRET",
                                               redirect_uri="YOUR_APP_REDIRECT_URI",
                                               scope="user-library-read"))

results = sp.current_user_saved_tracks()
for idx, item in enumerate(results['items']):
    track = item['track']
    print(idx, track['artists'][0]['name'], " – ", track['name'])

Expected result will be the list of music that you liked. For example if you liked Red and Sunflower, the result will be:

0 Post Malone  –  Sunflower - Spider-Man: Into the Spider-Verse
1 Taylor Swift  –  Red

Reporting Issues

For common questions please check our FAQ.

You can ask questions about Spotipy on Stack Overflow. Don’t forget to add the Spotipy tag, and any other relevant tags as well, before posting.

If you have suggestions, bugs or other issues specific to this library, file them here. Or just send a pull request.

Contributing

If you are a developer with Python experience, and you would like to contribute to Spotipy, please be sure to follow the guidelines listed on documentation page

Visit the guideline