SpotifyClient¶
-
class
spotify_client.SpotifyClient(client_id: str = None, secret_key: str = None, identifier: str = 'SpotifyClient')¶ Wrapper around the Spotify API
- Variables
client_id – Spotify client ID used for authenticating with API
secret_key – Spotify secret key used for authenticating with API
identifier – Identifier to include in log messages for identifying requests
-
_make_spotify_request(method: str, url: str, params: dict = None, data: Union[dict, bytes] = None, json: dict = None, headers: dict = None) → dict¶ Make a request to the Spotify API and return the JSON response
- Parameters
method – (str) HTTP method to use when sending request
url – (str) URL to send request to
params – (dict) GET query params to add to URL
data – (dict or bytes) POST data to send in request
json – (dict) JSON data to send in request
headers – (dict) Headers to include in request
- Returns
(dict) Response content
- Raises
SpotifyException if request was unsuccessful
- Raises
ClientException if unexpected error encountered
-
add_songs_to_playlist(auth_code: str, playlist_id: str, songs: list) → None¶ Add songs to a specified playlist
- Parameters
auth_code – (str) Access token for user from Spotify
playlist_id – (str) Spotify playlist ID to add songs to
songs – (list) Collection of Spotify track URIs to add to playlist
-
add_track_to_saved_songs(auth_code: str, song_uri: str)¶ Add a Spotify song to a users saved songs library
- Parameters
auth_code – (str) Access token for user from Spotify
song_uri – (str) Spotify URI code for song to save
-
add_track_to_user_queue(auth_code: str, song_uri: str) → None¶ Add a Spotify track to the authenticated user’s queue.
Requires user-modify-playback-state OAuth scope from Spotify
- Parameters
auth_code – (str) Access token for user from Spotify
song_uri – (str) Spotify URI code for song to add to queue
-
batch_tracks(tracks: list, batch_size: int = None) → List[list]¶ Some Spotify endpoints have a limit on the number of tracks to send in one request. This method will take a list of tracks and create a list of batches for including in Spotify requests.
- Parameters
tracks – (list) List of tracks to batch
batch_size – (int) Optional size of batches to return
- Returns
(list[list]) Original list of tracks, batched into lists of batch_size
-
build_spotify_oauth_confirm_link(state: str, scopes: List[str], redirect_url: str) → str¶ First step in the Spotify user authorization flow. This builds the request to authorize the application with Spotify. Note that this function simply builds the URL for the user to visit, the actual behavior for the authorization need to be made client-side.
- Parameters
state – (str) State to pass in request. Used for validating redirect URI against request
scopes – (list(str)) Spotify OAuth scopes to grant in authentication request
redirect_url – (str) URL to redirect to after OAuth confirmation
- Returns
(str) URL for Spotify OAuth confirmation
-
create_playlist(auth_code: str, spotify_user_id: str, playlist_name: str) → str¶ Create a playlist for the given Spotify user. Note that this creates an empty playlist, a subsequent API call should be made to populate the playlist with songs.
- Parameters
auth_code – (str) Access token for user from Spotify
spotify_user_id – (str) Spotify username for the given user
playlist_name – (str) Name of the playlist to be created
- Returns
(str) Spotify playlist ID for the created playlist
-
delete_songs_from_playlist(auth_code: str, playlist_id: str, songs: list) → None¶ Remove songs from a specified playlist
- Parameters
auth_code – (str) Access token for user from Spotify
playlist_id – (str) Spotify playlist ID to remove songs from
songs – (list) Collection of Spotify track URIs to remove from playlist
-
get_access_and_refresh_tokens(code: str, redirect_url: str) → dict¶ Make a request to the Spotify authorization endpoint to obtain the access and refresh tokens for a user after they have granted our application permission to Spotify on their behalf.
- Parameters
code – (str) Authorization code returned from initial request for Spotify OAuth
redirect_url – (str) URL to redirect to after OAuth confirmation
- Returns
(dict) - access_token (str) - refresh_token (str)
-
get_all_songs_from_user_playlist(auth_code: str, playlist_id: str) → List[str]¶ Get all the song URIs from the playlist for the given user
- Parameters
auth_code – (str) Access token for user who owns the playlist
playlist_id – (str) Playlist ID from Spotify
- Returns
List of Spotify URIs for songs in playlist
-
get_attributes_for_track(uri: str) → dict¶ Fetch song metadata for a singular track
- Parameters
uri – (str) URI of song to search for on Spotify
- Returns
(dict) - name (str) - artist (str) - code (str)
-
get_audio_features_for_tracks(tracks: List[dict]) → List[dict]¶ Get audio features (attributes we use for determining song emotion) for a number of tracks. Will update the tracks in place, each track in the list is a dictionary of values needed to create a Song object. This method returns the list of tracks updated with the tracks emotion attribute values.
- Parameters
tracks – (list[dict]) Song mappings
- Returns
(list[dict]) Song mappings + (energy, valence, danceability)
-
get_code_from_spotify_uri(code: str) → str¶ Get the Spotify code (alphanumeric value) from the Spotify song URI. Used in requests to Spotify for a track, as Spotify only cares about the alphanumeric value.
Ex. Given ‘spotify:track:19p0PEnGr6XtRqCYEI8Ucc’, return ‘19p0PEnGr6XtRqCYEI8Ucc’
- Parameters
code – (str) Full Spotify URI for a song
- Returns
(str) Spotify code for the song
-
get_playlists_for_category(category: str, num_playlists: int) → List[dict]¶ Get a number of playlists from Spotify for a given category
- Parameters
category – (str) Category ID of a genre in Spotify
num_playlists – (int) Number of playlists to return
- Returns
(list[dict]) Playlist mappings for the given category - name (str): Name of the playlist - uri (str): Spotify ID for the playlist - user (str): Spotify ID for the playlist owner
-
get_recently_played_tracks_for_user(auth_code: str, limit: int = None) → dict¶ Retrieve the top limit tracks that a user has listened to on Spotify - Requires the user-read-recently-played Spotify OAuth scope
- Parameters
auth_code – (str) Access token for user from Spotify
limit – (int) Number of tracks to return (default to self.DEFAULT_RECENTLY_PLAYED_TRACKS_LIMIT)
- Returns
(dict) Response of play history objects from Spotify API
-
get_recommendations(target: str, min_value: float, max_value: float, seed_tracks: List[str], limit: int)¶ Make a request to get recommendations for the target values based on the tracks supplied as the seed entity batch. This will return songs from the Spotify API whose attributes most closely match the seed tracks attributes for the given target
- Parameters
target – (str) Spotify attribute value to use in recommendation query
min_value – (float) Minimum target value to use in recommendation query
max_value – (float) Maximum target value to use in recommendation query
seed_tracks – (List[str]) List of Spotify song ids to use as entity batch
limit – (int) Max number of results to return from recommendation query
- Returns
(dict) Recommendations object from Spotify API
-
get_songs_from_playlist(playlist: dict, num_songs: int, allow_explicit: bool = False) → List[dict]¶ Get a number of songs randomly from the given playlist. List of songs is shuffled and the number of desired tracks are returned.
- Parameters
playlist – (dict) Mapping of values needed to retrieve playlist tracks
num_songs – (int) Number of songs to return from this playlist
allow_explicit – (bool) Flag to indicate whether or not to return explicit songs (default False)
- Returns
(list[dict]) Song mappings from the given playlist
name (str): Name of the song
artist (str): Name of the artist
code (str): Spotify ID of the song
-
get_user_playlists(auth_code: str, spotify_user_id: str) → dict¶ Get all playlists for the given Spotify user.
- Parameters
auth_code – (str) Access token for user from Spotify
spotify_user_id – (str) Spotify username for the given user
- Returns
(dict) Spotify response for all users playlists
-
get_user_profile(access_token: str) → dict¶ Get data on the user from Spotify API /me endpoint
- Parameters
access_token – (str) OAuth token from Spotify for the user
- Returns
(dict) Payload for the given user
-
get_user_top_artists(auth_code: str, max_top_artists: int) → List[str]¶ Retrieve the top artists from Spotify for a user.
- Parameters
auth_code – (str) Access token for user from Spotify
max_top_artists – (int) Max number of top artists to retrieve
- Returns
(list(str)) List of top artists for the user from Spotify
-
refresh_access_token(refresh_token: str) → str¶ Refresh application on behalf of user given a refresh token. On a successful response, will return an access token for the user good for the timeout period for Spotify authentication (One hour.)
- Parameters
refresh_token – (str) Refresh token for user from Spotify
- Returns
(str) New access token for user
-
search(query: str, search_types: Union[str, List], limit: int = None) → dict¶ Query the API for resources that match a given query.
- Parameters
query – (str) Query to send to the endpoint
search_types – (str | list) Single or multiple item types to search across. Must be one of album, artist, playlist, track, show, episode.
limit – (int) Maximum number of resources to return. Default to max of 50 resources
- Returns
(dict) Response from API. See https://developer.spotify.com/documentation/web-api/reference/search/search/#fields-reference for full details.
-
upload_image_to_playlist(auth_code: str, playlist_id: str, image_filepath: str) → None¶ Upload a custom image for a playlist. Requires ugc-image-upload and playlist-modify-public/playlist-modify-private scopes from Spotify
- Parameters
auth_code – (str) Access token for user who owns the playlist
playlist_id – (str) Playlist ID from Spotify
image_filepath – (str) Path to the image file to upload