spotifywebapipython.spotifyclient

@export
class SpotifyClient:

The SpotifyClient uses the Spotify Web API to retrieve information from the Spotify music service.

SpotifyClient( manager: urllib3.poolmanager.PoolManager = None, tokenStorageDir: str = None, tokenUpdater: Callable = None)

Initializes a new instance of the class.

Arguments:
  • manager (urllib3.PoolManager): The manager for HTTP requests to the device.
  • tokenStorageDir (str): The directory path that will contain the tokens.json file.
    A null value will default to the platform specific storage location:
    Example for Windows OS = C:\ProgramData\SpotifyWebApiPython
  • tokenUpdater (Callable): A method to call when a token needs to be refreshed by an external provider.
    The defined method is called with no parameters, and should return a token dictionary.
    Default is null.
SpotifyApiAuthorizeUrl = 'https://accounts.spotify.com/authorize'

Url used to request user authorization permission for an authorization token.

SpotifyApiTokenUrl = 'https://accounts.spotify.com/api/token'

Url used to request or renew a Spotify authorization token.

SpotifyWebApiUrlBase = 'https://api.spotify.com/v1'

Url base name used to access tthe Spotify Web API.

ConfigurationCache: dict

A dictionary of cached configuration objects that have been obtained from the spotify web api. Use the objects in this cache whenever it is too expensive or time consuming to make a real-time request from the spotify web api.

The configuration cache is updated for selected "Get...()" methods that return device information. All of the selected "Get...()" methods have a refresh:bool argument that controls where information is obtained from; if refresh=True, then the spotify web api is queried for real-time configuration information. If refresh=False, then the configuration information is pulled from the configuration cache dictionary; if the cache does not contain the object, then the spotify web api is queried for real-time configuration information.

It is obviously MUCH faster to retrieve configuration objects from the cache than from real-time spotify web api queries. This works very well for configuration objects that do not change very often (e.g. Devices, Categories, Markets, etc). You will still want to make real-time queries for configuration objects that change frequently (e.g. PlayerPlayState, PlayHistory, etc).

This property is read-only, and is set when the class is instantiated. The dictionary entries can be changed, but not the dictionary itself.

Returns:

The _ConfigurationCache property value.

Authorization token used to access the Spotify Web API.

ClientId: str

The unique identifier of the application.

Returns:

The ClientId of the AuthClient instance if set; otherwise, null.

Manager: urllib3.poolmanager.PoolManager

The request PoolManager object to use for http requests to the Spotify Web API.

Returns:

The Manager property value.

TokenProfileId: str

Profile identifier used when loading / storing an authorization token from / to disk.

Returns:

The TokenProfileId of the AuthClient instance if set; otherwise, null.

TokenStorageDir: str

The directory path that will contain the authorization token cache file.

Information about the user from their account profile.

This information is only populated for authorized access types; furthermore, some properties may not be populated if the appropriate scope(s) was not specified when the access token was created. Please refer to the UserProfile model for the properties that require specific scope.

def MakeRequest( self, method: str, msg: spotifywebapipython.spotifyapimessage.SpotifyApiMessage) -> int:

Performs a generic Spotify Web API request.

Arguments:
  • method (str): The preferred HTTP method (e.g. "GET", "POST", etc).
  • msg (SpotifyApiMessage): The api message object that contains input parameters and the output response.
Returns:

The status code (integer) or allowed methods (list).

Raises:
  • SpotifyWebApiError: If an error occurs while requesting content.

A 400 status code is immediately returned for the following scenarios:

  • The method argument is not supplied.
  • The msg argument is not supplied.

Per Spotify Developer Docs, here are the possible status codes:

  • 200 OK - The request has succeeded. The client can read the result of the request in the body and the headers of the response.
  • 201 Created - The request has been fulfilled and resulted in a new resource being created.
  • 202 Accepted - The request has been accepted for processing, but the processing has not been completed.
  • 204 No Content - The request has succeeded but returns no message body.
  • 304 Not Modified. See Conditional requests.
  • 400 Bad Request - The request could not be understood by the server due to malformed syntax. The message body will contain more information; see Response Schema.
  • 401 Unauthorized - The request requires user authentication or, if the request included authorization credentials, authorization has been refused for those credentials.
  • 403 Forbidden - The server understood the request, but is refusing to fulfill it.
  • 404 Not Found - The requested resource could not be found. This error can be due to a temporary or permanent condition.
  • 429 Too Many Requests - Rate limiting has been applied.
  • 500 Internal Server Error. You should never receive this error because our clever coders catch them all ... but if you are unlucky enough to get one, please report it to us through a comment at the bottom of this page.
  • 502 Bad Gateway - The server was acting as a gateway or proxy and received an invalid response from the upstream server.
  • 503 Service Unavailable - The server is currently unable to handle the request due to a temporary condition which will be alleviated after some delay. You can choose to resend the request again.
def AddPlayerQueueItem(self, uri: str, deviceId: str = None) -> None:

Add an item to the end of the user's current playback queue.

This method requires the user-modify-playback-state scope.

Arguments:
  • uri (str): The uri of the item to add to the queue; must be a track or an episode uri.
    Example: spotify:track:4iV5W9uYEdYUVa79Axb7Rh
  • deviceId (str): The id or name of the device this command is targeting.
    If not supplied, the user's currently active device is the target.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

The order of execution is not guaranteed when you use this API with other Player API endpoints.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # add an item to the end of the user's current playback queue.
    trackUri:str = 'spotify:track:27JODWXo4VNa6s7HqDL9yQ'
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    print('\nAdding item to the users current playback queue:\n- "%s" ...' % (trackUri))
    spotify.AddPlayerQueueItem(trackUri, deviceId)

    print('\nSuccess - item was added to the queue')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def AddPlaylistCoverImage(self, playlistId: str, imagePath: str) -> None:

Replace the image used to represent a specific playlist.

This method requires the ugc-image-upload, playlist-modify-public and playlist-modify-private scope.

Arguments:
  • playlistId (str): The Spotify ID of the playlist.
    Example: 5v5ETK9WFXAnGQ3MRubKuE
  • imagePath (str): The fully-qualified path of the image to be uploaded.
    The image must be in JPEG format, and cannot exceed 256KB in Base64 encoded size.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'playlist-modify-private',
        'playlist-modify-public',
        'ugc-image-upload',
        'user-library-modify',
        'user-library-read',
        'user-read-email',
        'user-read-playback-position',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # upload playlist cover image for specified playlist id.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    imagePath:str = './test/testdata/PlaylistCoverImage.jpg'
    print('\nUpdating cover image for playlist id "%s" ...\nFrom path: "%s"' % (playlistId, imagePath))
    spotify.AddPlaylistCoverImage(playlistId, imagePath)

    print('\nSuccess - cover image was uploaded')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def AddPlaylistItems(self, playlistId: str, uris: str = None, position: int = None) -> str:

Add one or more items to a user's playlist.

This method requires the playlist-modify-public and playlist-modify-private scope.

Arguments:
  • playlistId (str): The Spotify ID of the playlist. Example: 5AC9ZXA7nJ7oGWO911FuDG
  • uris (str): A comma-separated list of Spotify URIs to add; can be track or episode URIs.
    Example: spotify:track:4iV5W9uYEdYUVa79Axb7Rh,spotify:episode:512ojhOuo1ktJprKbVcKyQ.
    A maximum of 100 items can be specified in one request. If null, the currently playing context uri value is used.
  • position (int): The position to insert the items, a zero-based index.
    For example, to insert the items in the first position: position=0;
    to insert the items in the third position: position=2.
    If omitted, the items will be appended to the playlist.
    Items are added in the order they are listed in the uris argument.
Returns:

A snapshot ID for the updated playlist.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # add items to end of a playlist.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    itemUris:str = 'spotify:track:2takcwOaAZWiXQijPHIx7B, spotify:track:4eoYKv2kDwJS7gRGh5q6SK'
    print('\nAdding items to end of playlist id "%s" ...\n' % playlistId)
    result:str = spotify.AddPlaylistItems(playlistId, itemUris)

    print('Playlist updated successfully:\n- snapshot ID = "%s"' % result)

    # add items to begining of a playlist.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    itemUris:str = 'spotify:track:1kWUud3vY5ij5r62zxpTRy'
    print('\nAdding items to beginning of playlist id "%s" ...\n' % playlistId)
    result:str = spotify.AddPlaylistItems(playlistId, itemUris, 0)

    print('Playlist updated successfully:\n- snapshot ID = "%s"' % result)

    # add nowplaying item to end of a playlist.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    print('\nAdding nowplaying item to end of playlist id "%s" ...\n' % playlistId)
    result:str = spotify.AddPlaylistItems(playlistId)

    print('Playlist updated successfully:\n- snapshot ID = "%s"' % result)

except Exception as ex:

    print("** Exception: %s" % str(ex))

def ChangePlaylistDetails( self, playlistId: str, name: str = None, description: str = None, public: bool = None, collaborative: bool = None, imagePath: str = None) -> None:

Change a playlist's details (name, description, and public / private state).

This method requires the playlist-modify-public and playlist-modify-private scope.

Arguments:
  • playlistId (str): The Spotify ID of the playlist. Example: 5AC9ZXA7nJ7oGWO911FuDG
  • name (str): The updated name for the playlist, for example "My New Playlist Title" This name does not need to be unique; a user may have several playlists with the same name.
  • description (str): The updated playlist description, as displayed in Spotify Clients and in the Web API.
  • public (bool): If true, the playlist will be public; if false, it will be private.
  • collaborative (bool): If true, the playlist will become collaborative and other users will be able to modify the playlist in their Spotify client.
    Note: You can only set collaborative to true on non-public playlists.
  • imagePath (str): A fully-qualified path of an image to display for the playlist. The image must be in JPEG format, and cannot exceed 256KB in Base64 encoded size.

The user must own the playlist.

The public argument will be set to False if the collaborative argument is True.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Setting the public argument to true will publish the playlist on the user's profile, which means it will appear under public playlists. This will also make the playlist visible in search results. Note that the public argument does not refer to access control, so anyone with the link to the playlist can access it unless it's made private.

A playlist can also be made collaborative by setting the collaborative argument to true. This means that anyone with the link can add to or remove a track from it.

If the imagePath argument is specified, the AddPlaylistCoverImage method is called to upload the image after the playlist details are updated.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # change playlist details.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    print('\nChanging playlist details for id "%s" ...\n' % playlistId)
    spotify.ChangePlaylistDetails(playlistId, 
                                  name='My Updated Playlist Name',
                                  description='This is an updated playlist description with a unicode copyright \u00A9 character in it.',
                                  public=False,
                                  collaborative=True)

    print('\nSuccess - playlist details were updated')

    # change playlist details, and update image.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    imagePath:str = './test/testdata/PlaylistCoverImage.jpg'
    print('\nChanging playlist details for id "%s" ...\n' % playlistId)
    spotify.ChangePlaylistDetails(playlistId, 
                                  name='My Updated Playlist Name',
                                  description='This is an updated playlist description with a unicode copyright \u00A9 character in it.',
                                  public=False,
                                  collaborative=True,
                                  imagePath=imagePath)

    print('\nSuccess - playlist details were updated')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def CheckAlbumFavorites(self, ids: str) -> dict:

Check if one or more albums is already saved in the current Spotify user's 'Your Library'.

This method requires the user-library-read scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the albums.
    Maximum: 20 IDs.
    Example: 6vc9OTcyd3hyzabCmsdnwE,2noRn2Aes5aoNVsU6iWThc
Returns:

A dictionary of the ids, along with a boolean status for each that indicates if the album is saved (True) in the users 'Your Library' or not (False).

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # check if one or more albums is already saved in the current Spotify user's 'Your Library'.
    albumIds:str = '382ObEPsp2rxGrnsizN5TX,6vc9OTcyd3hyzabCmsdnwE,382ObEPsp2rxGrnsizN5TY'
    print('\nChecking if albums are saved by the current user: \n- %s' % albumIds.replace(',','\n- '))
    result:dict = spotify.CheckAlbumFavorites(albumIds)

    print('\nResults:')
    for key in result.keys():
        print('- %s = %s' % (key, result[key]))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def CheckArtistsFollowing(self, ids: str) -> dict:

Check to see if the current user is following one or more artists.

This method requires the user-follow-read scope.

Arguments:
  • ids (str): A comma-separated list of Spotify artist ID's to check.
    Maximum: 50 ID's.
    Example: 2CIMQHirSU0MQqyYHq0eOx,1IQ2e1buppatiN1bxUVkrk
Returns:

A dictionary of the IDs, along with a boolean status for each that indicates if the user follows the ID (True) or not (False).

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-follow-read',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # check to see if the current user is following one or more artists.
    ids:str = '2CIMQHirSU0MQqyYHq0eOx,1IQ2e1buppatiN1bxUVkrk'
    print('\nChecking if these artists are followed by me:\n- %s\n' % (ids.replace(',','\n- ')))
    result:dict = spotify.CheckArtistsFollowing(ids)

    print('Results:')
    for key in result.keys():
        print('- %s = %s' % (key, result[key]))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def CheckAudiobookFavorites(self, ids: str) -> dict:

Check if one or more audiobooks is already saved in the current Spotify user's 'Your Library'.

This method requires the user-library-read scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the audiobooks.
    Maximum: 50 IDs.
    Example: 74aydHJKgYz3AIq3jjBSv1,4nfQ1hBJWjD0Jq9sK3YRW8,3PFyizE2tGCSRLusl2Qizf
Returns:

A dictionary of the ids, along with a boolean status for each that indicates if the audiobook is saved (True) in the users 'Your Library' or not (False).

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # check if one or more audiobooks is already saved in the current Spotify user's 'Your Library'.
    audiobookIds:str = '74aydHJKgYz3AIq3jjBSv1,4nfQ1hBJWjD0Jq9sK3YRW8,3PFyizE2tGCSRLusl2Qizf'
    print('\nChecking if audiobooks are saved by the current user: \n- %s' % audiobookIds.replace(',','\n- '))
    result:dict = spotify.CheckAudiobookFavorites(audiobookIds)

    print('\nResults:')
    for key in result.keys():
        print('- %s = %s' % (key, result[key]))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def CheckEpisodeFavorites(self, ids: str) -> dict:

Check if one or more episodes is already saved in the current Spotify user's 'Your Library'.

This method requires the user-library-read scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the episodes.
    Maximum: 50 IDs.
    Example: 1kWUud3vY5ij5r62zxpTRy,2takcwOaAZWiXQijPHIx7B
Returns:

A dictionary of the ids, along with a boolean status for each that indicates if the episode is saved (True) in the users 'Your Library' or not (False).

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'playlist-modify-private',
        'playlist-modify-public',
        'ugc-image-upload',
        'user-library-modify',
        'user-library-read',
        'user-read-email',
        'user-read-playback-position',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # check if one or more episodes is already saved in the current Spotify user's 'Your Library'.
    episodeIds:str = '1hPX5WJY6ja6yopgVPBqm4,3F97boSWlXi8OzuhWClZHQ'
    print('\nChecking if episodes are saved by the current user: \n- %s' % episodeIds.replace(',','\n- '))
    result:dict = spotify.CheckEpisodeFavorites(episodeIds)

    print('\nResults:')
    for key in result.keys():
        print('- %s = %s' % (key, result[key]))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def CheckPlaylistFollowers(self, playlistId: str, userIds: str) -> dict:

Check to see if one or more Spotify users are following a specified playlist.

Arguments:
  • playlistId (str): The Spotify ID of the playlist.
    Example: 3cEYpjA9oz9GiPac4AsH4n
  • userIds (str): A comma-separated list of Spotify User ID's to check.
    Maximum: 5 ID's.
    Example: 1kWUud3vY5ij5r62zxpTRy,2takcwOaAZWiXQijPHIx7B
Returns:

A dictionary of the userIds, along with a boolean status for each that indicates if the user follows the playlist (True) or not (False).

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # check to see if one or more users are following a specified playlist.
    playlistId:str = '3cEYpjA9oz9GiPac4AsH4n'
    userIds:str = 'jmperezperez,thelinmichael,wizzler'
    print('\nChecking followers of playlist id "%s":\n- %s' % (playlistId, userIds.replace(',','\n- ')))
    result:dict = spotify.CheckPlaylistFollowers(playlistId, userIds)

    print('\nResults:')
    for key in result.keys():
        print('- %s = %s' % (key, result[key]))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def CheckShowFavorites(self, ids: str) -> dict:

Check if one or more shows is already saved in the current Spotify user's 'Your Library'.

This method requires the user-library-read scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the shows.
    Maximum: 50 IDs.
    Example: 1kWUud3vY5ij5r62zxpTRy,2takcwOaAZWiXQijPHIx7B
Returns:

A dictionary of the ids, along with a boolean status for each that indicates if the show is saved (True) in the users 'Your Library' or not (False).

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # check if one or more shows is already saved in the current Spotify user's 'Your Library'.
    showIds:str = '6kAsbP8pxwaU2kPibKTuHE,4rOoJ6Egrf8K2IrywzwOMk,1y3SUbFMUSESC1N43tBleK'
    print('\nChecking if shows are saved by the current user: \n- %s' % showIds.replace(',','\n- '))
    result:dict = spotify.CheckShowFavorites(showIds)

    print('\nResults:')
    for key in result.keys():
        print('- %s = %s' % (key, result[key]))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def CheckTrackFavorites(self, ids: str) -> dict:

Check if one or more tracks is already saved in the current Spotify user's 'Your Library'.

This method requires the user-library-read scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the tracks.
    Maximum: 50 IDs.
    Example: 1kWUud3vY5ij5r62zxpTRy,2takcwOaAZWiXQijPHIx7B
Returns:

A dictionary of the ids, along with a boolean status for each that indicates if the track is saved (True) in the users 'Your Library' or not (False).

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # check if one or more tracks is already saved in the current Spotify user's 'Your Library'.
    trackIds:str = '1kWUud3vY5ij5r62zxpTRy,2takcwOaAZWiXQijPHIx7B,4eoYKv2kDwJS7gRGh5q6SK'
    print('\nChecking if tracks are saved by the current user: \n- %s' % trackIds.replace(',','\n- '))
    result:dict = spotify.CheckTrackFavorites(trackIds)

    print('\nResults:')
    for key in result.keys():
        print('- %s = %s' % (key, result[key]))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def CheckUsersFollowing(self, ids: str) -> dict:

Check to see if the current user is following one or more users.

This method requires the user-follow-read scope.

Arguments:
  • ids (str): A comma-separated list of Spotify user ID's to check.
    Maximum: 50 ID's.
    Example: smedjan
Returns:

A dictionary of the IDs, along with a boolean status for each that indicates if the user follows the ID (True) or not (False).

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-follow-read',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # check to see if the current user is following one or more users.
    ids:str = 'smedjan'
    print('\nChecking if these users are followed by me:\n- %s\n' % (ids.replace(',','\n- ')))
    result:dict = spotify.CheckUsersFollowing(ids)

    print('Results:')
    for key in result.keys():
        print('- %s = %s' % (key, result[key]))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def ClearConfigurationCache(self) -> None:

Removes (clears) all items from the configuration cache.

def ClearPlaylistItems(self, playlistId: str) -> str:

Removes (clears) all items from a user's playlist.

This method requires the playlist-modify-public and playlist-modify-private scope.

Arguments:
  • playlistId (str): The Spotify ID of the playlist. Example: 5AC9ZXA7nJ7oGWO911FuDG
Returns:

A snapshot ID for the updated playlist.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # remove (clear) all items items in a playlist.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    print('\nRemoving all items in playlist id "%s" ...\n' % playlistId)
    result:str = spotify.ClearPlaylistItems(playlistId)

    print('Playlist items cleared successfully:\n- snapshot ID = "%s"' % result)

except Exception as ex:

    print("** Exception: %s" % str(ex))

def CreatePlaylist( self, userId: str, name: str = None, description: str = None, public: bool = True, collaborative: bool = False, imagePath: str = None) -> spotifywebapipython.models.playlist.Playlist:

Create an empty playlist for a Spotify user.

This method requires the playlist-modify-public and playlist-modify-private scope.

Arguments:
  • userId (str): The user's Spotify user ID. Example: 32k99y2kg5lnn3mxhtmd2bpdkjfu
  • name (str): The name for the new playlist, for example "My Playlist".
    This name does not need to be unique; a user may have several playlists with the same name.
  • description (str): The playlist description, as displayed in Spotify Clients and in the Web API.
  • public (bool): If true, the playlist will be public; if false, it will be private.
    To be able to create private playlists, the user must have granted the playlist-modify-private scope.
    Defaults to true.
  • collaborative (bool): If true, the playlist will be collaborative.
    Note: to create a collaborative playlist you must also set public to false. To create collaborative playlists you must have granted playlist-modify-private and playlist-modify-public scope.
    Defaults to false.
  • imagePath (str): A fully-qualified path of an image to display for the playlist. The image must be in JPEG format, and cannot exceed 256KB in Base64 encoded size.

The playlist will be empty until you add tracks.

Setting the public argument to true will publish the playlist on the user's profile, which means it will appear under public playlists. This will also make the playlist visible in search results. Note that the public argument does not refer to access control, so anyone with the link to the playlist can access it unless it's made private.

A playlist can also be made collaborative by setting the collaborative argument to true. This means that anyone with the link can add to or remove a track from it.

Each user is generally limited to a maximum of 11,000 playlists.

If the imagePath argument is specified, the AddPlaylistCoverImage method is called to upload the image after the playlist is created.

Returns:

A Playlist object that contains the playlist details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # create a playlist for the current user.
    userId:str = spotify.UserProfile.Id
    print('\nCreating new (empty) playlist for user "%s" ...\n' % userId)
    playlist:Playlist = spotify.CreatePlaylist(userId, 'My New Playlist 04',"Created from the SpotifyWebApiPython's library - test unicode \u00A9.",False,False)

    print(str(playlist))

    # create a playlist for the current user, and assign an image.
    userId:str = spotify.UserProfile.Id
    imagePath:str = './test/testdata/PlaylistCoverImage.jpg'
    print('\nCreating new (empty) playlist for user "%s" ...\n' % userId)
    playlist:Playlist = spotify.CreatePlaylist(userId, 'My New Playlist 04',"Created from the SpotifyWebApiPython's library - test unicode \u00A9.",False,False,imagePath)

    print(str(playlist))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def FollowArtists(self, ids: str = None) -> None:

