Spotipy Documentation

repository·master·Indexed 26 days ago

https://github.com/spotipy-dev/spotipy

A lightweight Python library providing a wrapper around the Spotify Web API. Spotipy allows developers to access music data and user-specific features using authentication flows such as SpotifyOAuth and SpotifyClientCredentials. The library supports searching the Spotify catalog, retrieving information for tracks, artists, and albums, managing playlists, and handling paged results and API rate limits.

Tokens
5.4K
Snippets
8
Records
40
Agent score
90%

What's inside Spotipy

  1. Use Authorization Code Flow with SpotifyOAuth

    master

    The Authorization Code flow is suitable for long-running applications where a user logs in once. It provides a refreshable access token.

    Requirements:

    1. Register your app at the Spotify Developer Dashboard to obtain a client id and client secret.
    2. Add a Redirect URI to your application in the Dashboard. The redirect_uri argument or SPOTIPY_REDIRECT_URI environment variable must match this exactly.
    3. If using an http scheme with 127.0.0.1 and a specific port, Spotipy will automatically start a local server to receive the token.

    Environment Variables:

    • SPOTIPY_CLIENT_ID
    • SPOTIPY_CLIENT_SECRET
    • SPOTIPY_REDIRECT_URI
    import spotipy
    from spotipy.oauth2 import SpotifyOAuth
    
    scope = "user-library-read"
    
    # Uses environment variables for credentials by default
    sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
    
    results = sp.current_user_saved_tracks()
    for idx, item in enumerate(results['items']):
        track = item['track']
        print(idx, track['artists'][0]['name'], " – ", track['name'])
  2. Use Client Credentials Flow with SpotifyClientCredentials

    master

    The Client Credentials flow is used for server-to-server authentication. It is suitable for accessing endpoints that do not require user-specific information. It offers a higher rate limit than the Authorization Code flow.

    Note: This flow does not require a SPOTIPY_REDIRECT_URI and will not trigger a browser redirect.

    Environment Variables:

    • SPOTIPY_CLIENT_ID
    • SPOTIPY_CLIENT_SECRET
    import spotipy
    from spotipy.oauth2 import SpotifyClientCredentials
    
    auth_manager = SpotifyClientCredentials()
    sp = spotipy.Spotify(auth_manager=auth_manager)
    
    playlists = sp.user_playlists('spotify')
    while playlists:
        for i, playlist in enumerate(playlists['items']):
            print(f"{i + 1 + playlists['offset']:4d} {playlist['uri']} {playlist['name']}")
        if playlists['next']:
            playlists = sp.next(playlists)
        else:
            playlists = None
  3. Obtain authorization in headless or browserless environments

    master
    If your application is running in an environment where a web browser cannot be opened (e.g., a remote server or CI/CD), set open_browser=False when instantiating SpotifyOAuth or SpotifyPKCE. This will prompt you to manually open the authorization URI provided in the console.
  4. Install Spotipy

    master

    Install the Spotipy library using pip. For Windows users, use the py -m pip command. You can also upgrade an existing installation using the --upgrade flag.

    pip install spotipy
    
    # For Windows users
    py -m pip install spotipy
    
    # To upgrade
    pip install spotipy --upgrade
  5. Install Spotipy via pip

    master

    Ensure you have Python 3 and the pip package manager installed. You can verify your installations with python --version and pip --version. To install or upgrade Spotipy, run the following command in your terminal:

    pip install spotipy --upgrade
  6. Initialize the Spotify client

    master

    Create an instance of the Spotify class to interact with the Spotify Web API. You can provide an access token directly via auth, or use managers for automated authentication (like SpotifyOAuth or SpotifyClientCredentials).

    Key configuration options:

    • auth: An access token string.
    • requests_session: A requests.Session object or a truthy value to enable connection pooling.
    • requests_timeout: Timeout in seconds for requests.
    • retries: Total number of retries allowed.
    • language: ISO-639-1 language code for the Accept-Language header.
  7. Fix '401 Unauthorized' errors

    master

    A spotipy.exceptions.SpotifyException: http status: 401 error typically indicates that the access token is valid but lacks the necessary permissions for the specific endpoint you are calling.

    To resolve this, ensure you have included the required Spotify Scopes in your SpotifyOAuth configuration.

  8. Handle API rate limits and request limits

    master

    If your application stops responding, you may have hit Spotify's rate limits or request limits. Spotipy (via urllib3) uses a built-in backoff-retry strategy that waits for the limit to reset.

    If you prefer to receive an immediate error instead of waiting, set retries=0 when instantiating the Spotify client. This will raise a spotipy.exceptions.SpotifyException.

  9. Troubleshoot Python and Module errors

    master

    Command not found: python

    If you receive zsh: command not found: python, check your version with python --version or python3 --version. If you are using Python 3, try running your script with:

    python3 main.py

    ModuleNotFoundError: No module named 'spotipy'

    If the package is not found, install it using:

    pip install spotipy
  10. Resolve 'Incorrect user' errors

    master

    If you encounter errors like You cannot create a playlist for another user or You cannot remove tracks from a playlist you don't own, you are likely authenticated with the wrong account.

    To fix this:

    1. Verify you are signed in to the correct account at https://spotify.com.
    2. Delete your local cache file: rm .cache-{userid}.
    3. Force a new login dialog by setting show_dialog=True in your SpotifyOAuth configuration.
    4. Verify the identity by calling spotipy.me() and checking the returned user ID.