Skip to content

spotify

Module for interacting with Spotify API. To use this module, you must have a Spotify API key and Spotify API secret.

import spotdl.utils.spotify
spotify.Spotify.init(client_id, client_secret)

Singleton ¤

Bases: type

Singleton metaclass for SpotifyClient. Ensures that SpotifyClient is not instantiated without prior initialization. Every other instantiation of SpotifyClient will return the same instance.

__call__() ¤

Call method for Singleton metaclass.

Returns¤
  • The instance of the SpotifyClient.
Source code in spotdl/utils/spotify.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def __call__(self):  # pylint: disable=bad-mcs-method-argument
    """
    Call method for Singleton metaclass.

    ### Returns
    - The instance of the SpotifyClient.
    """

    if self._instance is None:
        raise SpotifyError(
            "Spotify client not created. Call SpotifyClient.init"
            "(client_id, client_secret, user_auth, cache_path, no_cache, open_browser) first."
        )
    return self._instance

init(client_id, client_secret, user_auth=False, no_cache=False, headless=False, max_retries=3, use_cache_file=False, auth_token=None, cache_path=None) ¤

Initializes the SpotifyClient.

Arguments¤
  • client_id: The client ID of the application.
  • client_secret: The client secret of the application.
  • auth_token: The access token to use.
  • user_auth: Whether or not to use user authentication.
  • cache_path: The path to the cache file.
  • no_cache: Whether or not to use the cache.
  • open_browser: Whether or not to open the browser.
Returns¤
  • The instance of the SpotifyClient.
Source code in spotdl/utils/spotify.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def init(  # pylint: disable=bad-mcs-method-argument
    self,
    client_id: str,
    client_secret: str,
    user_auth: bool = False,
    no_cache: bool = False,
    headless: bool = False,
    max_retries: int = 3,
    use_cache_file: bool = False,
    auth_token: Optional[str] = None,
    cache_path: Optional[str] = None,
) -> "Singleton":
    """
    Initializes the SpotifyClient.

    ### Arguments
    - client_id: The client ID of the application.
    - client_secret: The client secret of the application.
    - auth_token: The access token to use.
    - user_auth: Whether or not to use user authentication.
    - cache_path: The path to the cache file.
    - no_cache: Whether or not to use the cache.
    - open_browser: Whether or not to open the browser.

    ### Returns
    - The instance of the SpotifyClient.
    """

    # check if initialization has been completed, if yes, raise an Exception
    if isinstance(self._instance, self):
        raise SpotifyError("A spotify client has already been initialized")

    credential_manager = None

    cache_handler = (
        CacheFileHandler(cache_path or get_cache_path())
        if not no_cache
        else MemoryCacheHandler()
    )
    # Use SpotifyOAuth as auth manager
    if user_auth:
        credential_manager = SpotifyOAuth(
            client_id=client_id,
            client_secret=client_secret,
            redirect_uri="http://127.0.0.1:9900/",
            scope="user-library-read,user-follow-read,playlist-read-private",
            cache_handler=cache_handler,
            open_browser=not headless,
        )
    # Use SpotifyClientCredentials as auth manager
    else:
        credential_manager = SpotifyClientCredentials(
            client_id=client_id,
            client_secret=client_secret,
            cache_handler=cache_handler,
        )
    if auth_token is not None:
        credential_manager = None

    self.user_auth = user_auth
    self.no_cache = no_cache
    self.max_retries = max_retries
    self.use_cache_file = use_cache_file

    # Create instance
    self._instance = super().__call__(
        auth=auth_token,
        auth_manager=credential_manager,
        status_forcelist=(429, 500, 502, 503, 504, 404),
    )

    # Return instance
    return self._instance

SpotifyClient(*args, **kwargs) ¤

Bases: Spotify

This is the Spotify client meant to be used in the app. Has to be initialized first by calling SpotifyClient.init(client_id, client_secret, user_auth, cache_path, no_cache, open_browser).

Arguments¤
  • auth: The access token to use.
  • auth_manager: The auth manager to use.
Source code in spotdl/utils/spotify.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def __init__(self, *args, **kwargs):
    """
    Initializes the SpotifyClient.

    ### Arguments
    - auth: The access token to use.
    - auth_manager: The auth manager to use.
    """

    super().__init__(*args, **kwargs)
    self._initialized = True

    use_cache_file: bool = self.use_cache_file  # type: ignore # pylint: disable=E1101
    cache_file_loc = get_spotify_cache_path()

    if use_cache_file and cache_file_loc.exists():
        with open(cache_file_loc, "r", encoding="utf-8") as cache_file:
            self.cache = json.load(cache_file)
    elif use_cache_file:
        with open(cache_file_loc, "w", encoding="utf-8") as cache_file:
            json.dump(self.cache, cache_file)

SpotifyError ¤

Bases: Exception

Base class for all exceptions related to SpotifyClient.

save_spotify_cache(cache) ¤

Saves the Spotify cache to a file.

Arguments¤
  • cache: The cache to save.
Source code in spotdl/utils/spotify.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def save_spotify_cache(cache: Dict[str, Optional[Dict]]):
    """
    Saves the Spotify cache to a file.

    ### Arguments
    - cache: The cache to save.
    """

    cache_file_loc = get_spotify_cache_path()

    logger.debug("Saving Spotify cache to %s", cache_file_loc)

    # Only cache tracks
    cache = {
        key: value
        for key, value in cache.items()
        if value is not None and "tracks/" in key
    }

    with open(cache_file_loc, "w", encoding="utf-8") as cache_file:
        json.dump(cache, cache_file)