Add the current user as a follower of one or more artists.

This method requires the user-follow-modify scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify artist IDs.
    A maximum of 50 IDs can be sent in one request. Example: 2CIMQHirSU0MQqyYHq0eOx,1IQ2e1buppatiN1bxUVkrk If null, the currently playing track artist uri id value is used.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No exception is raised if an artist is already followed.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-follow-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # add the current user as a follower of one or more artists.
    ids:str = '2CIMQHirSU0MQqyYHq0eOx,1IQ2e1buppatiN1bxUVkrk'
    print('\nStart following these artists:\n- %s\n' % (ids.replace(',','\n- ')))
    spotify.FollowArtists(ids)

    print('Success - artists are now followed')

    # add the current user as a follower of the nowplaying artist.
    print('\nStart following the nowplaying artist')
    spotify.FollowArtists()

    print('Success - artists are now followed')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def FollowPlaylist(self, playlistId: str, public: bool = True) -> None:

Add the current user as a follower of a playlist.

This method requires the playlist-modify-public and playlist-modify-private scope.

Arguments:
  • playlistId (str): The Spotify ID of the playlist.
    Example: 3cEYpjA9oz9GiPac4AsH4n
  • public (bool): If true the playlist will be included in user's public playlists, if false it will remain private.
    Default = True.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # add the current user as a follower of a playlist.
    playlistId:str = '3cEYpjA9oz9GiPac4AsH4n'
    print('\nFollowing playlist id "%s" ...' % playlistId)
    spotify.FollowPlaylist(playlistId, False)

    print('\nSuccess - playlist is now followed')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def FollowUsers(self, ids: str) -> None:

Add the current user as a follower of one or more users.

This method requires the user-follow-modify scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify user IDs.
    A maximum of 50 IDs can be sent in one request. Example: smedjan
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No exception is raised if a user is already followed.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-follow-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # add the current user as a follower of one or more users.
    ids:str = 'smedjan'
    print('\nStart following these users:\n- %s\n' % (ids.replace(',','\n- ')))
    spotify.FollowUsers(ids)

    print('Success - users are now followed')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetAlbum( self, albumId: str, market: str = None) -> spotifywebapipython.models.album.Album:

Get Spotify catalog information for a single album.

Arguments:
  • albumId (str): The Spotify ID of the album.
    Example: 6vc9OTcyd3hyzabCmsdnwE
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
Returns:

An Album object that contains the album details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a single album.
    albumId:str = '6vc9OTcyd3hyzabCmsdnwE'
    print('\nGetting details for Album "%s" ...\n' % albumId)
    album:Album = spotify.GetAlbum(albumId)

    print(str(album))

    print('\nArtists:')
    artist:ArtistSimplified
    for artist in album.Artists:
        print('- "{name}" ({uri})'.format(name=artist.Name, uri=artist.Uri))

    print('\nTracks:')
    track:TrackSaved
    for track in album.Tracks.Items:
        print('- "{name}" ({uri})'.format(name=track.Name, uri=track.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetAlbumFavorites( self, limit: int = 20, offset: int = 0, market: str = None, limitTotal: int = None) -> spotifywebapipython.models.albumpagesaved.AlbumPageSaved:

Get a list of the albums saved in the current Spotify user's 'Your Library'.

This method requires the user-library-read scope.

Arguments:
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

An AlbumPageSaved object that contains saved album information.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of the albums saved in the current Spotify user's 'Your Library'.
    print('\nGetting saved albums for current user ...\n')
    pageObj:AlbumPageSaved = spotify.GetAlbumFavorites()

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        print(str(pageObj))
        print('')
        print('Items in this page of results:')

        # display album details.
        albumSaved:AlbumSaved
        for albumSaved in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=albumSaved.Album.Name, uri=albumSaved.Album.Uri))

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetAlbumFavorites(offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a complete list of the albums saved in the current Spotify user's 'Your Library'.
    print('\nGetting ALL saved albums for current user ...\n')
    pageObj:AlbumPageSaved = spotify.GetAlbumFavorites(limitTotal=1000)

    # display results.
    print(str(pageObj))
    print('\nAlbums in this page of results (%d items):' % pageObj.ItemsCount)

    # display album details.
    albumSaved:AlbumSaved
    for albumSaved in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=albumSaved.Album.Name, uri=albumSaved.Album.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetAlbumNewReleases( self, limit: int = 20, offset: int = 0, country: str = None, limitTotal: int = None) -> spotifywebapipython.models.albumpagesimplified.AlbumPageSimplified:

Get a list of new album releases featured in Spotify (shown, for example, on a Spotify player's "Browse" tab).

Arguments:
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • country (str): A country in the form of an ISO 3166-1 alpha-2 country code.
    Provide this parameter if you want the list of returned items to be relevant to a particular country. If omitted, the returned items will be relevant to all countries.
    Example: SE
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

An AlbumPageSimplified object that contains simplified album information.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of new album releases featured in Spotify.
    print('\nGetting list of new album releases featured in Spotify ...\n')
    pageObj:AlbumPageSimplified = spotify.GetAlbumNewReleases()

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Albums in this page of results:')

        # display album details.
        albumSimplified:AlbumSimplified
        for albumSimplified in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=albumSimplified.Name, uri=albumSimplified.Uri))

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetAlbumNewReleases(offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of new album releases featured in Spotify.
    print('\nGetting list of ALL new album releases featured in Spotify ...\n')
    pageObj:AlbumPageSimplified = spotify.GetAlbumNewReleases(limitTotal=1000)

    # display results.
    print(str(pageObj))
    print('\nAlbums in this page of results (%d items):' % pageObj.ItemsCount)

    # display album details.
    albumSimplified:AlbumSimplified
    for albumSimplified in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=albumSimplified.Name, uri=albumSimplified.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetAlbums( self, ids: str, market: str = None) -> list[spotifywebapipython.models.album.Album]:

Get Spotify catalog information for multiple albums.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the albums.
    Maximum: 20 IDs.
    Example: 6vc9OTcyd3hyzabCmsdnwE,2noRn2Aes5aoNVsU6iWThc
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
Returns:

A list of Album objects that contain the album details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a multiple albums.
    albumIds:str = '6vc9OTcyd3hyzabCmsdnwE,382ObEPsp2rxGrnsizN5TX,1A2GTWGtFfWp7KSQTwWOyo,2noRn2Aes5aoNVsU6iWThc'
    print('\nGetting details for multiple albums: \n- %s \n' % albumIds.replace(',','\n- '))
    albums:list[Album] = spotify.GetAlbums(albumIds)

    album:Album
    for album in albums:

        print(str(album))

        print('\nArtist(s):')
        for artist in album.Artists:
            print('- "{name}" ({uri})'.format(name=artist.Name, uri=artist.Uri))

        print('\nTracks:')
        track:TrackSaved
        for track in album.Tracks.Items:
            print('- "{name}" ({uri})'.format(name=track.Name, uri=track.Uri))

        print('')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetAlbumTracks( self, albumId: str, limit: int = 20, offset: int = 0, market: str = None, limitTotal: int = None) -> spotifywebapipython.models.trackpagesimplified.TrackPageSimplified:

Get Spotify catalog information about an album's tracks.

Optional parameters can be used to limit the number of tracks returned.

Arguments:
  • albumId (str): The Spotify ID of the album.
    Example: 6vc9OTcyd3hyzabCmsdnwE
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The index of the first item to return; use with limit to get the next set of items.
    Default: 0 (the first item).
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A TrackPageSimplified object that contains simplified track information for the albumId.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about an album's tracks.
    albumId:str = '6vc9OTcyd3hyzabCmsdnwE'
    print('\nGetting list of tracks for album id "%s" ...\n' % albumId)
    trackPage:TrackPageSimplified = spotify.GetAlbumTracks(albumId) 

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(trackPage))
        print('')
        print('Tracks in this page of results:')

        # display track details.
        trackSimplified:TrackPageSimplified
        for trackSimplified in trackPage.Items:

            print('- "{name}" ({uri})'.format(name=trackSimplified.Name, uri=trackSimplified.Uri))

            # or dump the entire object:
            #print(str(trackSimplified))
            #print('')

        # anymore page results?
        if trackPage.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (trackPage.Limit))
            trackPage = spotify.GetAlbumTracks(albumId, offset=trackPage.Offset + trackPage.Limit, limit=trackPage.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about an album's tracks.
    albumId:str = '6vc9OTcyd3hyzabCmsdnwE'
    print('\nGetting list of ALL tracks for album id "%s" ...\n' % albumId)
    pageObj:TrackPageSimplified = spotify.GetAlbumTracks(albumId, limitTotal=1000) 

    # display paging details.
    print(str(pageObj))
    print('\nTracks in this page of results (%d items):' % pageObj.ItemsCount)

    # display track details.
    trackSimplified:TrackPageSimplified
    for trackSimplified in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=trackSimplified.Name, uri=trackSimplified.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetArtist(self, artistId: str) -> spotifywebapipython.models.artist.Artist:

Get Spotify catalog information for a single artist identified by their unique Spotify ID.

Arguments:
  • artistId (str): The Spotify ID of the artist.
    Example: 6APm8EjxOHSYM5B4i3vT3q
Returns:

An Artist object that contains the artist details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a single artist.
    artistId:str = '6APm8EjxOHSYM5B4i3vT3q'
    print('\nGetting details for Artist "%s" ...\n' % artistId)
    artist:Artist = spotify.GetArtist(artistId)

    print(str(artist))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetArtistAlbums( self, artistId: str, include_groups: str = 'album', limit: int = 20, offset: int = 0, market: str = None, limitTotal: int = None) -> spotifywebapipython.models.albumpagesimplified.AlbumPageSimplified:

Get Spotify catalog information about an artist's albums.

Arguments:
  • artistId (str): The Spotify ID of the artist.
    Example: 6APm8EjxOHSYM5B4i3vT3q
  • include_groups (str): A comma-separated list of keywords that will be used to filter the response.
    If not supplied, all album types will be returned.
    Valid values are: album, single, appears_on, compilation
    Example: single,appears_on
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The index of the first item to return; use with limit to get the next set of items.
    Default: 0 (the first item).
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter. Note: If neither market or user country are provided, the content is considered unavailable for the client. Users can view the country that is associated with their account in the account settings.
    Example: ES
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

An AlbumPageSimplified object of matching results.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about an artist's albums.
    artistId:str = '6APm8EjxOHSYM5B4i3vT3q'
    includeGroups:str = 'album,single,appears_on,compilation'
    print('\nGetting albums for artist id "%s" ...\n' % artistId)
    pageObj:AlbumPageSimplified = spotify.GetArtistAlbums(artistId, includeGroups, limit=50)

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Albums in this page of results:')

        # display album details.
        albumSimplified:AlbumSimplified
        for albumSimplified in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=albumSimplified.Name, uri=albumSimplified.Uri))

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetArtistAlbums(artistId, includeGroups, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about an artist's albums.
    artistId:str = '6APm8EjxOHSYM5B4i3vT3q'
    includeGroups:str = 'album,single,appears_on,compilation'
    print('\nGetting ALL albums for artist id "%s" ...\n' % artistId)
    pageObj:AlbumPageSimplified = spotify.GetArtistAlbums(artistId, includeGroups, limitTotal=1000)

    # display results.
    print(str(pageObj))
    print('\nAlbums in this page of results (%d items):' % pageObj.ItemsCount)

    # display album details.
    albumSimplified:AlbumSimplified
    for albumSimplified in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=albumSimplified.Name, uri=albumSimplified.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetArtistInfo(self, artistId: str) -> spotifywebapipython.models.artistinfo.ArtistInfo:

Get artist about information from the Spotify Artist Biography page for the specified Spotify artist ID.

Arguments:
  • artistId (str): The Spotify ID of the artist.
    Example: 6APm8EjxOHSYM5B4i3vT3q
Returns:

An ArtistInfo object that contains the artist info details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify artist biography page information.
    artistId:str = '6APm8EjxOHSYM5B4i3vT3q'   # MercyMe
    print('\nGetting details for Artist "%s" ...\n' % artistId)
    artistInfo:ArtistInfo = spotify.GetArtistInfo(artistId)
    print(str(artistInfo))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetArtistRelatedArtists(self, artistId: str) -> list[spotifywebapipython.models.artist.Artist]:

Get Spotify catalog information about artists similar to a given artist.
Similarity is based on analysis of the Spotify community's listening history.

Arguments:
  • artistId (str): The Spotify ID of the artist.
    Example: 6APm8EjxOHSYM5B4i3vT3q
Returns:

A list of Artist objects that contain the artist details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about artists similar to a given artist.
    artistId:str = '6APm8EjxOHSYM5B4i3vT3q'
    print('\nGetting artists similar to artist "%s" ...\n' % artistId)
    artists:list[Artist] = spotify.GetArtistRelatedArtists(artistId)

    artist:Artist
    for artist in artists:

        print(str(artist))
        print('')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetArtists(self, ids: list[str]) -> list[spotifywebapipython.models.artist.Artist]:

Get Spotify catalog information for several artists based on their Spotify IDs.

Arguments:
  • ids (list[str]): A comma-separated list of the Spotify IDs for the artists.
    Maximum: 50 IDs.
    Example: 2CIMQHirSU0MQqyYHq0eOx,1vCWHaC5f2uS3yhpwWbIA6
Returns:

A list of Artist objects that contain the artist details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for several artists.
    artistIds:str = '6APm8EjxOHSYM5B4i3vT3q,22sg0OT5BG5eWLBN97WPIZ,1LmsXfZSt1nutb8OCvt00G'
    print('\nGetting details for multiple artists: \n- %s \n' % artistIds.replace(',','\n- '))
    artists:list[Artist] = spotify.GetArtists(artistIds)

    artist:Artist
    for artist in artists:

        print(str(artist))
        print('')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetArtistsFollowed( self, after: str = None, limit: int = 20, limitTotal: int = None) -> spotifywebapipython.models.artistpage.ArtistPage:

Get the current user's followed artists.

Arguments:
  • after (str): The last artist ID retrieved from the previous request, or null for the first request.
    Example: 6APm8EjxOHSYM5B4i3vT3q
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

An ArtistPage object of matching results.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-follow-read',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get the current user's followed artists.
    print('\nGetting current users followed artists ...\n')
    pageObj:ArtistPage = spotify.GetArtistsFollowed()

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Artists in this page of results:')

        # display artist details.
        artist:Artist
        for artist in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=artist.Name, uri=artist.Uri))

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of items ...\n')
            pageObj = spotify.GetArtistsFollowed(after=artist.Id, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-follow-read',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get the current user's followed artists.
    print('\nGetting ALL of the current users followed artists ...\n')
    pageObj:ArtistPage = spotify.GetArtistsFollowed(limitTotal=1000)

    # display results.
    print(str(pageObj))
    print('\nArtists in this page of results (%d items):' % pageObj.ItemsCount)

    # display artist details.
    artist:Artist
    for artist in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=artist.Name, uri=artist.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetArtistTopTracks( self, artistId: str, market: str) -> list[spotifywebapipython.models.track.Track]:

Get Spotify catalog information about an artist's top tracks by country.

Arguments:
  • artistId (str): The Spotify ID of the artist.
    Example: 6APm8EjxOHSYM5B4i3vT3q
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
Returns:

A list of Track objects that contain the track details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about an artist's top tracks by country.
    artistId:str = '6APm8EjxOHSYM5B4i3vT3q'
    print('\nGetting top tracks for artist id "%s" ...\n' % artistId)
    tracks:list[Track] = spotify.GetArtistTopTracks(artistId, 'ES')

    track:Track
    for track in tracks:

        print(str(track))
        print('')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetAudiobook( self, audiobookId: str, market: str = None) -> spotifywebapipython.models.audiobook.Audiobook:

Get Spotify catalog information for a single audiobook.

Audiobooks are only available within the US, UK, Canada, Ireland, New Zealand and Australia markets.

Arguments:
  • audiobookId (str): The Spotify ID for the audiobook. Example: 74aydHJKgYz3AIq3jjBSv1
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
Returns:

A Audiobook object that contain the audiobook details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Important policy notes:

  • Spotify content may not be downloaded.
  • Keep visual content in its original form.
  • Ensure content attribution.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a single audiobook.
    audiobookId:str = '7iHfbu1YPACw6oZPAFJtqe'
    print('\nGetting details for audiobook id "%s" ...\n' % audiobookId)
    audiobook:Audiobook = spotify.GetAudiobook(audiobookId)

    print(str(audiobook))
    print('')

    # prepare to retrieve all chapters.
    pageObj:ChapterPageSimplified = audiobook.Chapters

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Chapters in this page of results:')

        # display chapter details.
        chapterSimplified:ChapterSimplified
        for chapterSimplified in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=chapterSimplified.Name, uri=chapterSimplified.Uri))

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetAudiobookChapters(audiobook.Id, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetAudiobookChapters( self, audiobookId: str, limit: int = 20, offset: int = 0, market: str = None, limitTotal: int = None) -> spotifywebapipython.models.chapterpagesimplified.ChapterPageSimplified:

Get Spotify catalog information about an audiobook's chapters.

Optional parameters can be used to limit the number of chapters returned.

Arguments:
  • audiobookId (str): The Spotify ID for the audiobook. Example: 74aydHJKgYz3AIq3jjBSv1
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The index of the first item to return; use with limit to get the next set of items.
    Default: 0 (the first item).
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A ChapterPageSimplified object that contains simplified track information for the audiobookId.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'playlist-modify-private',
        'playlist-modify-public',
        'ugc-image-upload',
        'user-library-modify',
        'user-library-read',
        'user-read-email',
        'user-read-playback-position',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about a audiobook's chapters.
    audiobookId:str = '7iHfbu1YPACw6oZPAFJtqe'  # <- Dune - Author=Frank Herbert
    print('\nGetting list of chapters for audiobook id "%s" ...\n' % audiobookId)
    pageObj:ChapterPageSimplified = spotify.GetAudiobookChapters(audiobookId) 

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Chapters in this page of results:')

        # display chapter details.
        chapterSimplified:ChapterPageSimplified
        for chapterSimplified in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=chapterSimplified.Name, uri=chapterSimplified.Uri))

            # or dump the entire object:
            #print(str(chapterSimplified))
            #print('')

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetAudiobookChapters(audiobookId, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'playlist-modify-private',
        'playlist-modify-public',
        'ugc-image-upload',
        'user-library-modify',
        'user-library-read',
        'user-read-email',
        'user-read-playback-position',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about a audiobook's chapters.
    audiobookId:str = '7iHfbu1YPACw6oZPAFJtqe'  # <- Dune - Author=Frank Herbert
    print('\nGetting list of ALL chapters for audiobook id "%s" ...\n' % audiobookId)
    pageObj:ChapterPageSimplified = spotify.GetAudiobookChapters(audiobookId, limitTotal=1000) 

    # display paging details.
    print(str(pageObj))
    print('\nChapters in this page of results (%d items):' % pageObj.ItemsCount)

    # display chapter details.
    chapterSimplified:ChapterPageSimplified
    for chapterSimplified in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=chapterSimplified.Name, uri=chapterSimplified.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetAudiobookFavorites( self, limit: int = 20, offset: int = 0, limitTotal: int = None) -> spotifywebapipython.models.audiobookpagesimplified.AudiobookPageSimplified:

Get a list of the audiobooks saved in the current Spotify user's 'Your Library'.

This method requires the user-library-read scope.

Arguments:
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

An AudiobookPageSimplified object that contains saved audiobook information.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of the audiobooks saved in the current Spotify user's 'Your Library'.
    print('\nGetting saved audiobooks for current user ...\n')
    pageObj:AudiobookPageSimplified = spotify.GetAudiobookFavorites()

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Audiobooks in this page of results:')

        # display audiobook details.
        audiobook:AudiobookSimplified
        for audiobook in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=audiobook.Name, uri=audiobook.Uri))

            # use the following to display all object properties.
            #print(str(audiobook))
            #print('')

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetAudiobookFavorites(offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # get a list of the audiobooks saved in the current Spotify user's 'Your Library'.
    print('\nGetting ALL saved audiobooks for current user ...\n')
    pageObj:AudiobookPageSimplified = spotify.GetAudiobookFavorites(limitTotal=1000)

    # display paging details.
    print(str(pageObj))
    print('\nAudiobooks in this page of results (%d items):' % pageObj.ItemsCount)

    # display audiobook details.
    audiobook:AudiobookSimplified
    for audiobook in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=audiobook.Name, uri=audiobook.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetAudiobooks( self, ids: str, market: str = None) -> list[spotifywebapipython.models.audiobooksimplified.AudiobookSimplified]:

Get Spotify catalog information for several audiobooks based on their Spotify IDs.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the audiobooks.
    Maximum: 50 IDs.
    Example: 74aydHJKgYz3AIq3jjBSv1,2kbbNqAvJZxwGyCukHoTLA
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
Returns:

A list of AudiobookSimplified objects that contain the audiobook details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Important policy notes:

  • Spotify content may not be downloaded.
  • Keep visual content in its original form.
  • Ensure content attribution.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a multiple audiobooks.
    audiobookIds:str = '74aydHJKgYz3AIq3jjBSv1,4nfQ1hBJWjD0Jq9sK3YRW8'
    print('\nGetting details for multiple audiobooks: \n- %s \n' % audiobookIds.replace(',','\n- '))
    audiobooks:list[AudiobookSimplified] = spotify.GetAudiobooks(audiobookIds)

    audiobook:AudiobookSimplified
    for audiobook in audiobooks:

        print(str(audiobook))
        print('')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetBrowseCategory( self, categoryId: str, country: str = None, locale: str = None, refresh: bool = True) -> spotifywebapipython.models.playlist.Playlist:

Get a single category used to tag items in Spotify.

Arguments:
  • categoryId (str): The Spotify category ID of the category.
    Note that some category id's are common names (e.g. toplists = Top Lists), while others are unique identifiers (e.g. 0JQ5DAqbMKFDXXwE9BDJAr = Rock).
    Example: toplists
  • country (str): A country: an ISO 3166-1 alpha-2 country code.
    Provide this parameter if you want the list of returned items to be relevant to a particular country. If omitted, the returned items will be relevant to all countries.
    Example: SE
  • locale (str): The desired language, consisting of a lowercase ISO 639-1 language code and an uppercase ISO 3166-1 alpha-2 country code, joined by an underscore.
    For example: es_MX, meaning "Spanish (Mexico)".
    Provide this parameter if you want the results returned in a particular language (where available).
    Note: if locale is not supplied, or if the specified language is not available, all strings will be returned in the Spotify default language (American English). The locale parameter, combined with the country parameter, may give odd results if not carefully matched. For example country=SE and locale=de_DE will return a list of categories relevant to Sweden but as German language strings.
    Example: sv_SE
  • refresh (bool): True (default) to return real-time information from the spotify web api; otherwise, False to to return a cached value IF a call has been made to the GetBrowseCategorys method (which creates a caches list of Category objects).
Returns:

A Category object that contains the category details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

The ConfigurationCache is updated with the results of this method. Use the refresh argument (with False value) to retrieve the cached value and avoid the spotify web api request. This results in better performance.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a single category used to tag items in Spotify.
    categoryId:str = '0JQ5DAqbMKFy0OenPG51Av' # "Christian and Gospel" category id
    print('\nGetting details for category "%s" ...\n' % categoryId)
    category:Category = spotify.GetBrowseCategory(categoryId)

    print(str(category))

    print('\nIcons(s):')
    for icon in category.Icons:
        print(str(icon))

    # get cached configuration, refreshing from device if needed.
    spotify.GetBrowseCategorys()  # load cache
    category:Category = spotify.GetBrowseCategory(categoryId, refresh=False)
    print("\nCached configuration:\n%s" % str(category))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetBrowseCategorys( self, limit: int = 20, offset: int = 0, country: str = None, locale: str = None, limitTotal: int = None) -> spotifywebapipython.models.categorypage.CategoryPage:

Get a page of categories used to tag items in Spotify.

Arguments:
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • country (str): A country: an ISO 3166-1 alpha-2 country code.
    Provide this parameter if you want the list of returned items to be relevant to a particular country. If omitted, the returned items will be relevant to all countries.
    Example: SE
  • locale (str): The desired language, consisting of a lowercase ISO 639-1 language code and an uppercase ISO 3166-1 alpha-2 country code, joined by an underscore.
    For example: es_MX, meaning "Spanish (Mexico)".
    Provide this parameter if you want the results returned in a particular language (where available).
    Note: if locale is not supplied, or if the specified language is not available, all strings will be returned in the Spotify default language (American English). The locale parameter, combined with the country parameter, may give odd results if not carefully matched. For example country=SE and locale=de_DE will return a list of categories relevant to Sweden but as German language strings.
    Example: sv_SE
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A CategoryPage object that contains a page of category details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of categories used to tag items in Spotify.
    print('\nGetting browse categories ...\n')
    pageObj:CategoryPage = spotify.GetBrowseCategorys(limit=50)

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Categories in this page of results:')

        # display category details.
        category:Category
        for category in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=category.Name, uri=category.Id))

            # uncomment to dump Category object:
            #print(str(category))
            #print('')

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetBrowseCategorys(offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of categories used to tag items in Spotify.
    print('\nGetting ALL browse categories ...\n')
    pageObj:CategoryPage = spotify.GetBrowseCategorys(limitTotal=10)

    # display paging details.
    print(str(pageObj))
    print('\nCategories in this page of results (%d items):' % pageObj.ItemsCount)

    # display category details.
    category:Category
    for category in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=category.Name, uri=category.Id))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetBrowseCategorysList( self, country: str = None, locale: str = None, refresh: bool = True) -> list[spotifywebapipython.models.category.Category]:

Get a sorted list of ALL categories used to tag items in Spotify.

Arguments:
  • country (str): A country: an ISO 3166-1 alpha-2 country code.
    Provide this parameter if you want the list of returned items to be relevant to a particular country. If omitted, the returned items will be relevant to all countries.
    Example: SE
  • locale (str): The desired language, consisting of a lowercase ISO 639-1 language code and an uppercase ISO 3166-1 alpha-2 country code, joined by an underscore.
    For example: es_MX, meaning "Spanish (Mexico)".
    Provide this parameter if you want the results returned in a particular language (where available).
    Note: if locale is not supplied, or if the specified language is not available, all strings will be returned in the Spotify default language (American English). The locale parameter, combined with the country parameter, may give odd results if not carefully matched. For example country=SE and locale=de_DE will return a list of categories relevant to Sweden but as German language strings.
    Example: sv_SE
  • refresh (bool): True to return real-time information from the spotify web api and update the cache; otherwise, False to just return the cached value.
Returns:

A list[Category] object that contains the list category details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

The ConfigurationCache is updated with the results of this method. Use the refresh argument (with False value) to retrieve the cached value and avoid the spotify web api request. This results in better performance.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a sorted list of all categories used to tag items in Spotify.
    print('\nGetting list of all browse categories ...')
    categories:list[Category] = spotify.GetBrowseCategorysList()

    # display category details.
    print('\nAll Browse Categories (sorted by name - %d items):' % len(categories))
    category:Category
    for category in categories:
        print('- "{name}" ({uri})'.format(name=category.Name, uri=category.Id))

    # get cached configuration, refreshing from device if needed.
    categories:list[Category] = spotify.GetBrowseCategorysList(refresh=False)
    print("\nCached configuration (count): %d" % len(categories))

    # get cached configuration directly from the configuration manager dictionary.
    if "GetBrowseCategorysList" in spotify.ConfigurationCache:
        categories:list[Category] = spotify.ConfigurationCache["GetBrowseCategorysList"]
        print("\nCached configuration direct access (count): %d" % len(categories))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetCategoryPlaylists( self, categoryId: str, limit: int = 20, offset: int = 0, country: str = None, limitTotal: int = None) -> Tuple[spotifywebapipython.models.playlistpagesimplified.PlaylistPageSimplified, str]:

Get a list of Spotify playlists tagged with a particular category.

Arguments:
  • categoryId (str): The Spotify category ID for the category.
    Example: dinner
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • country (str): A country: an ISO 3166-1 alpha-2 country code.
    Provide this parameter if you want the list of returned items to be relevant to a particular country. If omitted, the returned items will be relevant to all countries.
    Example: SE
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A tuple of 2 objects:

  • PlaylistPageSimplified object that contains playlist information.
  • string that describes what was returned (e.g. 'Popular Playlists').
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

The following are special undocumented category ID's that I have found:

  • 0JQ5DAt0tbjZptfcdMSKl3: Made For You

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of Spotify playlists tagged with a particular category.
    categoryId:str = 'toplists'
    print('\nGetting playlists for category "%s" ...\n' % categoryId)
    pageObj:PlaylistPageSimplified
    pageObj, message = spotify.GetCategoryPlaylists(categoryId)

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print('Playlist Results Type: "%s"\n' % str(message))
        print(str(pageObj))
        print('')
        print('Playlists in this page of results:')

        # display playlist details.
        playlist:PlaylistSimplified
        for playlist in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=playlist.Name, uri=playlist.Uri))

            # use the following to display all object properties.
            #print(str(playlist))
            #print('')

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj, message = spotify.GetCategoryPlaylists(categoryId, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of Spotify playlists tagged with a particular category.
    categoryId:str = 'toplists' # 'pop'
    print('\nGetting ALL playlists for category "%s" ...\n' % categoryId)
    pageObj:PlaylistPageSimplified
    pageObj, message = spotify.GetCategoryPlaylists(categoryId, limitTotal=1000)

    # display results.
    print('Playlist Results Type: "%s"\n' % str(message))
    print(str(pageObj))
    print('\nPlaylists in this page of results (%d items):' % pageObj.ItemsCount)

    # display playlist details.
    playlist:PlaylistSimplified
    for playlist in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=playlist.Name, uri=playlist.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Made For You Playlists

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of Spotify playlists tagged with a particular category.
    categoryId:str = '0JQ5DAt0tbjZptfcdMSKl3' # special hidden category id "Made For You"
    print('\nGetting ALL playlists for category "%s" ...\n' % categoryId)
    pageObj:PlaylistPageSimplified
    pageObj, message = spotify.GetCategoryPlaylists(categoryId, limitTotal=1000)

    # display results.
    print('Playlist Results Type: "%s"\n' % str(message))
    print(str(pageObj))
    print('\nPlaylists in this page of results (%d items):' % pageObj.ItemsCount)

    # display playlist details.
    playlist:PlaylistSimplified
    for playlist in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=playlist.Name, uri=playlist.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetChapter( self, chapterId: str, market: str = None) -> spotifywebapipython.models.chapter.Chapter:

Get Spotify catalog information for a single audiobook chapter identified by its unique Spotify ID.

This method requires the user-read-playback-position scope.

Arguments:
  • chapterId (str): The Spotify ID for the chapter. Example: 0D5wENdkdwbqlrHoaJ9g29
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
Returns:

An Chapter object that contain the chapter details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Important policy notes:

  • Spotify content may not be downloaded.
  • Keep visual content in its original form.
  • Ensure content attribution.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a single chapter.
    chapterId:str = '0D5wENdkdwbqlrHoaJ9g29'
    print('\nGetting details for chapter id "%s" ...\n' % chapterId)
    chapter:Chapter = spotify.GetChapter(chapterId)

    print(str(chapter))
    print('')

    print(str(chapter.Audiobook))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetChapters( self, ids: str, market: str = None) -> list[spotifywebapipython.models.chapter.Chapter]:

Get Spotify catalog information for several chapters based on their Spotify IDs.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the chapters.
    Maximum: 50 IDs.
    Example: 5CfCWKI5pZ28U0uOzXkDHe,5as3aKmN2k11yfDDDSrvaZ
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
Returns:

A list of Chapter objects that contain the chapter details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Important policy notes:

  • Spotify content may not be downloaded.
  • Keep visual content in its original form.
  • Ensure content attribution.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a multiple chapters.
    chapterIds:str = '0D5wENdkdwbqlrHoaJ9g29,0PMQAsGZ8f9tSTd9moghJs'
    print('\nGetting details for multiple chapters: \n- %s \n' % chapterIds.replace(',','\n- '))
    chapters:list[ChapterSimplified] = spotify.GetChapters(chapterIds)

    chapter:ChapterSimplified
    for chapter in chapters:

        print(str(chapter))
        print('')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetEpisode( self, episodeId: str, market: str = None) -> spotifywebapipython.models.episode.Episode:

Get Spotify catalog information for a single episode identified by its unique Spotify ID.

This method requires the user-read-playback-position scope.

Arguments:
  • episodeId (str): The Spotify ID for the episode. Example: 512ojhOuo1ktJprKbVcKyQ
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
Returns:

An Episode object that contain the episode details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Important policy notes:

  • Spotify content may not be downloaded.
  • Keep visual content in its original form.
  • Ensure content attribution.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'playlist-modify-private',
        'playlist-modify-public',
        'ugc-image-upload',
        'user-library-modify',
        'user-library-read',
        'user-read-email',
        'user-read-playback-position',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a single episode.
    episodeId:str = '26c0zVyOv1lzfYpBXdh1zC'
    print('\nGetting details for episode id "%s" ...\n' % episodeId)
    episode:Episode = spotify.GetEpisode(episodeId)

    print(str(episode))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetEpisodeFavorites( self, limit: int = 20, offset: int = 0, limitTotal: int = None) -> spotifywebapipython.models.episodepagesaved.EpisodePageSaved:

Get a list of the episodes saved in the current Spotify user's 'Your Library'.

This method requires the user-library-read scope.

Arguments:
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

An EpisodePageSaved object that contains saved episode information.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'playlist-modify-private',
        'playlist-modify-public',
        'ugc-image-upload',
        'user-library-modify',
        'user-library-read',
        'user-read-email',
        'user-read-playback-position',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of the episodes saved in the current Spotify user's 'Your Library'.
    print('\nGetting saved episodes for current user ...\n')
    pageObj:EpisodePageSaved = spotify.GetEpisodeFavorites()

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Episodes in this page of results:')

        # display episode details.
        episodeSaved:EpisodeSaved
        for episodeSaved in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=episodeSaved.Episode.Name, uri=episodeSaved.Episode.Uri))

            # use the following to display all object properties.
            #print(str(episodeSaved.Episode))
            #print('')

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetEpisodeFavorites(offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'playlist-modify-private',
        'playlist-modify-public',
        'ugc-image-upload',
        'user-library-modify',
        'user-library-read',
        'user-read-email',
        'user-read-playback-position',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of the episodes saved in the current Spotify user's 'Your Library'.
    print('\nGetting ALL saved episodes for current user ...\n')
    pageObj:EpisodePageSaved = spotify.GetEpisodeFavorites(limitTotal=1000)

    # display paging details.
    print(str(pageObj))
    print('\nEpisodes in this page of results (%d items):' % pageObj.ItemsCount)

    # display episode details.
    episodeSaved:EpisodeSaved
    for episodeSaved in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=episodeSaved.Episode.Name, uri=episodeSaved.Episode.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetEpisodes( self, ids: str, market: str = None) -> list[spotifywebapipython.models.episode.Episode]:

Get Spotify catalog information for several episodes based on their Spotify IDs.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the episodes.
    Maximum: 50 IDs.
    Example: 5CfCWKI5pZ28U0uOzXkDHe,5as3aKmN2k11yfDDDSrvaZ
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
Returns:

A list of Episode objects that contain the episode details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Important policy notes:

  • Spotify content may not be downloaded.
  • Keep visual content in its original form.
  • Ensure content attribution.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'playlist-modify-private',
        'playlist-modify-public',
        'ugc-image-upload',
        'user-library-modify',
        'user-library-read',
        'user-read-email',
        'user-read-playback-position',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a multiple episodes.
    episodeIds:str = '16OUc3NwQe7kJNaH8zmzfP,1hPX5WJY6ja6yopgVPBqm4,3F97boSWlXi8OzuhWClZHQ'
    print('\nGetting details for multiple episodes: \n- %s \n' % episodeIds.replace(',','\n- '))
    episodes:list[Episode] = spotify.GetEpisodes(episodeIds)

    episode:Episode
    for episode in episodes:

        print(str(episode))
        print('')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetFeaturedPlaylists( self, limit: int = 20, offset: int = 0, country: str = None, locale: str = None, timestamp: str = None, limitTotal: int = None) -> Tuple[spotifywebapipython.models.playlistpagesimplified.PlaylistPageSimplified, str]:

Get a list of Spotify featured playlists (shown, for example, on a Spotify player's 'Browse' tab).

Arguments:
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • country (str): A country: an ISO 3166-1 alpha-2 country code.
    Provide this parameter if you want the list of returned items to be relevant to a particular country. If omitted, the returned items will be relevant to all countries.
    Example: SE
  • locale (str): The desired language, consisting of a lowercase ISO 639-1 language code and an uppercase ISO 3166-1 alpha-2 country code, joined by an underscore.
    For example: es_MX, meaning "Spanish (Mexico)".
    Provide this parameter if you want the results returned in a particular language (where available).
    Note: if locale is not supplied, or if the specified language is not available, all strings will be returned in the Spotify default language (American English). The locale parameter, combined with the country parameter, may give odd results if not carefully matched. For example country=SE and locale=de_DE will return a list of categories relevant to Sweden but as German language strings.
    Example: sv_SE
  • timestamp (str): A timestamp in ISO 8601 format: yyyy-MM-ddTHH:mm:ss.
    Use this parameter to specify the user's local time to get results tailored for that specific date and time in the day. If not provided, the response defaults to the current UTC time. Example: 2023-10-23T09:00:00 for a user whose local time is 9AM. If there were no featured playlists (or there is no data) at the specified time, the response will revert to the current UTC time. Example: 2023-10-23T09:00:00
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A tuple of 2 objects:

  • PlaylistPageSimplified object that contains playlist information.
  • string that describes what was returned (e.g. 'Popular Playlists').
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of Spotify featured playlists.
    print('\nGetting Spotify featured playlists ...\n')
    pageObj:PlaylistPageSimplified
    pageObj, message = spotify.GetFeaturedPlaylists()

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(message))
        print(str(pageObj))
        print('')
        print('Playlists in this page of results:')

        # display playlist details.
        playlist:PlaylistSimplified
        for playlist in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=playlist.Name, uri=playlist.Uri))

            # use the following to display all object properties.
            #print(str(playlist))
            #print('')

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj, message = spotify.GetFeaturedPlaylists(offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of Spotify featured playlists.
    print('\nGetting ALL Spotify featured playlists ...\n')
    pageObj:PlaylistPageSimplified
    pageObj, message = spotify.GetFeaturedPlaylists(limitTotal=1000)

    # display paging details.
    print('Playlist Results Type: "%s"\n' % str(message))
    print(str(pageObj))
    print('\nPlaylists in this page of results (%d items):' % pageObj.ItemsCount)

    # display playlist details.
    playlist:PlaylistSimplified
    for playlist in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=playlist.Name, uri=playlist.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetGenres(self, refresh: bool = True) -> list[str]:

Get a sorted list of available genres seed parameter values.

Arguments:
  • refresh (bool): True to return real-time information from the spotify web api and update the cache; otherwise, False to just return the cached value.
Returns:

A sorted list of genre strings.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

The ConfigurationCache is updated with the results of this method. Use the refresh argument (with False value) to retrieve the cached value and avoid the spotify web api request. This results in better performance.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of available genre seed parameter values for recommendations.
    print('\nGetting list of genres ...')
    genres:list[str] = spotify.GetGenres()

    # display genre details.
    print('\nAll Genres (sorted by name):')
    genre:str
    for genre in genres:

        print('- "{name}"'.format(name=genre))

    # get cached configuration, refreshing from device if needed.
    genres:list[str] = spotify.GetGenres(refresh=False)
    print("\nCached configuration (count): %d" % len(genres))

    # get cached configuration directly from the configuration manager dictionary.
    if "GetGenres" in spotify.ConfigurationCache:
        genres:list[str] = spotify.ConfigurationCache["GetGenres"]
        print("\nCached configuration direct access (count): %d" % len(genres))

except Exception as ex:

    print("** Exception: %s" % str(ex))

@staticmethod
def GetIdFromUri(uri: str) -> str:

Get the id portion from a Spotify uri value.

Arguments:
  • uri (str): The Spotify URI value. Example: spotify:track:5v5ETK9WFXAnGQ3MRubKuE
Returns:

A string containing the id value.

No exceptions are raised with this method.

def GetMarkets(self, refresh: bool = True) -> list[str]:

Get the list of markets (country codes) where Spotify is available.

Arguments:
  • refresh (bool): True to return real-time information from the spotify web api and update the cache; otherwise, False to just return the cached value.
Returns:

A sorted list of market identifier strings.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

The ConfigurationCache is updated with the results of this method. Use the refresh argument (with False value) to retrieve the cached value and avoid the spotify web api request. This results in better performance.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get the list of markets where Spotify is available.
    print('\nGetting list of markets ...')
    markets:list[str] = spotify.GetMarkets()

    # display genre details.
    print('\nAll Markets (sorted by id):')
    market:str
    for market in markets:

        print('- "{name}"'.format(name=market))

    # get cached configuration, refreshing from device if needed.
    markets:list[str] = spotify.GetMarkets(refresh=False)
    print("\nCached configuration (count): %d" % len(markets))

    # get cached configuration directly from the configuration manager dictionary.
    if "GetMarkets" in spotify.ConfigurationCache:
        markets:list[str] = spotify.ConfigurationCache["GetMarkets"]
        print("\nCached configuration direct access (count): %d" % len(markets))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetPlayerDevice( self, deviceId: str, refresh: bool = True) -> spotifywebapipython.models.device.Device:

Get information about a user's available Spotify Connect player device.

This method requires the user-read-playback-state scope.

Arguments:
  • deviceId (str): The device id or name to retrieve.
  • refresh (bool): True (default) to resolve the device real-time from the spotify web api device list; otherwise, False to use the cached device list to resolve the device.
Returns:

A Device object if found; otherwise, null.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

The ConfigurationCache is updated with the results of this method. Use the refresh argument (with False value) to retrieve the cached value and avoid the spotify web api request. This results in better performance.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-playback-state', 
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify Connect player device by it's Id value.
    deviceId:str = '30fbc80e35598f3c242f2120413c943dfd9715fe'
    print('\nGetting Spotify Connect player device: \n- ID = "%s" ...\n' % deviceId)
    device:Device = spotify.GetPlayerDevice(deviceId)

    if device is not None:
        print(str(device))
    else:
        print("Device Id was not found in the list of devices")

    # get Spotify Connect player device by it's Name value.
    deviceName:str = 'Bose-ST10-1'
    print('\nGetting Spotify Connect player device: \n- Name = "%s" ...\n' % deviceName)
    device:Device = spotify.GetPlayerDevice(deviceName)

    if device is not None:
        print(str(device))
    else:
        print("Device Name was not found in the list of devices")

    # get cached configuration, refreshing from device if needed.
    device:Device = spotify.GetPlayerDevice(deviceId, refresh=False)
    print("\nCached configuration (by Id):\n%s" % str(device))

    # get cached configuration, refreshing from device if needed.
    device:Device = spotify.GetPlayerDevice(deviceName, refresh=False)
    print("\nCached configuration (by Name):\n%s" % str(device))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerConvertDeviceNameToId(self, value: str, refresh: bool = False) -> str:

Converts a Spotify Connect player device name to it's equivalent id value if the value is a device name. If the value is a device id, then the value is returned as-is.

This method requires the user-read-playback-state scope.

Arguments:
  • value (str): The device id or name value to check.
  • refresh (bool): True to resolve the device real-time from the spotify web api device list; otherwise, False (default) to use the cached device list to resolve the device.
Returns:

One of the following:

  • if value is a device id, then the value is returned as-is; no device list lookup is performed, and the value is assumed to be a valid device id.
  • if value is not a device id, then it is assumed to be a name; a device list lookup is performed to retrieve it's device id. if found, then the id is returned; otherwise, the value is returned as-is with the understanding that subsequent operations will fail since it's not in the device list.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

The id for the first match found on the device name will be returned if multiple devices are found in the Spotify Connect player device list that have the same name (with different id's). Care should be taken to make device names unique if using device names for methods that require a device id or name.

If the refresh argument is specified, then the ConfigurationCache is updated with the latest Spotify Connect player device list. Use the refresh argument (with False value) to retrieve the cached value and avoid the spotify web api request. This results in better performance.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-read-playback-state'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get device id for specified device name.
    deviceName:str = 'Web Player (Chrome)'
    print('\nGetting Spotify Connect Player device id for name:\n- Name: %s ...' % (deviceName))
    deviceId:str = spotify.PlayerConvertDeviceNameToId(deviceName, True)
    print('- ID:   %s' % (deviceId))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetPlayerDevices( self, refresh: bool = True) -> list[spotifywebapipython.models.device.Device]:

Get information about a user's available Spotify Connect player devices.

Some device models are not supported and will not be listed in the API response.

This method requires the user-read-playback-state scope.

Arguments:
  • refresh (bool): True (default) to return real-time information from the spotify web api and update the cache; otherwise, False to just return the cached value.
Returns:

A list of Device objects that contain the device details, sorted by name.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

The ConfigurationCache is updated with the results of this method. Use the refresh argument (with False value) to retrieve the cached value and avoid the spotify web api request. This results in better performance.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-playback-state', 
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get information about a user's available Spotify Connect player devices.
    print('\nGetting available Spotify Connect player devices ...')
    devices:list[Device] = spotify.GetPlayerDevices()

    device:Device
    for device in devices:

        print(str(device))
        print('')

    # get cached configuration, refreshing from device if needed.
    devices:list[Device] = spotify.GetPlayerDevices(refresh=False)
    print("\nCached configuration (count): %d" % len(devices))

    # get cached configuration directly from the configuration manager dictionary.
    if "GetPlayerDevices" in spotify.ConfigurationCache:
        devices:list[Device] = spotify.ConfigurationCache["GetPlayerDevices"]
        print("\nCached configuration direct access (count): %d" % len(devices))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetPlayerNowPlaying( self, market: str = None, additionalTypes: str = None) -> spotifywebapipython.models.playerplaystate.PlayerPlayState:

Get the object currently being played on the user's Spotify account.

This method requires the user-read-currently-playing scope.

Arguments:
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • additionalTypes (str): A comma-separated list of item types that your client supports besides the default track type.
    Valid types are: track and episode.
    Specify episode to get podcast track information.
    Note: This parameter was introduced to allow existing clients to maintain their current behaviour and might be deprecated in the future. In addition to providing this parameter, make sure that your client properly handles cases of new types in the future by checking against the type field of each object.
Returns:

A PlayerPlayState object that contains player state details as well as currently playing content.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-currently-playing', 
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get the object currently being played on the user's Spotify account.
    print('\nGetting object that is now playing on the users account ...\n')
    nowPlaying:PlayerPlayState = spotify.GetPlayerNowPlaying()

    if nowPlaying.CurrentlyPlayingType is not None:

        print(str(nowPlaying))
        print('')
        print(str(nowPlaying.Item))

    else:

        print('Nothing is currently playing via Spotify Connect')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetPlayerPlaybackState( self, market: str = None, additionalTypes: str = None) -> spotifywebapipython.models.playerplaystate.PlayerPlayState:

Get information about the user's current playback state, including track or episode, progress, and active device.

This method requires the user-read-playback-state scope.

Arguments:
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • additionalTypes (str): A comma-separated list of item types that your client supports besides the default track type.
    Valid types are: track and episode.
    Specify episode to get podcast track information.
    Note: This parameter was introduced to allow existing clients to maintain their current behaviour and might be deprecated in the future. In addition to providing this parameter, make sure that your client properly handles cases of new types in the future by checking against the type field of each object.
Returns:

A PlayerPlayState object that contains player state details as well as currently playing content.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify Connect playback state.
    print('\nGetting Spotify Connect playback state ...\n')
    playerState:PlayerPlayState = spotify.GetPlayerPlaybackState()

    if playerState.CurrentlyPlayingType is not None:

        print(str(playerState))
        print('')
        print(str(playerState.Item))

    else:

        print('Spotify Connect playback State is unavailable at this time')

except Exception as ex:

    print("** Exception: %s" % str(ex))

Get the list of objects that make up the user's playback queue.

This method requires the user-read-currently-playing and user-read-playback-state scope.

Returns:

A PlayerQueueInfo object that contains the player queue information.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-currently-playing',
        'user-read-email',
        'user-read-playback-state',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify Connect player queue info for the current user.
    print('\nGetting Spotify Connect player queue info ...\n')
    queueInfo:PlayerQueueInfo = spotify.GetPlayerQueueInfo()

    print(str(queueInfo))

    if queueInfo.CurrentlyPlaying is not None:
        print('\nCurrently Playing:\n%s' % queueInfo.CurrentlyPlaying)

    print('\nQueue: (%s items)' % queueInfo.QueueCount)
    for item in queueInfo.Queue:
        print('- {type}: "{name}" ({uri})'.format(type=item.Type, name=item.Name, uri=item.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetPlayerRecentTracks( self, limit: int = 50, after: int = None, before: int = None, limitTotal: int = None) -> spotifywebapipython.models.playhistorypage.PlayHistoryPage:

Get tracks from the current user's recently played tracks.
Note: Currently doesn't support podcast episodes.

This method requires the user-read-recently-played scope.

Arguments:
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • after (int): Returns all items after (but not including) this cursor position, which is a Unix timestamp in milliseconds.
    If after is specified, before must not be specified.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • before (int): Returns all items before (but not including) this cursor position, which is a Unix timestamp in milliseconds.
    If before is specified, after must not be specified.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)

Spotify currently limits the maximum number of items returned to 50 no matter what you supply for the limitTotal argument.

The after and before arguments are based upon local time (not UTC time). Recently played item history uses a local timestamp, and NOT a UTC timestamp.

If both after and before arguments are null (or zero), then a before value is generated that will retrieve the last 50 recently played tracks.

Returns:

A PlayHistoryPage object that contains the recently played items.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - After DateTime

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-recently-played',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get all tracks played after UTC date 2024-01-25T21:34:16.821Z (1706218456821)
    afterMS:int = 1706218456821

    # get tracks from current user's recently played tracks.
    print('\nGetting recently played tracks for current user ...\n')
    pageObj:PlayHistoryPage = spotify.GetPlayerRecentTracks(after=afterMS)

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Tracks in this page of results:')

        # display history details.
        history:PlayHistory
        for history in pageObj.Items:

            print('- {played_at} {played_atMS}: "{name}" ({uri})'.format(played_at=history.PlayedAt, played_atMS=history.PlayedAtMS, name=history.Track.Name, uri=history.Track.Uri))

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of items ...\n')
            pageObj = spotify.GetPlayerRecentTracks(after=pageObj.CursorAfter, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - For Past 1 Hour

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-recently-played',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get all tracks played within the past 1 hour.
    afterMS:int = GetUnixTimestampMSFromUtcNow(hours=-1)     # last 1 hour
    #afterMS:int = GetUnixTimestampMSFromUtcNow(hours=-24)   # last 24 hours
    #afterMS:int = GetUnixTimestampMSFromUtcNow(days=-7)     # last 7 days

    # get tracks from current user's recently played tracks.
    print('\nGetting recently played tracks for current user ...\n')
    pageObj:PlayHistoryPage = spotify.GetPlayerRecentTracks(after=afterMS)

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Tracks in this page of results:')

        # display history details.
        history:PlayHistory
        for history in pageObj.Items:

            print('- {played_at} {played_atMS}: "{name}" ({uri})'.format(played_at=history.PlayedAt, played_atMS=history.PlayedAtMS, name=history.Track.Name, uri=history.Track.Uri))

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of items ...\n')
            pageObj = spotify.GetPlayerRecentTracks(after=pageObj.CursorAfter, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetPlaylist( self, playlistId: str, market: str = None, fields: str = None, additionalTypes: str = None) -> spotifywebapipython.models.playlist.Playlist:

Get a playlist owned by a Spotify user.

Arguments:
  • playlistId (str): The Spotify ID of the playlist.
    Example: 5v5ETK9WFXAnGQ3MRubKuE
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • fields (str): Filters for the query: a comma-separated list of the fields to return.
    If omitted, all fields are returned. For example, to get just the playlist's description and URI:
    fields=description,uri. A dot separator can be used to specify non-reoccurring fields, while parentheses can be used to specify reoccurring fields within objects. For example, to get just the added date and user ID of the adder:
    fields=tracks.items(added_at,added_by.id).
    Use multiple parentheses to drill down into nested objects, for example:
    fields=tracks.items(track(name,href,album(name,href))).
    Fields can be excluded by prefixing them with an exclamation mark, for example:
    fields=tracks.items(track(name,href,album(!name,href)))
    Example: fields=items(added_by.id,track(name,href,album(name,href)))
  • additionalTypes (str): A comma-separated list of item types that your client supports besides the default track type.
    Valid types are: track and episode.
    Note: This parameter was introduced to allow existing clients to maintain their current behaviour and might be deprecated in the future. In addition to providing this parameter, make sure that your client properly handles cases of new types in the future by checking against the type field of each object.
Returns:

A Playlist object that contains the playlist details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a playlist owned by a Spotify user.
    playlistId:str = '5v5ETK9WFXAnGQ3MRubKuE'
    print('\nGetting details for playlist "%s" ...\n' % playlistId)
    playlist:Playlist = spotify.GetPlaylist(playlistId)

    print(str(playlist))
    print('')

    print(str(playlist.Tracks))

    print('\nTracks:')
    playlistTrack:PlaylistTrack
    for playlistTrack in playlist.Tracks.Items:
        print('- "{name}" ({uri})'.format(name=playlistTrack.Track.Name, uri=playlistTrack.Track.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetPlaylistCoverImage( self, playlistId: str) -> spotifywebapipython.models.imageobject.ImageObject:

Get the current image associated with a specific playlist.

Arguments:
  • playlistId (str): The Spotify ID of the playlist.
    Example: 5v5ETK9WFXAnGQ3MRubKuE
Returns:

A ImageObject object that contains the image details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get the current image details associated with a specific playlist.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    print('\nGetting cover image details for playlist id "%s" ...\n' % playlistId)
    imageObj:ImageObject = spotify.GetPlaylistCoverImage(playlistId)

    print(str(imageObj))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetPlaylistItems( self, playlistId: str, limit: int = 50, offset: int = 0, market: str = None, fields: str = None, additionalTypes: str = None, limitTotal: int = None) -> spotifywebapipython.models.playlistpage.PlaylistPage:

Get full details of the items of a playlist owned by a Spotify user.

This method requires the playlist-read-private scope.

Arguments:
  • playlistId (str): The Spotify ID of the playlist.
    Example: 5v5ETK9WFXAnGQ3MRubKuE
  • limit (int): The maximum number of items to return in a page of items.
    Default: 50, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • fields (str): Filters for the query: a comma-separated list of the fields to return.
    If omitted, all fields are returned. For example, to get just the playlist's description and URI:
    fields=description,uri. A dot separator can be used to specify non-reoccurring fields, while parentheses can be used to specify reoccurring fields within objects. For example, to get just the added date and user ID of the adder:
    fields=tracks.items(added_at,added_by.id).
    Use multiple parentheses to drill down into nested objects, for example:
    fields=tracks.items(track(name,href,album(name,href))).
    Fields can be excluded by prefixing them with an exclamation mark, for example:
    fields=tracks.items(track(name,href,album(!name,href)))
    Example: fields=items(added_by.id,track(name,href,album(name,href)))
  • additionalTypes (str): A comma-separated list of item types that your client supports besides the default track type.
    Valid types are: track and episode.
    Note: This parameter was introduced to allow existing clients to maintain their current behaviour and might be deprecated in the future. In addition to providing this parameter, make sure that your client properly handles cases of new types in the future by checking against the type field of each object.
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A Playlist object that contains the playlist details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get full details of the items of a playlist owned by a Spotify user.
    playlistId:str = '5v5ETK9WFXAnGQ3MRubKuE'
    print('\nGetting item details for playlist "%s" ...\n' % playlistId)
    pageObj:PlaylistPage = spotify.GetPlaylistItems(playlistId)

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Tracks in this page of results:')

        # display track details.
        playlistTrack:PlaylistTrack
        for playlistTrack in pageObj.Items:

            print('- "{name}" ({uri}), added on {added} '.format(name=playlistTrack.Track.Name, uri=playlistTrack.Track.Uri, added=playlistTrack.AddedAt))

            # uncomment to dump PlaylistTrack and Track objects:
            # print(str(playlistTrack))
            # print('')

            # print(str(playlistTrack.Track))

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetPlaylistItems(playlistId, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get full details of the items of a playlist owned by a Spotify user.
    playlistId:str = '5v5ETK9WFXAnGQ3MRubKuE'
    print('\nGetting ALL item details for playlist "%s" ...\n' % playlistId)
    pageObj:PlaylistPage = spotify.GetPlaylistItems(playlistId, limitTotal=1000)

    # display paging details.
    print(str(pageObj))
    print('\nTrack Item results: (%d items)' % pageObj.ItemsCount)

    # display track details.
    playlistTrack:PlaylistTrack
    for playlistTrack in pageObj.Items:
        print('- "{name}" ({uri}), added on {added} '.format(name=playlistTrack.Track.Name, uri=playlistTrack.Track.Uri, added=playlistTrack.AddedAt))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetPlaylistFavorites( self, limit: int = 20, offset: int = 0, limitTotal: int = None) -> spotifywebapipython.models.playlistpagesimplified.PlaylistPageSimplified:

Get a list of the playlists owned or followed by the current Spotify user.

This method requires the playlist-read-private scope.

Arguments:
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

An PlaylistPageSimplified object that contains playlist information.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of the playlists owned or followed by the current Spotify user.
    print('\nGetting playlists for current user ...\n')
    pageObj:PlaylistPageSimplified = spotify.GetPlaylistFavorites()

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')

        # display playlist details.
        playlist:PlaylistSimplified
        for playlist in pageObj.Items:

            print(str(playlist))
            print('')

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('Getting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetPlaylistFavorites(offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of the playlists owned or followed by the current Spotify user.
    print('\nGetting ALL playlists for current user ...\n')
    pageObj:PlaylistPageSimplified = spotify.GetPlaylistFavorites(limitTotal=1000)

    # display paging details.
    print(str(pageObj))
    print('\nPlaylists in this page of results (%d items):' % pageObj.ItemsCount)

    # display playlist details.
    playlist:PlaylistSimplified
    for playlist in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=playlist.Name, uri=playlist.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetPlaylistsForUser( self, userId: str, limit: int = 20, offset: int = 0, limitTotal: int = None) -> spotifywebapipython.models.playlistpagesimplified.PlaylistPageSimplified:

Get a list of the playlists owned or followed by a Spotify user.

This method requires the playlist-read-private and playlist-read-collaborative scope.

Arguments:
  • userId (str): The user's Spotify user ID.
    Example: smedjan
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

An PlaylistPageSimplified object that contains playlist information.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of the playlists owned or followed by a Spotify user.
    userId:str = 'smedjan'
    print('\nGetting playlists for user "%s" ...\n' % userId)
    pageObj:PlaylistPageSimplified = spotify.GetPlaylistsForUser(userId)

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')

        # display playlist details.
        playlist:PlaylistSimplified
        for playlist in pageObj.Items:

            print(str(playlist))
            print('')

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('Getting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetPlaylistsForUser(userId, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of the playlists owned or followed by a Spotify user.
    userId:str = 'smedjan'
    print('\nGetting ALL playlists for user "%s" ...\n' % userId)
    pageObj:PlaylistPageSimplified = spotify.GetPlaylistsForUser(userId, limitTotal=1000)

    # display paging details.
    print(str(pageObj))
    print('\nPlaylists in this page of results (%d items):' % pageObj.ItemsCount)

    # display playlist details.
    playlist:PlaylistSimplified
    for playlist in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=playlist.Name, uri=playlist.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetShow( self, showId: str, market: str = None) -> spotifywebapipython.models.show.Show:

Get Spotify catalog information for a single show identified by its unique Spotify ID.

Arguments:
  • showId (str): The Spotify ID for the show. Example: 5CfCWKI5pZ28U0uOzXkDHe
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
Returns:

A Show object that contain the show details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Important policy notes:

  • Spotify content may not be downloaded.
  • Keep visual content in its original form.
  • Ensure content attribution.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a single show.
    showId:str = '6E1u3kxII5CbbFR4VObax4'
    print('\nGetting details for show id "%s" ...\n' % showId)
    show:Show = spotify.GetShow(showId)

    print(str(show))
    print('')

    # prepare to retrieve all episodes.
    pageObj:EpisodePageSimplified = show.Episodes

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Episodes in this page of results:')

        # display episode details.
        episodeSimplified:EpisodeSimplified
        for episodeSimplified in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=episodeSimplified.Name, uri=episodeSimplified.Uri))

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetShowEpisodes(show.Id, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetShowEpisodes( self, showId: str, limit: int = 20, offset: int = 0, market: str = None, limitTotal: int = None) -> spotifywebapipython.models.episodepagesimplified.EpisodePageSimplified:

Get Spotify catalog information about a show's episodes.

Optional parameters can be used to limit the number of episodes returned.

Arguments:
  • showId (str): The Spotify ID for the show. Example: 6kAsbP8pxwaU2kPibKTuHE
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The index of the first item to return; use with limit to get the next set of items.
    Default: 0 (the first item).
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A EpisodePageSimplified object that contains simplified track information for the showId.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'playlist-modify-private',
        'playlist-modify-public',
        'ugc-image-upload',
        'user-library-modify',
        'user-library-read',
        'user-read-email',
        'user-read-playback-position',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about a show's episodes.
    showId:str = '6E1u3kxII5CbbFR4VObax4'
    print('\nGetting list of episodes for show id "%s" ...\n' % showId)
    pageObj:EpisodePageSimplified = spotify.GetShowEpisodes(showId) 

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Episodes in this page of results:')

        # display episode details.
        episodeSimplified:EpisodePageSimplified
        for episodeSimplified in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=episodeSimplified.Name, uri=episodeSimplified.Uri))

            # or dump the entire object:
            #print(str(episodeSimplified))
            #print('')

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetShowEpisodes(showId, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'playlist-modify-private',
        'playlist-modify-public',
        'ugc-image-upload',
        'user-library-modify',
        'user-library-read',
        'user-read-email',
        'user-read-playback-position',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about a show's episodes.
    showId:str = '6E1u3kxII5CbbFR4VObax4'
    print('\nGetting list of ALL episodes for show id "%s" ...\n' % showId)
    pageObj:EpisodePageSimplified = spotify.GetShowEpisodes(showId, limitTotal=1000) 

    # display paging details.
    print(str(pageObj))
    print('\nEpisodes in this page of results (%d items):' % pageObj.ItemsCount)

    # display episode details.
    episodeSimplified:EpisodePageSimplified
    for episodeSimplified in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=episodeSimplified.Name, uri=episodeSimplified.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetShowFavorites( self, limit: int = 20, offset: int = 0, limitTotal: int = None) -> spotifywebapipython.models.showpagesaved.ShowPageSaved:

Get a list of the shows saved in the current Spotify user's 'Your Library'.

This method requires the user-library-read scope.

Arguments:
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

An ShowPageSaved object that contains saved show information.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of the shows saved in the current Spotify user's 'Your Library'.
    print('\nGetting saved shows for current user ...\n')
    pageObj:ShowPageSaved = spotify.GetShowFavorites()

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Shows in this page of results:')

        # display show details.
        showSaved:ShowSaved
        for showSaved in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=showSaved.Show.Name, uri=showSaved.Show.Uri))

            # use the following to display all object properties.
            #print(str(showSaved.Show))
            #print('')

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetShowFavorites(offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of the shows saved in the current Spotify user's 'Your Library'.
    print('\nGetting ALL saved shows for current user ...\n')
    pageObj:ShowPageSaved = spotify.GetShowFavorites(limitTotal=1000)

    # display paging details.
    print(str(pageObj))
    print('\nShows in this page of results (%d items):' % pageObj.ItemsCount)

    # display show details.
    showSaved:ShowSaved
    for showSaved in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=showSaved.Show.Name, uri=showSaved.Show.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetShows( self, ids: str, market: str = None) -> list[spotifywebapipython.models.showsimplified.ShowSimplified]:

Get Spotify catalog information for several shows based on their Spotify IDs.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the shows.
    Maximum: 50 IDs.
    Example: 5CfCWKI5pZ28U0uOzXkDHe,5as3aKmN2k11yfDDDSrvaZ
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
Returns:

A list of ShowSimplified objects that contain the show details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Important policy notes:

  • Spotify content may not be downloaded.
  • Keep visual content in its original form.
  • Ensure content attribution.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a multiple shows.
    showIds:str = '6kAsbP8pxwaU2kPibKTuHE,5yX0eiyk7OVq1TpNt8Owkh,6m5al8OnkyVCunFq56qwRE,6E1u3kxII5CbbFR4VObax4'
    print('\nGetting details for multiple shows: \n- %s \n' % showIds.replace(',','\n- '))
    shows:list[ShowSimplified] = spotify.GetShows(showIds)

    show:ShowSimplified
    for show in shows:

        print(str(show))
        print('')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetTrack(self, trackId: str) -> spotifywebapipython.models.track.Track:

Get Spotify catalog information for a single track identified by its unique Spotify ID.

Arguments:
  • trackId (str): The Spotify ID of the track.
    Example: 1kWUud3vY5ij5r62zxpTRy
Returns:

A Track object that contains the track details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a single track.
    trackId:str = '1kWUud3vY5ij5r62zxpTRy'
    print('\nGetting details for track "%s" ...\n' % trackId)
    track:Track = spotify.GetTrack(trackId)

    print(str(track))

    print('\nArtists:')
    artist:ArtistSimplified
    for artist in track.Artists:
        print('- "{name}" ({uri})'.format(name=artist.Name, uri=artist.Uri))

    print('')
    print(str(track.Album))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetTrackAudioFeatures( self, trackId: str) -> spotifywebapipython.models.audiofeatures.AudioFeatures:

Get audio feature information for a single track identified by its unique Spotify ID.

Arguments:
  • trackId (str): The Spotify ID of the track.
    Example: 1kWUud3vY5ij5r62zxpTRy
Returns:

An AudioFeatures object that contains the audio feature details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get audio feature information for a single track.
    trackId:str = '1kWUud3vY5ij5r62zxpTRy'
    print('\nGetting audio features for track "%s" ...\n' % trackId)
    audioFeatures:AudioFeatures = spotify.GetTrackAudioFeatures(trackId)

    print(str(audioFeatures))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetTrackFavorites( self, limit: int = 20, offset: int = 0, market: str = None, limitTotal: int = None) -> spotifywebapipython.models.trackpagesaved.TrackPageSaved:

Get a list of the tracks saved in the current Spotify user's 'Your Library'.

This method requires the user-library-read scope.

Arguments:
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

An TrackPageSaved object that contains saved track information.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of the tracks saved in the current Spotify user's 'Your Library'.
    print('\nGetting saved tracks for current user ...\n')
    pageObj:TrackPageSaved = spotify.GetTrackFavorites()

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Tracks in this page of results:')

        # display track details.
        trackSaved:TrackSaved
        for trackSaved in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=trackSaved.Track.Name, uri=trackSaved.Track.Uri))

            # use the following to display all object properties.
            #print(str(trackSaved.Track))
            #print('')

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetTrackFavorites(offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = ['user-read-email','user-library-read']

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get a list of the tracks saved in the current Spotify user's 'Your Library'.
    print('\nGetting ALL saved tracks for current user ...\n')
    pageObj:TrackPageSaved = spotify.GetTrackFavorites(limitTotal=1000)

    # display paging details.
    print(str(pageObj))
    print('\nTracks in this page of results (%d items):' % pageObj.ItemsCount)

    # display track details.
    trackSaved:TrackSaved
    for trackSaved in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=trackSaved.Track.Name, uri=trackSaved.Track.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetTracks( self, ids: list[str], market: str = None) -> list[spotifywebapipython.models.track.Track]:

Get Spotify catalog information for multiple tracks based on their Spotify IDs.

Arguments:
  • ids (list[str]): A comma-separated list of the Spotify track IDs. Maximum: 50 IDs.
    Example: 7ouMYWpwJ422jRcDASZB7P,4VqPOruhp5EdPBeR92t6lQ,2takcwOaAZWiXQijPHIx7B
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
Returns:

A list of Track objects that contain the track details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information for a multiple tracks.
    trackIds:str = '1kWUud3vY5ij5r62zxpTRy,4eoYKv2kDwJS7gRGh5q6SK'
    print('\nGetting details for multiple tracks: \n- %s \n' % trackIds.replace(',','\n- '))
    tracks:list[Track] = spotify.GetTracks(trackIds)

    track:Track
    for track in tracks:

        print(str(track))

        print('\nArtist(s):')
        for artist in track.Artists:
            print('- "{name}" ({uri})'.format(name=artist.Name, uri=artist.Uri))

        print('')
        print(str(track.Album))
        print('')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetTracksAudioFeatures( self, ids: list[str]) -> list[spotifywebapipython.models.audiofeatures.AudioFeatures]:

Get audio features for multiple tracks based on their Spotify IDs.

Arguments:
  • ids (list[str]): A comma-separated list of the Spotify track IDs. Maximum: 100 IDs.
    Example: 7ouMYWpwJ422jRcDASZB7P,4VqPOruhp5EdPBeR92t6lQ,2takcwOaAZWiXQijPHIx7B
Returns:

A list of AudioFeatures objects that contain the audio feature details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get audio features for multiple tracks based on their Spotify IDs.
    trackIds:str = '1kWUud3vY5ij5r62zxpTRy,4eoYKv2kDwJS7gRGh5q6SK'
    print('\nGetting audio features for multiple tracks: \n- %s \n' % trackIds.replace(',','\n- '))
    items:list[AudioFeatures] = spotify.GetTracksAudioFeatures(trackIds)

    audioFeatures:AudioFeatures
    for audioFeatures in items:

        print(str(audioFeatures))
        print('')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetTrackRecommendations( self, limit: int = 50, market: str = None, seedArtists: str = None, seedGenres: str = None, seedTracks: str = None, minAcousticness: float = None, maxAcousticness: float = None, targetAcousticness: float = None, minDanceability: float = None, maxDanceability: float = None, targetDanceability: float = None, minDurationMS: int = None, maxDurationMS: int = None, targetDurationMS: int = None, minEnergy: float = None, maxEnergy: float = None, targetEnergy: float = None, minInstrumentalness: float = None, maxInstrumentalness: float = None, targetInstrumentalness: float = None, minKey: int = None, maxKey: int = None, targetKey: int = None, minLiveness: float = None, maxLiveness: float = None, targetLiveness: float = None, minLoudness: float = None, maxLoudness: float = None, targetLoudness: float = None, minMode: float = None, maxMode: float = None, targetMode: float = None, minPopularity: int = None, maxPopularity: int = None, targetPopularity: int = None, minSpeechiness: float = None, maxSpeechiness: float = None, targetSpeechiness: float = None, minTempo: int = None, maxTempo: int = None, targetTempo: int = None, minTimeSignature: int = None, maxTimeSignature: int = None, targetTimeSignature: int = None, minValence: float = None, maxValence: float = None, targetValence: float = None) -> spotifywebapipython.models.trackrecommendations.TrackRecommendations:

Get track recommendations for specified criteria.

Use the GetTrackAudioFeatures method to get an idea of what to specify for some of the minX / maxX / and targetX argument values.

Arguments:
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • seedArtists (str): A comma separated list of Spotify IDs for seed artists.
    Up to 5 seed values may be provided in any combination of seedArtists, seedTracks and seedGenres.
    Note: only required if seedGenres and seedTracks are not set.
    Example: 4NHQUGzhtTLFvgF5SZesLK
  • seedGenres (str): A comma separated list of any genres in the set of available genre seeds.
    Up to 5 seed values may be provided in any combination of seedArtists, seedTracks and seedGenres.
    Note: only required if seedArtists and seedTracks are not set.
    Example: classical,country
  • seedTracks (str): A comma separated list of Spotify IDs for a seed track.
    Up to 5 seed values may be provided in any combination of seedArtists, seedTracks and seedGenres.
    Note: only required if seedArtists and seedGenres are not set.
    Example: 0c6xIDDpzE81m2q797ordA
  • minAcousticness (float): Restrict results to only those tracks whose acousticness level is greater than the specified value.
    Range: 0 - 1
  • maxAcousticness (float): Restrict results to only those tracks whose acousticness level is less than the specified value.
    Range: 0 - 1
  • targetAcousticness (float): Restrict results to only those tracks whose acousticness level is equal to the specified value.
    Range: 0 - 1
  • minDanceability (float): Restrict results to only those tracks whose danceability level is greater than the specified value.
    Range: 0 - 1
  • maxDanceability (float): Restrict results to only those tracks whose danceability level is less than the specified value.
    Range: 0 - 1
  • targetDanceability (float): Restrict results to only those tracks whose acousticness is equal to the specified value.
    Range: 0 - 1
  • minDurationMS (int): Restrict results to only those tracks whose duration is greater than the specified value in milliseconds.
  • maxDurationMS (int): Restrict results to only those tracks whose duration is less than the specified value in milliseconds.
  • targetDurationMS (int): Restrict results to only those tracks whose duration is equal to the specified value in milliseconds.
  • minEnergy (float): Restrict results to only those tracks whose energy level is greater than the specified value.
    Range: 0 - 1
  • maxEnergy (float): Restrict results to only those tracks whose energy level is less than the specified value.
    Range: 0 - 1
  • targetEnergy (float): Restrict results to only those tracks whose energy level is equal to the specified value.
    Range: 0 - 1
  • minInstrumentalness (float): Restrict results to only those tracks whose instrumentalness level is greater than the specified value.
    Range: 0 - 1
  • maxInstrumentalness (float): Restrict results to only those tracks whose instrumentalness level is less than the specified value.
    Range: 0 - 1
  • targetInstrumentalness (float): Restrict results to only those tracks whose instrumentalness level is equal to the specified value.
    Range: 0 - 1
  • minKey (int): Restrict results to only those tracks whose key level is greater than the specified value.
    Range: 0 - 11
  • maxKey (int): Restrict results to only those tracks whose key level is less than the specified value.
    Range: 0 - 11
  • targetKey (int): Restrict results to only those tracks whose key level is equal to the specified value.
    Range: 0 - 11
  • minLiveness (float): Restrict results to only those tracks whose liveness level is greater than the specified value.
    Range: 0 - 1
  • maxLiveness (float): Restrict results to only those tracks whose liveness level is less than the specified value.
    Range: 0 - 1
  • targetLiveness (float): Restrict results to only those tracks whose liveness level is equal to the specified value.
    Range: 0 - 1
  • minLoudness (float): Restrict results to only those tracks whose loudness level is greater than the specified value.
  • maxLoudness (float): Restrict results to only those tracks whose loudness level is less than the specified value.
  • targetLoudness (float): Restrict results to only those tracks whose loudness level is equal to the specified value.
  • minMode (float): Restrict results to only those tracks whose mode level is greater than the specified value.
    Range: 0 - 1
  • maxMode (float): Restrict results to only those tracks whose mode level is less than the specified value.
    Range: 0 - 1
  • targetMode (float): Restrict results to only those tracks whose mode level is equal to the specified value.
    Range: 0 - 1
  • minPopularity (int): Restrict results to only those tracks whose popularity level is greater than the specified value.
    Range: 0 - 100
  • maxPopularity (int): Restrict results to only those tracks whose popularity level is less than the specified value.
    Range: 0 - 100
  • targetPopularity (int): Restrict results to only those tracks whose popularity level is equal to the specified value.
    Range: 0 - 100
  • minSpeechiness (float): Restrict results to only those tracks whose speechiness level is greater than the specified value.
    Range: 0 - 1
  • maxSpeechiness (float): Restrict results to only those tracks whose speechiness level is less than the specified value.
    Range: 0 - 1
  • targetSpeechiness (float): Restrict results to only those tracks whose speechiness level is equal to the specified value.
    Range: 0 - 1
  • minTempo (int): Restrict results to only those tracks with a tempo greater than the specified number of beats per minute.
  • maxTempo (int): Restrict results to only those tracks with a tempo less than the specified number of beats per minute.
  • targetTempo (int): Restrict results to only those tracks with a tempo equal to the specified number of beats per minute.
  • minTimeSignature (int): Restrict results to only those tracks whose time signature is greater than the specified value.
    Maximum value: 11
  • maxTimeSignature (int): Restrict results to only those tracks whose time signature is less than the specified value.
  • targetTimeSignature (int): Restrict results to only those tracks whose time signature is equal to the specified value.
  • minValence (float): Restrict results to only those tracks whose valence level is greater than the specified value.
    Range: 0 - 1
  • maxValence (float): Restrict results to only those tracks whose valence level is less than the specified value.
    Range: 0 - 1
  • targetValence (float): Restrict results to only those tracks whose valence level is equal to the specified value.
    Range: 0 - 1
Returns:

A TrackRecommendations object that contain the recommendations.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Recommendations are generated based on the available information for a given seed entity and matched against similar artists and tracks. If there is sufficient information about the provided seeds, a list of tracks will be returned together with pool size details.

For artists and tracks that are very new or obscure there might not be enough data to generate a list of tracks.

Important policy note:

  • Spotify content may not be used to train machine learning or AI model.

Sample Code - Wind Down

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify track recommendations for specified criteria.
    print('\nGetting track recommendations - Wind Down!\n')
    recommendations:TrackRecommendations = spotify.GetTrackRecommendations(seedArtists='3jdODvx7rIdq0UGU7BOVR3',seedGenres='piano',maxEnergy=0.175)

    print(str(recommendations))
    print('')

    seed:RecommendationSeed
    for seed in recommendations.Seeds:

        print(str(seed))
        print('')

    print('Recommended Tracks:')
    track:Track
    for track in recommendations.Tracks:

        print('- "{name}" ({uri})'.format(name=track.Name, uri=track.Uri))
        #print(str(track))

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - I Wanna Rock!

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify track recommendations for specified criteria.
    print('\nGetting track recommendations - I wanna rock!\n')
    recommendations:TrackRecommendations = spotify.GetTrackRecommendations(seedGenres='rock,hard-rock,rock-n-roll',minLoudness=-9.201,minTimeSignature=4,minEnergy=0.975)

    print(str(recommendations))
    print('')

    seed:RecommendationSeed
    for seed in recommendations.Seeds:

        print(str(seed))
        print('')

    print('Recommended Tracks:')
    track:Track
    for track in recommendations.Tracks:

        print('- "{name}" ({uri})'.format(name=track.Name, uri=track.Uri))
        #print(str(track))

except Exception as ex:

    print("** Exception: %s" % str(ex))

@staticmethod
def GetTypeFromUri(uri: str) -> str:

Get the type portion from a Spotify uri value.

Arguments:
  • uri (str): The Spotify URI value. Example: spotify:track:5v5ETK9WFXAnGQ3MRubKuE
Returns:

A string containing the type value (e.g. track).

No exceptions are raised with this method.

def GetUsersCurrentProfile( self, refresh: bool = True) -> spotifywebapipython.models.userprofile.UserProfile:

Get detailed profile information about the current user (including the current user's username).

This method requires the user-read-private and user-read-email scope.

Arguments:
  • refresh (bool): True (default) to return real-time information from the spotify web api and update the cache; otherwise, False to just return the cached value.
Returns:

A UserProfile object that contains the user details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

The ConfigurationCache is updated with the results of this method. Use the refresh argument (with False value) to retrieve the cached value and avoid the spotify web api request. This results in better performance.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-library-read',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # note - the spotify.UserProfile contains the same object, but you can also do it this way ...

    # get detailed profile information about the current user.
    print('\nGetting user profile for current user ...\n')
    userProfile:UserProfile = spotify.GetUsersCurrentProfile()

    print(str(userProfile))

    # get cached configuration, refreshing from device if needed.
    userProfile:UserProfile = spotify.GetUsersCurrentProfile(refresh=False)
    print("\nCached configuration:\n%s" % str(userProfile))

    # get cached configuration directly from the configuration manager dictionary.
    if "GetUsersCurrentProfile" in spotify.ConfigurationCache:
        userProfile:UserProfile = spotify.ConfigurationCache["GetUsersCurrentProfile"]
        print("\nCached configuration direct access:\n%s" % str(userProfile))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetUsersPublicProfile( self, userId: str) -> spotifywebapipython.models.userprofilesimplified.UserProfileSimplified:

Get public profile information about a Spotify user.

Arguments:
  • userId (str): The user's Spotify user ID. Example: smedjan
Returns:

A UserProfileSimplified object that contains the user's public details.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get public profile information about a Spotify user.
    userId:str = 'smedjan'
    print('\nGetting public user profile for user id "%s" ...\n' % userId)
    userProfile:UserProfileSimplified = spotify.GetUsersPublicProfile(userId)

    print(str(userProfile))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetUsersTopArtists( self, timeRange: str = 'medium_term', limit: int = 20, offset: int = 0, limitTotal: int = None) -> spotifywebapipython.models.artistpage.ArtistPage:

Get the current user's top artists based on calculated affinity.

Arguments:
  • timeRange (str): Over what time frame the affinities are computed.
    Valid values:
    • long_term (calculated from several years of data and including all new data as it becomes available).
    • medium_term (approximately last 6 months).
    • short_term (approximately last 4 weeks).
      Default: medium_term
      Example: long_term
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item), Range: 0 to 1000
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

An ArtistPage object of matching results.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-top-read',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get current user's top artists based on calculated affinity.
    affinity:str = 'long_term'
    print('\nGetting current user top artists for "%s" affinity ...\n' % affinity)
    pageObj:ArtistPage = spotify.GetUsersTopArtists(affinity)

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Artists in this page of results:')

        # display artist details.
        artist:Artist
        for artist in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=artist.Name, uri=artist.Uri))

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetUsersTopArtists(affinity, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-top-read',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get current user's top artists based on calculated affinity.
    affinity:str = 'long_term'
    print('\nGetting ALL current user top artists for "%s" affinity ...\n' % affinity)
    pageObj:ArtistPage = spotify.GetUsersTopArtists(affinity, limitTotal=1000)

    # display paging details.
    print(str(pageObj))
    print('\nArtists in this page of results (%d items):' % pageObj.ItemsCount)

    # display artist details.
    artist:Artist
    for artist in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=artist.Name, uri=artist.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def GetUsersTopTracks( self, timeRange: str = 'medium_term', limit: int = 20, offset: int = 0, limitTotal: int = None) -> spotifywebapipython.models.trackpage.TrackPage:

Get the current user's top tracks based on calculated affinity.

Arguments:
  • timeRange (str): Over what time frame the affinities are computed.
    Valid values:
    • long_term (calculated from several years of data and including all new data as it becomes available).
    • medium_term (approximately last 6 months).
    • short_term (approximately last 4 weeks).
      Default: medium_term
      Example: long_term
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item).
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

An TrackPage object of matching results.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-top-read',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get current user's top tracks based on calculated affinity.
    affinity:str = 'long_term'
    print('\nGetting current user top tracks for "%s" affinity ...\n' % affinity)
    pageObj:TrackPage = spotify.GetUsersTopTracks(affinity,limit=8)

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # display paging details.
        print(str(pageObj))
        print('')
        print('Tracks in this page of results:')

        # display track details.
        track:Track
        for track in pageObj.Items:

            print('- "{name}" ({uri})'.format(name=track.Name, uri=track.Uri))

        # anymore page results?
        if pageObj.Next is None:
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            pageObj = spotify.GetUsersTopTracks(affinity, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-top-read',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get current user's top tracks based on calculated affinity.
    affinity:str = 'long_term'
    print('\nGetting ALL current user top tracks for "%s" affinity ...\n' % affinity)
    pageObj:TrackPage = spotify.GetUsersTopTracks(affinity, limitTotal=1000)

    # display paging details.
    print(str(pageObj))
    print('\nTracks in this page of results (%d items):' % pageObj.ItemsCount)

    # display track details.
    track:Track
    for track in pageObj.Items:
        print('- "{name}" ({uri})'.format(name=track.Name, uri=track.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerMediaPause(self, deviceId: str = None, delay: float = 0.5) -> None:

Pause media play for the specified Spotify Connect device.

This method requires the user-modify-playback-state scope.

Arguments:
  • deviceId (str): The id or name of the device this command is targeting.
    If not supplied, the user's currently active device is the target.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

The order of execution is not guaranteed when you use this API with other Player API endpoints.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # pause play on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    print('\nPause media on Spotify Connect device:\n- "%s" ...' % str(deviceId))
    spotify.PlayerMediaPause(deviceId)

    print('\nSuccess - media was paused')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerMediaPlayContext( self, contextUri: str, offsetUri: str = None, offsetPosition: int = None, positionMS: int = 0, deviceId: str = None, delay: float = 0.5) -> None:

Start playing one or more tracks of the specified context on a Spotify Connect device.

This method requires the user-modify-playback-state scope.

Arguments:
  • contextUri (str): Spotify URI of the context to play.
    Valid contexts are albums, artists & playlists.
    Example: spotify:album:6vc9OTcyd3hyzabCmsdnwE.
  • offsetUri (str): Indicates from what Uri in the context playback should start.
    Only available when contextUri corresponds to an artist, album or playlist.
    The offsetPosition argument will be used if this value is null.
    Default is null.
    Example: spotify:track:1301WleyT98MSxVHPZCA6M start playing at the specified track Uri.
  • offsetPosition (int): Indicates from what position in the context playback should start.
    The value is zero-based, and can't be negative.
    Only available when contextUri corresponds to an album or playlist.
    Default is 0.
    Example: 3 start playing at track number 4.
  • positionMS (int): The position in milliseconds to seek to; must be a positive number.
    Passing in a position that is greater than the length of the track will cause the player to start playing the next track.
    Default is 0.
    Example: 25000
  • deviceId (str): The id or name of the device this command is targeting.
    If not supplied, the user's currently active device is the target.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

The order of execution is not guaranteed when you use this API with other Player API endpoints.

Sample Code - Play Album

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # play album on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    contextUri:str = 'spotify:album:6vc9OTcyd3hyzabCmsdnwE'  # Album = Welcome to the New
    print('\nPlaying album on Spotify Connect device: \nID: %s \n- %s' % (deviceId, contextUri))
    spotify.PlayerMediaPlayContext(contextUri, deviceId=deviceId)

    print('\nSuccess - album should be playing')

    # play album starting at track #7 on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    contextUri:str = 'spotify:album:6vc9OTcyd3hyzabCmsdnwE'  # Album = Welcome to the New
    print('\nPlaying album starting at track #7 on Spotify Connect device: \nID: %s \n- %s' % (deviceId, contextUri))
    spotify.PlayerMediaPlayContext(contextUri, offsetPosition=6, deviceId=deviceId)

    print('\nSuccess - album should be playing')

    # play album starting at track #5 and 25 seconds position on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    contextUri:str = 'spotify:album:6vc9OTcyd3hyzabCmsdnwE'  # Album = Welcome to the New
    print('\nPlaying album starting at track #5 (25 seconds) on Spotify Connect device: \nID: %s \n- %s' % (deviceId, contextUri))
    spotify.PlayerMediaPlayContext(contextUri, offsetPosition=4, positionMS=25000, deviceId=deviceId)

    print('\nSuccess - album should be playing')

    # play album starting at track id #7 on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    contextUri:str = 'spotify:album:6vc9OTcyd3hyzabCmsdnwE'  # Album = Welcome to the New
    offsetUri:str = 'spotify:track:1kWUud3vY5ij5r62zxpTRy'   # Track = Flawless
    print('\nPlaying album starting at track #7 on Spotify Connect device: \nID: %s \n- %s' % (deviceId, contextUri))
    spotify.PlayerMediaPlayContext(contextUri, offsetUri=offsetUri, deviceId=deviceId)

    print('\nSuccess - album should be playing')

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Play Artist

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # play artist on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    contextUri:str = 'spotify:artist:6APm8EjxOHSYM5B4i3vT3q'  # Artist = MercyMe
    print('\nPlaying artist on Spotify Connect device: \nID: %s \n- %s' % (deviceId, contextUri))
    spotify.PlayerMediaPlayContext(contextUri, deviceId=deviceId)

    print('\nSuccess - artist should be playing')

    # play artist and start first song played at the 25 seconds position on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    contextUri:str = 'spotify:artist:6APm8EjxOHSYM5B4i3vT3q'  # Artist = MercyMe
    print('\nPlaying artist at the 25 seconds position on Spotify Connect device: \nID: %s \n- %s' % (deviceId, contextUri))
    spotify.PlayerMediaPlayContext(contextUri, positionMS=25000, deviceId=deviceId)

    print('\nSuccess - artist should be playing')

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Play Playlist

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # play playlist on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    contextUri:str = 'spotify:playlist:5v5ETK9WFXAnGQ3MRubKuE'  # Playlist = My Playlist
    print('\nPlaying playlist on Spotify Connect device: \nID: %s \n- %s' % (deviceId, contextUri))
    spotify.PlayerMediaPlayContext(contextUri, deviceId=deviceId)

    print('\nSuccess - playlist should be playing')

    # play playlist starting at track #7 on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    contextUri:str = 'spotify:playlist:5v5ETK9WFXAnGQ3MRubKuE'  # Playlist = My Playlist
    print('\nPlaying playlist starting at track #7 on Spotify Connect device: \nID: %s \n- %s' % (deviceId, contextUri))
    spotify.PlayerMediaPlayContext(contextUri, offsetPosition=6, deviceId=deviceId)

    print('\nSuccess - playlist should be playing')

    # play playlist starting at track #5 and 25 seconds position on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    contextUri:str = 'spotify:playlist:5v5ETK9WFXAnGQ3MRubKuE'  # Playlist = My Playlist
    print('\nPlaying playlist starting at track #5 (25 seconds) on Spotify Connect device: \nID: %s \n- %s' % (deviceId, contextUri))
    spotify.PlayerMediaPlayContext(contextUri, offsetPosition=4, positionMS=25000, deviceId=deviceId)

    print('\nSuccess - playlist should be playing')

    # play playlist starting at track id #7 on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    contextUri:str = 'spotify:playlist:5v5ETK9WFXAnGQ3MRubKuE'  # Playlist = My Playlist
    offsetUri:str = 'spotify:track:1kWUud3vY5ij5r62zxpTRy'      # Track = Flawless
    print('\nPlaying playlist starting at track #7 on Spotify Connect device: \nID: %s \n- %s' % (deviceId, contextUri))
    spotify.PlayerMediaPlayContext(contextUri, offsetUri=offsetUri, deviceId=deviceId)

    print('\nSuccess - playlist should be playing')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerMediaPlayTrackFavorites( self, deviceId: str = None, shuffle: bool = True, delay: float = 0.5) -> None:

Get a list of the tracks saved in the current Spotify user's 'Your Library' and starts playing them.

Arguments:
  • deviceId (str): The id or name of the device this command is targeting.
    If not supplied, the user's currently active device is the target.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
  • shuffle (bool): True to set player shuffle mode to on; otherwise, False for no shuffle.
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

This method simply calls the GetTrackFavorites method to retrieve the current users favorite tracks (200 max), then calls the PlayerMediaPlayTracks method to play them.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # play all track favorites on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    print('\nPlaying track favorites on Spotify Connect device: \nID: %s' % deviceId)
    spotify.PlayerMediaPlayTrackFavorites(deviceId)

    print('\nSuccess - media should be playing')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerMediaPlayTracks( self, uris: list[str], positionMS: int = 0, deviceId: str = None, delay: float = 0.5) -> None:

Start playing one or more tracks on the specified Spotify Connect device.

This method requires the user-modify-playback-state scope.

Arguments:
  • uris (str): A list of Spotify track URIs to play; can be track or episode URIs.
    Example: [spotify:track:6zd8T1PBe9JFHmuVnurdRp ,spotify:track:1kWUud3vY5ij5r62zxpTRy].
    It can also be specified as a comma-delimited string.
    Example: spotify:track:6zd8T1PBe9JFHmuVnurdRp,spotify:track:1kWUud3vY5ij5r62zxpTRy.
    A maximum of 50 items can be added in one request.
  • positionMS (int): The position in milliseconds to seek to; must be a positive number.
    Passing in a position that is greater than the length of the track will cause the player to start playing the next track.
    Default is 0.
    Example: 25000
  • deviceId (str): The id or name of the device this command is targeting.
    If not supplied, the user's currently active device is the target.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

The order of execution is not guaranteed when you use this API with other Player API endpoints.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # play single track on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    uris:str='spotify:track:1kWUud3vY5ij5r62zxpTRy'  # Flawless
    print('\nPlaying media on Spotify Connect device: \nID: %s \n- %s' % (deviceId, uris.replace(',','\n- ')))
    spotify.PlayerMediaPlayTracks(uris, 0, deviceId)

    print('\nSuccess - media should be playing')

    # play single track on the specified Spotify Connect device.
    # start playing at the 25 seconds (25000 milliseconds) point in the track.
    deviceId:str = None   # use currently playing device
    uris:str='spotify:track:1kWUud3vY5ij5r62zxpTRy'  # Flawless
    print('\nPlaying media on Spotify Connect device: \nID: %s \n- %s' % (deviceId, uris.replace(',','\n- ')))
    spotify.PlayerMediaPlayTracks(uris, 25000, deviceId)

    print('\nSuccess - media should be playing')

    # play multiple tracks on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    uris:str='spotify:track:1kWUud3vY5ij5r62zxpTRy,spotify:track:27JODWXo4VNa6s7HqDL9yQ,spotify:track:4iV5W9uYEdYUVa79Axb7Rh'
    print('\nPlaying media on Spotify Connect device: \nID: %s \n- %s' % (deviceId, uris.replace(',','\n- ')))
    spotify.PlayerMediaPlayTracks(uris, 0, deviceId)

    print('\nSuccess - media should be playing')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerMediaResume(self, deviceId: str = None, delay: float = 0.5) -> None:

Resume media play for the specified Spotify Connect device.

This method requires the user-modify-playback-state scope.

Arguments:
  • deviceId (str): The id or name of the device this command is targeting.
    If not supplied, the user's currently active device is the target.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

The order of execution is not guaranteed when you use this API with other Player API endpoints.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # resume play on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    print('\nResume media on Spotify Connect device:\n- "%s" ...' % str(deviceId))
    spotify.PlayerMediaResume(deviceId)

    print('\nSuccess - media was resumed')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerMediaSeek( self, positionMS: int = 0, deviceId: str = None, delay: float = 0.5) -> None:

Seeks to the given position in the user's currently playing track for the specified Spotify Connect device.

This method requires the user-modify-playback-state scope.

Arguments:
  • positionMS (int): The position in milliseconds to seek to; must be a positive number.
    Passing in a position that is greater than the length of the track will cause the player to start playing the next song. Example: 25000
  • deviceId (str): The id or name of the device this command is targeting.
    If not supplied, the user's currently active device is the target.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

The order of execution is not guaranteed when you use this API with other Player API endpoints.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # seek to the given position in the on the specified Spotify Connect device.
    positionMS:int = 25000
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    print('\nSeeking to %d milliseconds on Spotify Connect device:\n- "%s" ...' % (positionMS, deviceId))
    spotify.PlayerMediaSeek(positionMS, deviceId)

    print('\nSuccess - seek to position in track')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerMediaSkipNext(self, deviceId: str = None, delay: float = 0.5) -> None:

Skips to next track in the user's queue for the specified Spotify Connect device.

This method requires the user-modify-playback-state scope.

Arguments:
  • deviceId (str): The id or name of the device this command is targeting.
    If not supplied, the user's currently active device is the target.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

The order of execution is not guaranteed when you use this API with other Player API endpoints.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # skip to next track on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    print('\nSkip to next track on Spotify Connect device:\n- "%s" ...' % str(deviceId))
    spotify.PlayerMediaSkipNext(deviceId)

    print('\nSuccess - skipped to next track')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerMediaSkipPrevious(self, deviceId: str = None, delay: float = 0.5) -> None:

Skips to previous track in the user's queue for the specified Spotify Connect device.

This method requires the user-modify-playback-state scope.

Arguments:
  • deviceId (str): The id or name of the device this command is targeting.
    If not supplied, the user's currently active device is the target.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

The order of execution is not guaranteed when you use this API with other Player API endpoints.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # skip to previous track on the specified Spotify Connect device.
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    print('\nSkip to previous track on Spotify Connect device:\n- "%s" ...' % str(deviceId))
    spotify.PlayerMediaSkipPrevious(deviceId)

    print('\nSuccess - skipped to previous track')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerSetRepeatMode( self, state: str = 'off', deviceId: str = None, delay: float = 0.5) -> None:

Set repeat mode for the specified Spotify Connect device.

This method requires the user-modify-playback-state scope.

Arguments:
  • state (str): The repeat mode to set:
    • track - will repeat the current track.
    • context - will repeat the current context.
    • off - will turn repeat off. Default: off
  • deviceId (str): The id or name of the device this command is targeting.
    If not supplied, the user's currently active device is the target.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

The order of execution is not guaranteed when you use this API with other Player API endpoints.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # set repeat mode CONTEXT for the user's current playback device.
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    print('\nSet repeat mode CONTEXT for Spotify Connect device:\n- "%s" ...' % (str(deviceId)))
    spotify.PlayerSetRepeatMode('context', deviceId)

    print('\nSuccess - repeat mode CONTEXT was set')

    # set repeat mode TRACK for the user's current playback device.
    deviceId:str = None   # use currently playing device
    print('\nSet repeat mode to single track for Spotify Connect device:\n- "%s" ...' % (str(deviceId)))
    spotify.PlayerSetRepeatMode('track', deviceId)

    print('\nSuccess - repeat mode TRACK was set')

    # set repeat mode OFF for the user's current playback device.
    deviceId:str = None   # use currently playing device
    print('\nSet repeat mode OFF for Spotify Connect device:\n- "%s" ...' % (str(deviceId)))
    spotify.PlayerSetRepeatMode('off', deviceId)

    print('\nSuccess - repeat mode OFF was set')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerSetShuffleMode( self, state: bool = False, deviceId: str = None, delay: float = 0.5) -> None:

Set shuffle mode for the specified Spotify Connect device.

This method requires the user-modify-playback-state scope.

Arguments:
  • state (bool): The shuffle mode to set:
    • True - Shuffle user's playback.
    • False - Do not shuffle user's playback. Default: False
  • deviceId (str): The id or name of the device this command is targeting.
    If not supplied, the user's currently active device is the target.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

The order of execution is not guaranteed when you use this API with other Player API endpoints.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # set shuffle mode ON for the user's current playback device.
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    print('\nSet shuffle mode ON for Spotify Connect device:\n- "%s" ...' % (str(deviceId)))
    spotify.PlayerSetShuffleMode(True, deviceId)

    print('\nSuccess - shuffle mode ON was set')

    # set shuffle mode OFF for the user's current playback device.
    deviceId:str = None   # use currently playing device
    print('\nSet shuffle mode OFF for Spotify Connect device:\n- "%s" ...' % (str(deviceId)))
    spotify.PlayerSetShuffleMode(False, deviceId)

    print('\nSuccess - shuffle mode OFF was set')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerSetVolume( self, volumePercent: int, deviceId: str = None, delay: float = 0.5) -> None:

Set volume level for the specified Spotify Connect device.

This method requires the user-modify-playback-state scope.

Arguments:
  • volumePercent (int): The volume to set.
    Must be a value from 0 to 100 inclusive. Example: 50
  • deviceId (str): The id or name of the device this command is targeting.
    If not supplied, the user's currently active device is the target.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

The order of execution is not guaranteed when you use this API with other Player API endpoints.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # set the volume for the user's current playback device.
    volumePercent:int = 100
    deviceId:str = None   # use currently playing device
    #deviceId:str = "Web Player (Chrome)" # or device name
    #deviceId:str = "0d1841b0976bae2a3a310dd74c0f3df354899bc8" # or device id
    print('\nSet %d%% volume on Spotify Connect device:\n- "%s" ...' % (volumePercent, str(deviceId)))
    spotify.PlayerSetVolume(volumePercent, deviceId)

    print('\nSuccess - volume was set')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerTransferPlayback( self, deviceId: str = None, play: bool = True, delay: float = 0.5) -> None:

Transfer playback to a new Spotify Connect device and optionally begin playback.

This method requires the user-modify-playback-state scope.

Arguments:
  • deviceId (str): The id or name of the device on which playback should be started/transferred. Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
    Example: Web Player (Chrome)
  • play (bool): The transfer method:
    • True - ensure playback happens on new device.
    • False - keep the current playback state.
      Default: True
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

This API only works for users who have Spotify Premium.

The order of execution is not guaranteed when you use this API with other Player API endpoints.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # transfer Spotify Connect playback control to another device.
    # the device name and id can be retrieved from `GetPlayerDevices` method.
    deviceId:str = "Web Player (Chrome)" # or device name
    print('\nTransfer Spotify Connect playback control to:\n-Name: "%s" ...' % deviceId)
    spotify.PlayerTransferPlayback(deviceId, True)

    print('\nSuccess - control was transferred')

    # transfer Spotify Connect playback control to another device.
    # the device name and id can be retrieved from `GetPlayerDevices` method.
    deviceId:str = 'Bose-ST10-1'
    print('\nTransfer Spotify Connect playback control to:\n-Name: "%s" ...' % deviceId)
    spotify.PlayerTransferPlayback(deviceId, True)

    print('\nSuccess - control was transferred')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def PlayerVerifyDeviceDefault( self, defaultDeviceId: str = None, play: bool = False, delay: float = 0.5) -> spotifywebapipython.models.playerplaystate.PlayerPlayState:

Checks to see if there is an active Spotify Connect device, and if not to make one active.

If no active device was found, then it will activate the device specified by the defaultDeviceId argument and optionally start play on the device.

This method requires the user-read-playback-state and user-modify-playback-state scope.

Arguments:
  • defaultDeviceId (str): The id of the device on which playback should be started/transferred if there is currently no active device.
    Example: 0d1841b0976bae2a3a310dd74c0f3df354899bc8
  • play (bool): The transfer method:
    • True - ensure playback happens on new device.
    • False - keep the current playback state.
      Default: False
  • delay (float): Time delay (in seconds) to wait AFTER issuing the command to the player.
    This delay will give the spotify web api time to process the change before another command is issued.
    Default is 0.50; value range is 0 - 10.
Returns:

A PlayerPlayState object that contains player state details as well as currently playing content.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-modify-playback-state',
        'user-read-email',
        'user-read-playback-state'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # verify that Spotify Connect has a default player active.
    defaultDeviceId:str = '236427c8c0d510caa323f84cb42bc03eec090750'
    print('\nVerifying Spotify Connect player is active; default device if not:\n- ID: %s ...' % (defaultDeviceId))
    playerState:PlayerPlayState = spotify.PlayerVerifyDeviceDefault(defaultDeviceId, False)

    print(str(playerState))
    print('')
    print(str(playerState.Item))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def RemoveAlbumFavorites(self, ids: str = None) -> None:

Remove one or more albums from the current user's 'Your Library'.

This method requires the user-library-modify scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the albums.
    Maximum: 50 IDs.
    Example: 6vc9OTcyd3hyzabCmsdnwE,382ObEPsp2rxGrnsizN5TX If null, the currently playing track album uri id value is used.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No error will be raised if an album id in the list does not exist in the user's 'Your Library'.

An SpotifyWebApiError will be raised if a specified album id does not exist in the Spotify music catalog.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-library-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # remove one or more albums from the current user's 'Your Library'.
    albumIds:str = '382ObEPsp2rxGrnsizN5TX,6vc9OTcyd3hyzabCmsdnwE,382ObEPsp2rxGrnsizN5TY'
    print('\nRemoving saved album(s) from the current users profile: \n- %s' % albumIds.replace(',','\n- '))
    spotify.RemoveAlbumFavorites(albumIds)

    print('\nSuccess - album(s) were removed')

    # remove nowplaying track album from the current user's 'Your Library'.
    print('\nRemoving nowplaying track album from the current users profile')
    spotify.RemoveAlbumFavorites()

    print('\nSuccess - album(s) were removed')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def RemoveAudiobookFavorites(self, ids: str) -> None:

Remove one or more audiobooks from the current user's 'Your Library'.

This method requires the user-library-modify scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the audiobooks.
    Maximum: 50 IDs.
    Example: 3PFyizE2tGCSRLusl2Qizf,7iHfbu1YPACw6oZPAFJtqe
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No error will be raised if a audiobook id in the list does not exist in the user's 'Your Library'.

An SpotifyWebApiError will be raised if a specified album id does not exist in the Spotify music catalog.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-library-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # remove one or more audiobooks from the current user's 'Your Library'.
    audiobookIds:str = '3PFyizE2tGCSRLusl2Qizf,7iHfbu1YPACw6oZPAFJtqe'
    print('\nRemoving saved audiobook(s) from the current users profile: \n- %s' % audiobookIds.replace(',','\n- '))
    spotify.RemoveAudiobookFavorites(audiobookIds)

    print('\nSuccess - audiobook(s) were removed')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def RemoveEpisodeFavorites(self, ids: str) -> None:

Remove one or more episodes from the current user's 'Your Library'.

This method requires the user-library-modify scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the episodes.
    Maximum: 50 IDs.
    Example: 6kAsbP8pxwaU2kPibKTuHE,4rOoJ6Egrf8K2IrywzwOMk
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No error will be raised if a episode id in the list does not exist in the user's 'Your Library'.

An SpotifyWebApiError will be raised if a specified album id does not exist in the Spotify music catalog.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-library-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # remove one or more episodes from the current user's 'Your Library'.
    episodeIds:str = '1hPX5WJY6ja6yopgVPBqm4,3F97boSWlXi8OzuhWClZHQ'
    print('\nRemoving saved episode(s) from the current users profile: \n- %s' % episodeIds.replace(',','\n- '))
    spotify.RemoveEpisodeFavorites(episodeIds)

    print('\nSuccess - episode(s) were removed')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def RemovePlaylist(self, playlistId: str) -> None:

Remove a user's playlist (calls the UnfollowPlaylist method).

This method requires the playlist-modify-public and playlist-modify-private scope.

Arguments:
  • playlistId (str): The Spotify ID of the playlist. Example: 5AC9ZXA7nJ7oGWO911FuDG
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

There is no Spotify Web API endpoint for deleting a playlist. The notion of deleting a playlist is not relevant within the Spotify playlist system. Even if you are the playlist owner and you choose to manually remove it from your own list of playlists, you are simply unfollowing it. Although this behavior may sound strange, it means that other users who are already following the playlist can keep enjoying it.

Manually restoring a deleted playlist through the Spotify Accounts Service is the same thing as following one of your own playlists that you have previously unfollowed.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # remove playlist (ie. unfollow it).
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    print('\nRemoving playlist id "%s"' % playlistId)
    spotify.RemovePlaylist(playlistId)

    print('\nPlaylist removed successfully')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def RemovePlaylistItems(self, playlistId: str, uris: str = None, snapshotId: str = None) -> str:

Remove one or more items from a user's playlist.

This method requires the playlist-modify-public and playlist-modify-private scope.

Arguments:
  • playlistId (str): The Spotify ID of the playlist. Example: 5AC9ZXA7nJ7oGWO911FuDG
  • uris (str): A comma-separated list of Spotify URIs to remove; can be track or episode URIs.
    Example: spotify:track:4iV5W9uYEdYUVa79Axb7Rh,spotify:episode:512ojhOuo1ktJprKbVcKyQ.
    A maximum of 100 items can be specified in one request. If null, the currently playing context uri value is used.
  • snapshotId (str): The playlist's snapshot ID against which you want to make the changes.
    The API will validate that the specified items exist and in the specified positions and make the changes, even if more recent changes have been made to the playlist. If null, the current playlist is updated.
    Example: MTk3LGEzMjUwZGYwODljNmI5ZjAxZTRjZThiOGI4NzZhM2U5M2IxOWUyMDQ Default is null.
Returns:

A snapshot ID for the updated playlist.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

The snapshotId argument value will be returned if no items were removed; otherwise, a new snapshot id value will be returned.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # remove items from current playlist.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    itemUris:str = 'spotify:track:2takcwOaAZWiXQijPHIx7B,spotify:track:4eoYKv2kDwJS7gRGh5q6SK'
    print('\nRemoving items from playlist id "%s": \n- %s' % (playlistId, itemUris.replace(',','\n- ')))
    result:str = spotify.RemovePlaylistItems(playlistId, itemUris)

    print('\nPlaylist updated successfully:\n- snapshot ID = "%s"' % result)

    # remove items from a playlist snapshot.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    snapshotId:str = 'NDQsMGI2ZjJhMTcyNWY3NmMyZDZhNTkxNTc5ODI0ZGFjOWRkYWM2N2QyMw===='
    itemUris:str = 'spotify:track:2takcwOaAZWiXQijPHIx7B,spotify:track:4eoYKv2kDwJS7gRGh5q6SK'
    print('\nRemoving items from snapshot playlist id "%s": \n- %s' % (playlistId, itemUris.replace(',','\n- ')))
    result:str = spotify.RemovePlaylistItems(playlistId, itemUris, snapshotId)

    print('\nPlaylist updated successfully:\n- snapshot ID = "%s"' % result)

    # remove nowplaying item from current playlist.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    print('\nRemoving nowplaying item from playlist id "%s"' % (playlistId))
    result:str = spotify.RemovePlaylistItems(playlistId)

    print('\nPlaylist updated successfully:\n- snapshot ID = "%s"' % result)

except Exception as ex:

    print("** Exception: %s" % str(ex))

def RemoveShowFavorites(self, ids: str) -> None:

Remove one or more shows from the current user's 'Your Library'.

This method requires the user-library-modify scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the shows.
    Maximum: 50 IDs.
    Example: 6kAsbP8pxwaU2kPibKTuHE,4rOoJ6Egrf8K2IrywzwOMk
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No error will be raised if a show id in the list does not exist in the user's 'Your Library'.

An SpotifyWebApiError will be raised if a specified album id does not exist in the Spotify music catalog.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-library-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # remove one or more shows from the current user's 'Your Library'.
    showIds:str = '6kAsbP8pxwaU2kPibKTuHE,4rOoJ6Egrf8K2IrywzwOMk,1y3SUbFMUSESC1N43tBleK'
    print('\nRemoving saved show(s) from the current users profile: \n- %s' % showIds.replace(',','\n- '))
    spotify.RemoveShowFavorites(showIds)

    print('\nSuccess - show(s) were removed')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def RemoveTrackFavorites(self, ids: str = None) -> None:

Remove one or more tracks from the current user's 'Your Library'.

This method requires the user-library-modify scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the tracks.
    Maximum: 50 IDs.
    Example: 1kWUud3vY5ij5r62zxpTRy,4eoYKv2kDwJS7gRGh5q6SK If null, the currently playing context uri id value is used.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No error will be raised if a track id in the list does not exist in the user's 'Your Library'.

An SpotifyWebApiError will be raised if a specified album id does not exist in the Spotify music catalog.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-library-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # remove one or more tracks from the current user's 'Your Library'.
    trackIds:str = '1kWUud3vY5ij5r62zxpTRy,2takcwOaAZWiXQijPHIx7B,4eoYKv2kDwJS7gRGh5q6SK'
    print('\nRemoving saved track(s) from the current users profile: \n- %s' % trackIds.replace(',','\n- '))
    spotify.RemoveTrackFavorites(trackIds)

    # remove nowplaying track from the current user's 'Your Library'.
    print('\nRemoving nowplaying track from the current users profile')
    spotify.RemoveTrackFavorites()

    print('\nSuccess - track(s) were removed')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def ReorderPlaylistItems( self, playlistId: str, rangeStart: int, insertBefore: int, rangeLength: int = 1, snapshotId: str = None) -> str:

Reorder items in a user's playlist.

This method requires the playlist-modify-public and playlist-modify-private scope.

Arguments:
  • playlistId (str): The Spotify ID of the playlist. Example: 5AC9ZXA7nJ7oGWO911FuDG
  • rangeStart (int): The position of the first item to be reordered.
    This is a one-offset integer (NOT zero-offset).
  • insertBefore (int): The position where the items should be inserted. To reorder the items to the end of the playlist, simply set insertBefore to the position after the last item.
    This is a one-offset integer (NOT zero-offset).
  • rangeLength (int): The amount of items to be reordered; defaults to 1 if not set.
    The range of items to be reordered begins from the rangeStart position, and includes the rangeLength subsequent items.
  • snapshotId (str): The playlist's snapshot ID against which you want to make the changes.
    If null, the current playlist is updated.
    Example: MTk3LGEzMjUwZGYwODljNmI5ZjAxZTRjZThiOGI4NzZhM2U5M2IxOWUyMDQ Default is null.
Returns:

A snapshot ID for the updated playlist.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

The rangeStart and insertBefore arguments are one-offset values; the underlying Spotify Web API utilizes zero-based offsets for these values. The one-offset values make it much easier (IMHO) to compare the results with the Spotify Web UI, which uses a one-offset track numbering scheme (e.g. the first track is #1, then #2, etc). See the examples below for the various ways to reorder tracks.

The snapshotId argument value will be returned if no items were reordered; otherwise, a new snapshot id value will be returned.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # the following examples were run for a playlist that contains 9 tracks.

    # reorder items in current playlist - move track #5 to position #1 in the list.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    print('\nReordering items in playlist id "%s": \n- move track #5 to position #1 in the list' % (playlistId))
    result:str = spotify.ReorderPlaylistItems(playlistId, 5, 1)
    print('\nPlaylist updated successfully:\n- snapshot ID = "%s"' % result)

    # reorder items in current playlist - move tracks #5,6,7 to position #1 in the list.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    print('\nReordering items in playlist id "%s": \n- move tracks #5,6,7 to position #1 in the list' % (playlistId))
    result:str = spotify.ReorderPlaylistItems(playlistId, 5, 1, 3)
    print('\nPlaylist updated successfully:\n- snapshot ID = "%s"' % result)

    # reorder items in current playlist - move track #7 to position #6 in the list.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    print('\nReordering items in playlist id "%s": \n- move track #7 to position #6 in the list' % (playlistId))
    result:str = spotify.ReorderPlaylistItems(playlistId, 7, 6)
    print('\nPlaylist updated successfully:\n- snapshot ID = "%s"' % result)

    # reorder items in current playlist - move track #5 to position #10 in the list.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    print('\nReordering items in playlist id "%s": \n- move track #5 to position #10 in the list' % (playlistId))
    result:str = spotify.ReorderPlaylistItems(playlistId, 5, 10)
    print('\nPlaylist updated successfully:\n- snapshot ID = "%s"' % result)

except Exception as ex:

    print("** Exception: %s" % str(ex))

def ReplacePlaylistItems(self, playlistId: str, uris: str = None) -> str:

Replace one or more items in a user's playlist. Replacing items in a playlist will overwrite its existing items.

This method can also be used to clear a playlist.

This method requires the playlist-modify-public and playlist-modify-private scope.

Arguments:
  • playlistId (str): The Spotify ID of the playlist. Example: 5AC9ZXA7nJ7oGWO911FuDG
  • uris (str): A comma-separated list of Spotify URIs to replace; can be track or episode URIs.
    Example: spotify:track:4iV5W9uYEdYUVa79Axb7Rh,spotify:episode:512ojhOuo1ktJprKbVcKyQ.
    A maximum of 100 items can be specified in one request.
Returns:

A snapshot ID for the updated playlist.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # replace items in a playlist.
    playlistId:str = '4yptcTKnXjCu3V92tVVafS'
    itemUris:str = 'spotify:track:1kWUud3vY5ij5r62zxpTRy'
    print('\nReplacing items in playlist id "%s" ...\n' % playlistId)
    result:str = spotify.ReplacePlaylistItems(playlistId, itemUris)

    print('Playlist items replaced successfully:\n- snapshot ID = "%s"' % result)

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SaveAlbumFavorites(self, ids: str = None) -> None:

Save one or more albums to the current user's 'Your Library'.

This method requires the user-library-modify scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the albums.
    Maximum: 50 IDs.
    Example: 6vc9OTcyd3hyzabCmsdnwE,382ObEPsp2rxGrnsizN5TX,2noRn2Aes5aoNVsU6iWThc If null, the currently playing track album uri id value is used.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No error will be raised if an album id in the list already exists in the user's 'Your Library'.

An SpotifyWebApiError will be raised if a specified album id does not exist in the Spotify music catalog.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-library-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # save one or more albums to the current user's 'Your Library'.
    albumIds:str = '382ObEPsp2rxGrnsizN5TX,6vc9OTcyd3hyzabCmsdnwE,382ObEPsp2rxGrnsizN5TY'
    print('\nAdding saved album(s) to the current users profile: \n- %s' % albumIds.replace(',','\n- '))
    spotify.SaveAlbumFavorites(albumIds)

    print('\nSuccess - album(s) were added')

    # save nowplaying track album to the current user's 'Your Library'.
    print('\nSaving nowplaying track album to the current users profile')
    spotify.SaveAlbumFavorites()

    print('\nSuccess - album(s) were added')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SaveAudiobookFavorites(self, ids: str) -> None:

Save one or more audiobooks to the current user's 'Your Library'.

This method requires the user-library-modify scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the audiobooks.
    Maximum: 50 IDs.
    Example: 3PFyizE2tGCSRLusl2Qizf,7iHfbu1YPACw6oZPAFJtqe
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No error will be raised if an audiobook id in the list already exists in the user's 'Your Library'.

An SpotifyWebApiError will be raised if a specified album id does not exist in the Spotify music catalog.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-library-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # save one or more audiobooks to the current user's 'Your Library'.
    audiobookIds:str = '3PFyizE2tGCSRLusl2Qizf,7iHfbu1YPACw6oZPAFJtqe'
    print('\nAdding saved audiobook(s) to the current users profile: \n- %s' % audiobookIds.replace(',','\n- '))
    spotify.SaveAudiobookFavorites(audiobookIds)

    print('\nSuccess - audiobook(s) were added')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SaveEpisodeFavorites(self, ids: str) -> None:

Save one or more episodes to the current user's 'Your Library'.

This method requires the user-library-modify scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the episodes.
    Maximum: 50 IDs.
    Example: 6kAsbP8pxwaU2kPibKTuHE,4rOoJ6Egrf8K2IrywzwOMk
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No error will be raised if an episode id in the list already exists in the user's 'Your Library'.

An SpotifyWebApiError will be raised if a specified album id does not exist in the Spotify music catalog.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-library-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # save one or more episodes to the current user's 'Your Library'.
    episodeIds:str = '1hPX5WJY6ja6yopgVPBqm4,3F97boSWlXi8OzuhWClZHQ'
    print('\nAdding saved episode(s) to the current users profile: \n- %s' % episodeIds.replace(',','\n- '))
    spotify.SaveEpisodeFavorites(episodeIds)

    print('\nSuccess - episode(s) were added')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SaveShowFavorites(self, ids: str) -> None:

Save one or more shows to the current user's 'Your Library'.

This method requires the user-library-modify scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the shows.
    Maximum: 50 IDs.
    Example: 6kAsbP8pxwaU2kPibKTuHE,4rOoJ6Egrf8K2IrywzwOMk
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No error will be raised if an show id in the list already exists in the user's 'Your Library'.

An SpotifyWebApiError will be raised if a specified album id does not exist in the Spotify music catalog.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-library-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # save one or more shows to the current user's 'Your Library'.
    showIds:str = '7bnjJ7Va1nM07Um4Od55dW,6cRP8gclqWDfA9pkKsqDPv,4HHvTURWViZE5vYuSt0ldG'
    print('\nAdding saved show(s) to the current users profile: \n- %s' % showIds.replace(',','\n- '))
    spotify.SaveShowFavorites(showIds)

    print('\nSuccess - show(s) were added')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SaveTrackFavorites(self, ids: str = None) -> None:

Save one or more tracks to the current user's 'Your Library'.

This method requires the user-library-modify scope.

Arguments:
  • ids (str): A comma-separated list of the Spotify IDs for the tracks.
    Maximum: 50 IDs.
    Example: 6vc9OTcyd3hyzabCmsdnwE,382ObEPsp2rxGrnsizN5TX,2noRn2Aes5aoNVsU6iWThc If null, the currently playing context uri id value is used.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No error will be raised if a track id in the list already exists in the user's 'Your Library'.

An SpotifyWebApiError will be raised if a specified album id does not exist in the Spotify music catalog.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-library-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # save one or more tracks to the current user's 'Your Library'.
    trackIds:str = '1kWUud3vY5ij5r62zxpTRy,2takcwOaAZWiXQijPHIx7B,4eoYKv2kDwJS7gRGh5q6SK'
    print('\nAdding saved track(s) to the current users profile: \n- %s' % trackIds.replace(',','\n- '))
    spotify.SaveTrackFavorites(trackIds)

    # save currently playing track to the current user's 'Your Library'.
    print('\nAdding nowplaying track to the current users profile')
    spotify.SaveTrackFavorites()

    print('\nSuccess - track(s) were added')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SearchAlbums( self, criteria: str, limit: int = 20, offset: int = 0, market: str = None, includeExternal: str = None, limitTotal: int = None) -> spotifywebapipython.models.searchresponse.SearchResponse:

Get Spotify catalog information about Albums that match a keyword string.

Arguments:
  • criteria (str): Your search query.
    You can narrow down your search using field filters.
    The available filters are album, artist, track, year, upc, tag:hipster, tag:new, isrc, and genre. Each field filter only applies to certain result types.
    The artist and year filters can be used while searching albums, artists and tracks. You can filter on a single year or a range (e.g. 1955-1960).
    The album filter can be used while searching albums and tracks.
    The genre filter can be used while searching artists and tracks.
    The isrc and track filters can be used while searching tracks.
    The upc, tag:new and tag:hipster filters can only be used while searching albums. The tag:new filter will return albums released in the past two weeks and tag:hipster can be used to return only albums with the lowest 10% popularity.
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item). Range: 0 to 1000.
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • includeExternal (str): If "audio" is specified it signals that the client can play externally hosted audio content, and marks the content as playable in the response. By default externally hosted audio content is marked as unplayable in the response.
    Allowed values: "audio"
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A SearchResponse object that contains the search results.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Note that Spotify Web API automatically limits you to 1,000 max entries per type that can be returned with a search.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Albums that match a keyword string.
    criteria:str = 'Welcome to the New'
    print('\nSearching for Albums - criteria: "%s" ...\n' % criteria)
    searchResponse:SearchResponse = spotify.SearchAlbums(criteria, limit=25)

    # display search response details.
    print(str(searchResponse))
    print('')

    # save initial search response total, as search next page response total 
    # will change with each page retrieved.  this is odd behavior, as it seems
    # that the spotify web api is returning a new result set each time rather 
    # than working off of a cached result set.
    pageObjInitialTotal:int = searchResponse.Albums.Total

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # only display album results for this example.
        pageObj:AlbumPageSimplified = searchResponse.Albums

        # display paging details.
        print(str(pageObj))
        print('')
        print('Albums in this page of results:')

        # display album details.
        album:AlbumSimplified
        for album in pageObj.Items:
            print('- "{name}" ({uri})'.format(name=album.Name, uri=album.Uri))

        # for testing - don't return 1000 results!  
        # comment the following 3 lines of code if you want ALL results.
        if pageObj.Offset + pageObj.Limit >= 75:
            print('\n*** Stopping paging loop after 75 entries for testing.')
            break

        # anymore page results?
        if (pageObj.Next is None) or ((pageObj.Offset + pageObj.Limit) > pageObjInitialTotal):
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            searchResponse = spotify.SearchAlbums(criteria, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Albums that match a keyword string.
    criteria:str = 'Welcome to the New'
    print('\nSearching for Albums - criteria: "%s" ...\n' % criteria)
    pageObj:SearchResponse = spotify.SearchAlbums(criteria, limitTotal=75)

    # display paging details.
    print(str(pageObj))
    print(str(pageObj.Albums))
    print('\nAlbums in this page of results (%d items):' % pageObj.Albums.ItemsCount)

    # display album details.
    album:AlbumSimplified
    for album in pageObj.Albums.Items:
        print('- "{name}" ({uri})'.format(name=album.Name, uri=album.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SearchArtists( self, criteria: str, limit: int = 20, offset: int = 0, market: str = None, includeExternal: str = None, limitTotal: int = None) -> spotifywebapipython.models.searchresponse.SearchResponse:

Get Spotify catalog information about Artists that match a keyword string.

Arguments:
  • criteria (str): Your search query.
    You can narrow down your search using field filters.
    The available filters are album, artist, track, year, upc, tag:hipster, tag:new, isrc, and genre. Each field filter only applies to certain result types.
    The artist and year filters can be used while searching albums, artists and tracks. You can filter on a single year or a range (e.g. 1955-1960).
    The album filter can be used while searching albums and tracks.
    The genre filter can be used while searching artists and tracks.
    The isrc and track filters can be used while searching tracks.
    The upc, tag:new and tag:hipster filters can only be used while searching albums. The tag:new filter will return albums released in the past two weeks and tag:hipster can be used to return only albums with the lowest 10% popularity.
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item). Range: 0 to 1000.
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • includeExternal (str): If "audio" is specified it signals that the client can play externally hosted audio content, and marks the content as playable in the response. By default externally hosted audio content is marked as unplayable in the response.
    Allowed values: "audio"
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A SearchResponse object that contains the search results.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Note that Spotify Web API automatically limits you to 1,000 max entries per type that can be returned with a search.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Artists that match a keyword string.
    criteria:str = 'MercyMe'
    print('\nSearching for Artists - criteria: "%s" ...\n' % criteria)
    searchResponse:SearchResponse = spotify.SearchArtists(criteria, limit=25)

    # display search response details.
    print(str(searchResponse))
    print('')

    # save initial search response total, as search next page response total 
    # will change with each page retrieved.  this is odd behavior, as it seems
    # that the spotify web api is returning a new result set each time rather 
    # than working off of a cached result set.
    pageObjInitialTotal:int = searchResponse.Artists.Total

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # only display artist results for this example.
        pageObj:ArtistPage = searchResponse.Artists

        # display paging details.
        print(str(pageObj))
        print('\nArtists in this page of results:')

        # display artist details.
        artist:ArtistPage
        for artist in pageObj.Items:
            print('- "{name}" ({uri})'.format(name=artist.Name, uri=artist.Uri))

        # for testing - don't return 1000 results!  
        # comment the following 3 lines of code if you want ALL results.
        if pageObj.Offset + pageObj.Limit >= 75:
            print('\n*** Stopping paging loop after 75 entries for testing.')
            break

        # anymore page results?
        if (pageObj.Next is None) or ((pageObj.Offset + pageObj.Limit) > pageObjInitialTotal):
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            searchResponse = spotify.SearchArtists(criteria, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Artists that match a keyword string.
    criteria:str = 'MercyMe'
    print('\nSearching for Artists - criteria: "%s" ...\n' % criteria)
    pageObj:SearchResponse = spotify.SearchArtists(criteria, limitTotal=75)

    # display paging details.
    print(str(pageObj))
    print(str(pageObj.Artists))
    print('\nArtists in this page of results (%d items):' % pageObj.Artists.ItemsCount)

    # display artist details.
    artist:Artist
    for artist in pageObj.Artists.Items:
        print('- "{name}" ({uri})'.format(name=artist.Name, uri=artist.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SearchAudiobooks( self, criteria: str, limit: int = 20, offset: int = 0, market: str = None, includeExternal: str = None, limitTotal: int = None) -> spotifywebapipython.models.searchresponse.SearchResponse:

Get Spotify catalog information about Audiobooks that match a keyword string.

Arguments:
  • criteria (str): Your search query.
    You can narrow down your search using field filters.
    The available filters are album, artist, track, year, upc, tag:hipster, tag:new, isrc, and genre. Each field filter only applies to certain result types.
    The artist and year filters can be used while searching albums, artists and tracks. You can filter on a single year or a range (e.g. 1955-1960).
    The album filter can be used while searching albums and tracks.
    The genre filter can be used while searching artists and tracks.
    The isrc and track filters can be used while searching tracks.
    The upc, tag:new and tag:hipster filters can only be used while searching albums. The tag:new filter will return albums released in the past two weeks and tag:hipster can be used to return only albums with the lowest 10% popularity.
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item). Range: 0 to 1000.
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • includeExternal (str): If "audio" is specified it signals that the client can play externally hosted audio content, and marks the content as playable in the response. By default externally hosted audio content is marked as unplayable in the response.
    Allowed values: "audio"
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A SearchResponse object that contains the search results.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Audiobooks are only available within the US, UK, Canada, Ireland, New Zealand and Australia markets.

Note that Spotify Web API automatically limits you to 1,000 max entries per type that can be returned with a search.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Audiobooks that match a keyword string.
    criteria:str = 'Terry Brooks'
    print('\nSearching for Audiobooks - criteria: "%s" ...\n' % criteria)
    searchResponse:SearchResponse = spotify.SearchAudiobooks(criteria, limit=25)

    # display search response details.
    print(str(searchResponse))
    print('')

    # save initial search response total, as search next page response total 
    # will change with each page retrieved.  this is odd behavior, as it seems
    # that the spotify web api is returning a new result set each time rather 
    # than working off of a cached result set.
    pageObjInitialTotal:int = searchResponse.Audiobooks.Total

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # only display audiobook results for this example.
        pageObj:AudiobookPageSimplified = searchResponse.Audiobooks

        # display paging details.
        print(str(pageObj))
        print('\nAudiobooks in this page of results:')

        # display audiobook details.
        audiobook:AudiobookSimplified
        for audiobook in pageObj.Items:
            print('- "{name}" ({uri})'.format(name=audiobook.Name, uri=audiobook.Uri))

        # for testing - don't return 1000 results!  
        # comment the following 3 lines of code if you want ALL results.
        if pageObj.Offset + pageObj.Limit >= 75:
            print('\n*** Stopping paging loop after 75 entries for testing.')
            break

        # anymore page results?
        if (pageObj.Next is None) or ((pageObj.Offset + pageObj.Limit) > pageObjInitialTotal):
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            searchResponse = spotify.SearchAudiobooks(criteria, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Audiobooks that match a keyword string.
    criteria:str = 'Terry Brooks'
    print('\nSearching for Audiobooks - criteria: "%s" ...\n' % criteria)
    pageObj:SearchResponse = spotify.SearchAudiobooks(criteria, limitTotal=75)

    # display paging details.
    print(str(pageObj))
    print(str(pageObj.Audiobooks))
    print('\nAudiobooks in this page of results (%d items):' % pageObj.Audiobooks.ItemsCount)

    # display audiobook details.
    audiobook:Audiobook
    for audiobook in pageObj.Audiobooks.Items:
        print('- "{name}" ({uri})'.format(name=audiobook.Name, uri=audiobook.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SearchEpisodes( self, criteria: str, limit: int = 20, offset: int = 0, market: str = None, includeExternal: str = None, limitTotal: int = None) -> spotifywebapipython.models.searchresponse.SearchResponse:

Get Spotify catalog information about Episodes that match a keyword string.

Arguments:
  • criteria (str): Your search query.
    You can narrow down your search using field filters.
    The available filters are album, artist, track, year, upc, tag:hipster, tag:new, isrc, and genre. Each field filter only applies to certain result types.
    The artist and year filters can be used while searching albums, artists and tracks. You can filter on a single year or a range (e.g. 1955-1960).
    The album filter can be used while searching albums and tracks.
    The genre filter can be used while searching artists and tracks.
    The isrc and track filters can be used while searching tracks.
    The upc, tag:new and tag:hipster filters can only be used while searching albums. The tag:new filter will return albums released in the past two weeks and tag:hipster can be used to return only albums with the lowest 10% popularity.
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item). Range: 0 to 1000.
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • includeExternal (str): If "audio" is specified it signals that the client can play externally hosted audio content, and marks the content as playable in the response. By default externally hosted audio content is marked as unplayable in the response.
    Allowed values: "audio"
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A SearchResponse object that contains the search results.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Note that Spotify Web API automatically limits you to 1,000 max entries per type that can be returned with a search.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Episodes that match a keyword string.
    criteria:str = 'The LOL Podcast'
    print('\nSearching for Episodes - criteria: "%s" ...\n' % criteria)
    searchResponse:SearchResponse = spotify.SearchEpisodes(criteria, limit=25)

    # display search response details.
    print(str(searchResponse))
    print('')

    # save initial search response total, as search next page response total 
    # will change with each page retrieved.  this is odd behavior, as it seems
    # that the spotify web api is returning a new result set each time rather 
    # than working off of a cached result set.
    pageObjInitialTotal:int = searchResponse.Episodes.Total

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # only display episode results for this example.
        pageObj:EpisodePageSimplified = searchResponse.Episodes

        # display paging details.
        print(str(pageObj))
        print('\nEpisodes in this page of results:')

        # display episode details.
        episode:EpisodeSimplified
        for episode in pageObj.Items:
            print('- "{name}" ({uri})'.format(name=episode.Name, uri=episode.Uri))

        # for testing - don't return 1000 results!  
        # comment the following 3 lines of code if you want ALL results.
        if pageObj.Offset + pageObj.Limit >= 75:
            print('\n*** Stopping paging loop after 75 entries for testing.')
            break

        # anymore page results?
        if (pageObj.Next is None) or ((pageObj.Offset + pageObj.Limit) > pageObjInitialTotal):
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            searchResponse = spotify.SearchEpisodes(criteria, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Episodes that match a keyword string.
    criteria:str = 'The LOL Podcast'
    print('\nSearching for Episodes - criteria: "%s" ...\n' % criteria)
    pageObj:SearchResponse = spotify.SearchEpisodes(criteria, limitTotal=75)

    # display paging details.
    print(str(pageObj))
    print(str(pageObj.Episodes))
    print('\nEpisodes in this page of results (%d items):' % pageObj.Episodes.ItemsCount)

    # display episode details.
    episode:EpisodeSimplified
    for episode in pageObj.Episodes.Items:
        print('- "{name}" ({uri})'.format(name=episode.Name, uri=episode.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SearchPlaylists( self, criteria: str, limit: int = 20, offset: int = 0, market: str = None, includeExternal: str = None, limitTotal: int = None) -> spotifywebapipython.models.searchresponse.SearchResponse:

Get Spotify catalog information about Playlists that match a keyword string.

Arguments:
  • criteria (str): Your search query.
    You can narrow down your search using field filters.
    The available filters are album, artist, track, year, upc, tag:hipster, tag:new, isrc, and genre. Each field filter only applies to certain result types.
    The artist and year filters can be used while searching albums, artists and tracks. You can filter on a single year or a range (e.g. 1955-1960).
    The album filter can be used while searching albums and tracks.
    The genre filter can be used while searching artists and tracks.
    The isrc and track filters can be used while searching tracks.
    The upc, tag:new and tag:hipster filters can only be used while searching albums. The tag:new filter will return albums released in the past two weeks and tag:hipster can be used to return only albums with the lowest 10% popularity.
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item). Range: 0 to 1000.
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • includeExternal (str): If "audio" is specified it signals that the client can play externally hosted audio content, and marks the content as playable in the response. By default externally hosted audio content is marked as unplayable in the response.
    Allowed values: "audio"
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A SearchResponse object that contains the search results.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Note that Spotify Web API automatically limits you to 1,000 max entries per type that can be returned with a search.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Playlists that match a keyword string.
    criteria:str = 'MercyMe'
    print('\nSearching for Playlists - criteria: "%s" ...\n' % criteria)
    searchResponse:SearchResponse = spotify.SearchPlaylists(criteria, limit=25)

    # display search response details.
    print(str(searchResponse))
    print('')

    # save initial search response total, as search next page response total 
    # will change with each page retrieved.  this is odd behavior, as it seems
    # that the spotify web api is returning a new result set each time rather 
    # than working off of a cached result set.
    pageObjInitialTotal:int = searchResponse.Playlists.Total

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # only display playlist results for this example.
        pageObj:PlaylistPageSimplified = searchResponse.Playlists

        # display paging details.
        print(str(pageObj))
        print('\nPlaylists in this page of results:')

        # display playlist details.
        playlist:PlaylistSimplified
        for playlist in pageObj.Items:
            print('- "{name}" ({uri})'.format(name=playlist.Name, uri=playlist.Uri))

        # for testing - don't return 1000 results!  
        # comment the following 3 lines of code if you want ALL results.
        if pageObj.Offset + pageObj.Limit >= 75:
            print('\n*** Stopping paging loop after 75 entries for testing.')
            break

        # anymore page results?
        if (pageObj.Next is None) or ((pageObj.Offset + pageObj.Limit) > pageObjInitialTotal):
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            searchResponse = spotify.SearchPlaylists(criteria, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Playlists that match a keyword string.
    criteria:str = 'MercyMe'
    print('\nSearching for Playlists - criteria: "%s" ...\n' % criteria)
    pageObj:SearchResponse = spotify.SearchPlaylists(criteria, limitTotal=75)

    # display paging details.
    print(str(pageObj))
    print(str(pageObj.Playlists))
    print('\nPlaylists in this page of results (%d items):' % pageObj.Playlists.ItemsCount)

    # display playlist details.
    playlist:PlaylistSimplified
    for playlist in pageObj.Playlists.Items:
        print('- "{name}" ({uri})'.format(name=playlist.Name, uri=playlist.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SearchShows( self, criteria: str, limit: int = 20, offset: int = 0, market: str = None, includeExternal: str = None, limitTotal: int = None) -> spotifywebapipython.models.searchresponse.SearchResponse:

Get Spotify catalog information about Shows that match a keyword string.

Arguments:
  • criteria (str): Your search query.
    You can narrow down your search using field filters.
    The available filters are album, artist, track, year, upc, tag:hipster, tag:new, isrc, and genre. Each field filter only applies to certain result types.
    The artist and year filters can be used while searching albums, artists and tracks. You can filter on a single year or a range (e.g. 1955-1960).
    The album filter can be used while searching albums and tracks.
    The genre filter can be used while searching artists and tracks.
    The isrc and track filters can be used while searching tracks.
    The upc, tag:new and tag:hipster filters can only be used while searching albums. The tag:new filter will return albums released in the past two weeks and tag:hipster can be used to return only albums with the lowest 10% popularity.
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item). Range: 0 to 1000.
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • includeExternal (str): If "audio" is specified it signals that the client can play externally hosted audio content, and marks the content as playable in the response. By default externally hosted audio content is marked as unplayable in the response.
    Allowed values: "audio"
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A SearchResponse object that contains the search results.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Note that Spotify Web API automatically limits you to 1,000 max entries per type that can be returned with a search.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Shows that match a keyword string.
    # note - use an Authorization type of token or the `market` argument for this
    # method, otherwise the item result are all null.
    criteria:str = 'Joe Rogan'
    print('\nSearching for Shows - criteria: "%s" ...\n' % criteria)
    searchResponse:SearchResponse = spotify.SearchShows(criteria, limit=25)

    # display search response details.
    print(str(searchResponse))
    print('')

    # save initial search response total, as search next page response total 
    # will change with each page retrieved.  this is odd behavior, as it seems
    # that the spotify web api is returning a new result set each time rather 
    # than working off of a cached result set.
    pageObjInitialTotal:int = searchResponse.Shows.Total

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # only display show results for this example.
        pageObj:ShowPageSimplified = searchResponse.Shows

        # display paging details.
        print(str(pageObj))
        print('\nShows in this page of results:')

        # display show details.
        show:ShowSimplified
        for show in pageObj.Items:
            print('- "{name}" ({uri})'.format(name=show.Name, uri=show.Uri))

        # for testing - don't return 1000 results!  
        # comment the following 3 lines of code if you want ALL results.
        if pageObj.Offset + pageObj.Limit >= 75:
            print('\n*** Stopping paging loop after 75 entries for testing.')
            break

        # anymore page results?
        if (pageObj.Next is None) or ((pageObj.Offset + pageObj.Limit) > pageObjInitialTotal):
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            searchResponse = spotify.SearchShows(criteria, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Shows that match a keyword string.
    # note - use an Authorization type of token or the `market` argument for this
    # method, otherwise the item result are all null.
    criteria:str = 'Joe Rogan'
    print('\nSearching for Shows - criteria: "%s" ...\n' % criteria)
    pageObj:SearchResponse = spotify.SearchShows(criteria, limitTotal=75)

    # display paging details.
    print(str(pageObj))
    print(str(pageObj.Shows))
    print('\nShows in this page of results (%d items):' % pageObj.Shows.ItemsCount)

    # display show details.
    show:ShowSimplified
    for show in pageObj.Shows.Items:
        print('- "{name}" ({uri})'.format(name=show.Name, uri=show.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SearchTracks( self, criteria: str, limit: int = 20, offset: int = 0, market: str = None, includeExternal: str = None, limitTotal: int = None) -> spotifywebapipython.models.searchresponse.SearchResponse:

Get Spotify catalog information about Tracks that match a keyword string.

Arguments:
  • criteria (str): Your search query.
    You can narrow down your search using field filters.
    The available filters are album, artist, track, year, upc, tag:hipster, tag:new, isrc, and genre. Each field filter only applies to certain result types.
    The artist and year filters can be used while searching albums, artists and tracks. You can filter on a single year or a range (e.g. 1955-1960).
    The album filter can be used while searching albums and tracks.
    The genre filter can be used while searching artists and tracks.
    The isrc and track filters can be used while searching tracks.
    The upc, tag:new and tag:hipster filters can only be used while searching albums. The tag:new filter will return albums released in the past two weeks and tag:hipster can be used to return only albums with the lowest 10% popularity.
  • limit (int): The maximum number of items to return in a page of items.
    Default: 20, Range: 1 to 50.
  • offset (int): The page index offset of the first item to return.
    Use with limit to get the next set of items.
    Default: 0 (the first item). Range: 0 to 1000.
  • market (str): An ISO 3166-1 alpha-2 country code. If a country code is specified, only content that is available in that market will be returned. If a valid user access token is specified in the request header, the country associated with the user account will take priority over this parameter.
    Note: If neither market or user country are provided, the content is considered unavailable for the client.
    Users can view the country that is associated with their account in the account settings.
    Example: ES
  • includeExternal (str): If "audio" is specified it signals that the client can play externally hosted audio content, and marks the content as playable in the response. By default externally hosted audio content is marked as unplayable in the response.
    Allowed values: "audio"
  • limitTotal (int): The maximum number of items to return for the request.
    If specified, this argument overrides the limit and offset argument values and paging is automatically used to retrieve all available items up to the maximum number specified.
    Default: None (disabled)
Returns:

A SearchResponse object that contains the search results.

Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Note that Spotify Web API automatically limits you to 1,000 max entries per type that can be returned with a search.

Sample Code - Manual Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Tracks that match a keyword string.
    criteria:str = 'Flawless'
    print('\nSearching for Tracks - criteria: "%s" ...\n' % criteria)
    searchResponse:SearchResponse = spotify.SearchTracks(criteria, limit=25)

    # display search response details.
    print(str(searchResponse))
    print('')

    # save initial search response total, as search next page response total 
    # will change with each page retrieved.  this is odd behavior, as it seems
    # that the spotify web api is returning a new result set each time rather 
    # than working off of a cached result set.
    pageObjInitialTotal:int = searchResponse.Tracks.Total

    # handle pagination, as spotify limits us to a set # of items returned per response.
    while True:

        # only display track results for this example.
        pageObj:TrackPage = searchResponse.Tracks

        # for testing - don't return 1000 results!  
        # comment the following 2 lines of code if you want ALL results.
        if pageObj.Offset + pageObj.Limit > 75:
            break

        # display paging details.
        print(str(pageObj))
        print('')
        print('Tracks in this page of results:')

        # display track details.
        track:Track
        for track in pageObj.Items:
            print('- "{name}" ({uri})'.format(name=track.Name, uri=track.Uri))

        # anymore page results?
        if (pageObj.Next is None) or ((pageObj.Offset + pageObj.Limit) > pageObjInitialTotal):
            # no - all pages were processed.
            break
        else:
            # yes - retrieve the next page of results.
            print('\nGetting next page of %d items ...\n' % (pageObj.Limit))
            searchResponse = spotify.SearchTracks(criteria, offset=pageObj.Offset + pageObj.Limit, limit=pageObj.Limit)

except Exception as ex:

    print("** Exception: %s" % str(ex))

Sample Code - Auto Paging

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    CLIENT_ID:str = 'your_client_id'
    CLIENT_SECRET:str = 'your_client_secret'

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify client credentials access token (no scope, public data use only).
    spotify.SetAuthTokenClientCredentials(CLIENT_ID, CLIENT_SECRET)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # get Spotify catalog information about Tracks that match a keyword string.
    criteria:str = 'Parliament Funkadelic'
    print('\nSearching for Tracks - criteria: "%s" ...\n' % criteria)
    pageObj:SearchResponse = spotify.SearchTracks(criteria, limitTotal=75)

    # display paging details.
    print(str(pageObj))
    print(str(pageObj.Tracks))
    print('\nTracks in this page of results (%d items):' % pageObj.Tracks.ItemsCount)

    # display track details.
    track:Track
    for track in pageObj.Tracks.Items:
        print('- "{name}" ({uri})'.format(name=track.Name, uri=track.Uri))

except Exception as ex:

    print("** Exception: %s" % str(ex))

def SetAuthTokenAuthorizationCode( self, clientId: str, clientSecret: str, scope: str = None, tokenProfileId: str = None, forceAuthorize: bool = False, redirectUriHost: str = 'localhost', redirectUriPort: int = 8080) -> None:

Generates a new Authorization Code type of authorization token used to access the Spotify Web API.

Arguments:
  • clientId (str): The unique identifier of the application.
  • clientSecret (str): The client secret, which is the key you will use to authorize your Web API or SDK calls.
  • scope (str | list[str]): A space-delimited list of scope identifiers you wish to request access to.
    If no scope is specified, authorization will be granted only to access publicly available information; that is, only information normally visible in the Spotify desktop, web, and mobile players.
    Default is None.
  • tokenProfileId (str): Profile identifier used when loading / storing the token to disk.
    A null value will default to Shared.
    Default: Shared
  • forceAuthorize (bool): True to force authorization, even if we already have a token.
    This can be useful if dynamically changing scope.
    Default is False.
  • redirectUriHost (str): The value to use for the host portion of the redirect URI.
    Default is 'localhost'.
  • redirectUriPort (int): The value to use for the port portion of the redirect URI. You can specify a single port as an integer, or a port range as a list (e.g. [8080,8090]). If a port range is specified, then the logic will loop through the port range looking for an available port to use.
    Default is 8080.
Raises:
  • SpotifApiError: If the method fails for any reason.

The authorization code flow is suitable for long-running applications (e.g. web and mobile apps) where the user grants permission only once. If you are using the authorization code flow in a mobile app, or any other type of application where the client secret can't be safely stored, then you should use the SetAuthTokenAuthorizationCode method.

This allows you to specify scope values, which allow more granular access to data that is not public (e.g. a user's email, playlist, profile, etc). The user gets final approval for the requested scope(s) when they login to approve the access, as the login form will show what scope they are about to approve. The user also has the ability to remove the application access at any time, in the event that the client is abusing the given scope privileges.

The authorization flow will attempt to automatically open the Spotify authorization URL in a new browser tab (using the default browser). This will force the user to login to Spotify, if not already logged in. Spotify then displays to the user the requested access (scope) that your application is requesting, and allows them to accept / reject it. The flow will start a local web server to listen for the user response to the authorization request. Once authorization is complete, the Spotify authorization server will redirect the user's browser to the local web server with the response. The web server will get the authorization code from the response and shutdown. The authorization code is then exchanged for a Spotify authorization token.

Note that you must have 'http://localhost:8080/' in the Redirect URI allowlist that you specified when you registered your application in the Spotify Developer Portal. The redirect URI is case-sensitive, and must contain the trailing slash. You will need to adjust the redirect URI value if you specify custom values using the redirectUriHost and redirectUriPort arguments.

def SetAuthTokenAuthorizationCodePKCE( self, clientId: str, scope: str = None, tokenProfileId: str = None, forceAuthorize: bool = False, redirectUriHost: str = 'localhost', redirectUriPort: int = 8080) -> None:

Generates a new Authorization Code PKCE type of authorization token used to access the Spotify Web API.

Arguments:
  • clientId (str): The unique identifier of the application.
  • scope (str | list[str]): A space-delimited list of scope identifiers you wish to request access to.
    If no scope is specified, authorization will be granted only to access publicly available information; that is, only information normally visible in the Spotify desktop, web, and mobile players.
    Default is None.
  • tokenProfileId (str): Profile identifier used when loading / storing the token to disk.
    A null value will default to Shared.
    Default: Shared
  • forceAuthorize (bool): True to force authorization, even if we already have a token.
    This can be useful if dynamically changing scope.
    Default is False.
  • redirectUriHost (str): The value to use for the host portion of the redirect URI.
    Default is 'localhost'.
  • redirectUriPort (int): The value to use for the port portion of the redirect URI. You can specify a single port as an integer, or a port range as a list (e.g. [8080,8090]). If a port range is specified, then the logic will loop through the port range looking for an available port to use.
    Default is 8080.
Raises:
  • SpotifApiError: If the method fails for any reason.

The authorization code with PKCE is the recommended authorization type if you are implementing authorization in a mobile app, single page web app, or any other type of application where the client secret can't be safely stored.

This allows you to specify scope values, which allow more granular access to data that is not public (e.g. a user's email, playlist, profile, etc). The user gets final approval for the requested scope(s) when they login to approve the access, as the login form will show what scope they are about to approve. The user also has the ability to remove the application access at any time, in the event that the client is abusing the given scope privileges.

The authorization flow will attempt to automatically open the Spotify authorization URL in a new browser tab (using the default browser). This will force the user to login to Spotify, if not already logged in. Spotify then displays to the user the requested access (scope) that your application is requesting, and allows them to accept / reject it. The flow will start a local web server to listen for the user response to the authorization request. Once authorization is complete, the Spotify authorization server will redirect the user's browser to the local web server with the response. The web server will get the authorization code from the response and shutdown. The authorization code is then exchanged for a Spotify authorization token.

Note that you must have 'http://localhost:8080/' in the Redirect URI allowlist that you specified when you registered your application in the Spotify Developer Portal. The redirect URI is case-sensitive, and must contain the trailing slash. You will need to adjust the redirect URI value if you specify custom values using the redirectUriHost and redirectUriPort arguments.

def SetAuthTokenClientCredentials( self, clientId: str, clientSecret: str, tokenProfileId: str = None) -> None:

Generates a new client credentials type of authorization token used to access the Spotify Web API.

Arguments:
  • clientId (str): The unique identifier of the application.
  • clientSecret (str): The application's secret key, used to authorize your Web API or SDK calls.
  • tokenProfileId (str): Profile identifier used when loading / storing the token to disk.
    A null value will default to Shared.
    Default: Shared

The Client Credentials flow is used in server-to-server authentication. Since this flow does not include authorization, only endpoints that do not access user information can be accessed.

There is also no persistant token storage, as a new token is retrieved when this method is called initially, and when the token needs to be refreshed.

def SetAuthTokenFromToken(self, clientId: str, token: dict, tokenProfileId: str = None) -> None:

Uses an OAuth2 authorization token that was generated from an external provider to access the Spotify Web API.

Arguments:
  • clientId (str): The unique identifier of the application.
  • token (dict): A dictionary object that contains OAuth2 token data.
  • tokenProfileId (str): Profile identifier used when loading / storing the token to disk.
    A null value will default to Shared.
    Default: Shared
Raises:
  • SpotifApiError: If the method fails for any reason.

Make sure you have the tokenUpdater argument supplied on the class constructor so that token updates are passed on to the external provider.

def ToString(self) -> str:

Returns a displayable string representation of the class.

def UnfollowArtists(self, ids: str = None) -> None:

Remove the current user as a follower of one or more artists.

This method requires the user-follow-modify scope.

Arguments:
  • ids (str): A comma-separated list of Spotify artist IDs.
    A maximum of 50 IDs can be sent in one request. Example: 2CIMQHirSU0MQqyYHq0eOx,1IQ2e1buppatiN1bxUVkrk If null, the currently playing track artist uri id value is used.
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No exception is raised if a specified artist id is not being followed.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-follow-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # remove the current user as a follower of one or more artists.
    ids:str = '2CIMQHirSU0MQqyYHq0eOx,1IQ2e1buppatiN1bxUVkrk'
    print('\nStop following these artists:\n- %s\n' % (ids.replace(',','\n- ')))
    spotify.UnfollowArtists(ids)

    print('Success - artists are now unfollowed')

    # remove the current user as a follower of the nowplaying artist.
    print('\nStop following the nowplaying artist')
    spotify.UnfollowArtists()

    print('Success - artists are now unfollowed')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def UnfollowPlaylist(self, playlistId: str) -> None:

Remove the current user as a follower of a playlist.

This method requires the playlist-modify-public and playlist-modify-private scope.

Arguments:
  • playlistId (str): The Spotify ID of the playlist.
    Example: 3cEYpjA9oz9GiPac4AsH4n
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-read-email',
        'user-library-read',
        'user-library-modify',
        'playlist-modify-private',
        'playlist-modify-public'
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # remove the current user as a follower of a playlist.
    playlistId:str = '3cEYpjA9oz9GiPac4AsH4n'
    print('\nUnfollowing playlist id "%s" ...' % playlistId)
    spotify.UnfollowPlaylist(playlistId)

    print('\nSuccess - playlist is now unfollowed')

except Exception as ex:

    print("** Exception: %s" % str(ex))

def UnfollowUsers(self, ids: str) -> None:

Remove the current user as a follower of one or more users.

This method requires the user-follow-modify scope.

Arguments:
  • ids (str): A comma-separated list of Spotify user IDs.
    A maximum of 50 IDs can be sent in one request. Example: smedjan
Raises:
  • SpotifyWebApiError: If the Spotify Web API request was for a non-authorization service and the response contains error information.
  • SpotifApiError: If the method fails for any other reason.

No exception is raised if a specified user id is not being followed.

Sample Code

from spotifywebapipython import *
from spotifywebapipython.models import *

try:

    # this sample requires an authorization token, as it requires security scope to accesses user data.

    CLIENT_ID:str = 'your_client_id'
    SPOTIFY_SCOPES:list = \
    [
        'user-follow-modify',
        'user-read-email',
    ]

    # create new spotify client instance.
    spotify:SpotifyClient = SpotifyClient()

    # generate a spotify authorization code with PKCE access token (with scope, private and public data use).
    spotify.SetAuthTokenAuthorizationCodePKCE(CLIENT_ID, SPOTIFY_SCOPES)
    print('\nAuth Token:\n Type="%s"\n Scope="%s"' % (spotify.AuthToken.AuthorizationType, str(spotify.AuthToken.Scope)))
    print('\nUser:\n DisplayName="%s"\n EMail="%s"' % (spotify.UserProfile.DisplayName, spotify.UserProfile.EMail))

    # remove the current user as a follower of one or more users.
    ids:str = 'smedjan'
    print('\nStop following this user(s):\n- %s\n' % (ids.replace(',','\n- ')))
    spotify.UnfollowUsers(ids)

    print('Success - user(s) is now unfollowed')

except Exception as ex:

    print("** Exception: %s" % str(ex))