Welcome to Pyfy’s documentation! 👋¶
Pyfy is a Sync + Async Pythonic Spotify Client that focuses on ease of use in personal projects and API stability and security for production grade codebases.
Setup 🥁¶
$ pip install pyfy
Quick Start 🎛️¶
Sync
from pyfy import Spotify
spt = Spotify('your_access_token')
spt.play()
spt.volume(85)
spt.next()
spt.pause()
Async
import asyncio
from pyfy import AsyncSpotify
spt = AsyncSpotify('your_access_token')
async def search():
return await spt.search('A tout le monde')
search_result = asyncio.run(search())
Getting Started 👩¶
You should start by creating client credentials from Spotify’s Developer’s console.
Next, edit your application’s settings and set a Redirect URL. If it’s for personal use then set it as:
http://localhost:9000 Port can be any port of choice, not necessarily 9000
Next, copy your:
Client ID
Client Secret
Redirect URL (That you just set)
Next, figure out the scopes that you think you’ll need from here: https://developer.spotify.com/documentation/general/guides/scopes/
e.g. ["user-library-modify", "app-remote-control"]
Next, follow the first authentication scheme from below (it’s the one you’ll most likely need, unless you’re sure otherwise)
Authentication 👩🎤¶
1. Authorization Code Flow (OAuth2) (recommended)
Suitable if you want to access user-related resources. e.g. user-playlists, user-tracks etc.
Click here for full working examples with Sanic(async) and Flask(sync).
from pyfy import Spotify, ClientCreds, UserCreds, AuthError, ApiError
client = ClientCreds(
client_id='clientid',
client_secret='client_secret',
redirect_uri='https://localhost:9000",
scopes=["user-library-modify", "app-remote-control"]
)
spt = Spotify(client_creds=client)
def authorize():
# Fist step of OAuth, Redirect user to spotify's authorization endpoint
if spt.is_oauth_ready:
return redirect(spt.auth_uri())
# Authorization callback
def callback(grant):
try:
user_creds = spt.build_credentials(grant=grant)
except AuthError as e:
abort(401)
logging.info(e.msg)
logging.info(e.http_response)
else:
db.insert(user_creds)
return redirect(url_for_home)
def get_user_tracks():
try:
return json.dumps(spt.user_tracks())
except ApiError:
abort(500)
2. User’s Access Token: get from here
Same as the Authorization Code Flow above but without a refresh token. Suitable for quick runs.
from pyfy import Spotify
spt = Spotify('your access token')
3. Client Credentials Flow (OAuth2): get from here
Suitable for when you want to access public information quickly. (Accessing user information is porhibited using this method)
from pyfy import ClientCreds, Spotify
client = ClientCreds(client_id=client_id, client_secret=client_secret)
spt = Spotify(client_creds=client)
spt.authorize_client_creds()
API endpoints 🌐¶
Albums¶
Get an album:
Get an album’s tracks:
Get several albums:
Artists¶
Get an artist:
Artist albums:
Artist top tracks:
Artist related artists:
Get several artists:
Browse¶
Get a category:
Get a category’s playlists:
Get list of categories:
Get a list of featured playlists:
Get a list of new releases:
Get recommendations based on seeds:
Episodes¶
Get an episode:
Pyfy: TODO
Web API reference: https://developer.spotify.com/documentation/web-api/reference/episodes/get-an-episode/
Get several episodes:
Pyfy: TODO
Web API reference: https://developer.spotify.com/documentation/web-api/reference/episodes/get-several-episodes/
Follow¶
Check if Current User Follows Artists or Users:
Check if Users Follow a Playlist:
Follow Artists:
Follow Users:
Follow a playlist:
Get User’s Followed Artists:
Unfollow Artists:
Unfollow Users:
Unfollow Playlist:
User Library¶
Check User’s Saved Albums:
Check User’s Saved Shows:
Pyfy: TODO
Web API reference: https://developer.spotify.com/documentation/web-api/reference/library/check-users-saved-shows/
Check User’s Saved Tracks:
Get Current User’s Saved Albums:
Get User’s Saved Shows:
Pyfy: TODO
Web API reference: https://developer.spotify.com/documentation/web-api/reference/library/get-users-saved-shows/
Get a User’s Saved Tracks:
Remove Albums for Current User:
Remove User’s Saved Shows:
Pyfy: TODO
Web API reference: https://developer.spotify.com/documentation/web-api/reference/library/remove-shows-user/
Remove User’s Saved Tracks:
Save Albums for Current User:
Save Shows for Current User:
Pyfy: TODO
Web API reference: https://developer.spotify.com/documentation/web-api/reference/library/save-shows-user/
Save Tracks for User:
Personalization¶
Get a User’s Top Artists:
Get a User’s Top Tracks:
Player¶
Add an Item to the User’s Playback Queue:
Get a User’s Available Devices:
Get Information About The User’s Current Playback:
Get Current User’s Recently Played Tracks:
Get the User’s Currently Playing Track:
Pause a User’s Playback:
Seek To Position In Currently Playing Track:
Set Repeat Mode On User’s Playback:
Set Volume For User’s Playback:
Skip User’s Playback To Next Track:
Skip User’s Playback To Previous Track:
Start/Resume a User’s Playback:
Toggle Shuffle For User’s Playback:
Transfer a User’s Playback:
Playlists¶
Add playlist items:
Edit playlist:
Create playlist:
List a user’s playlists:
Playlist cover:
Pyfy: TODO
Web API reference: https://developer.spotify.com/documentation/web-api/reference/playlists/get-playlist-cover/
List a playlist:
List a playlist items:
Remove playlist items:
Reorder playlist items:
Replace playlist items:
Upload custom playlist cover image:
Pyfy: TODO
Web API reference: https://developer.spotify.com/documentation/web-api/reference/playlists/upload-custom-playlist-cover/
List current user playlists:
Search¶
Search for an item:
Shows¶
Get a Show:
Pyfy: TODO
Web API reference: https://developer.spotify.com/documentation/web-api/reference/shows/get-a-show/
Get Several Shows:
Pyfy: TODO
Web API reference: https://developer.spotify.com/documentation/web-api/reference/shows/get-several-shows/
Get a Show’s Episodes:
Pyfy: TODO
Web API reference: https://developer.spotify.com/documentation/web-api/reference/shows/get-shows-episodes/
Tracks¶
Get Audio Analysis for a Track:
Get Audio Features for a Track:
Get Audio Features for Several Tracks:
Get Several Tracks:
Get a Track:
Users Profile¶
Get Current User’s Profile:
Get a User’s Profile:
Pagination 📖¶
from pyfy import Spotify
user_creds = {'access_token': '...', 'refresh_token': '....'}
spt = Spotify(user_creds=user_creds)
user_top_tracks = spt.user_top_tracks(limit=5)
next_page_1 = spt.next_page(user_top_tracks)
next_page_2 = spt.next_page(next_page_1)
previous_page_1 = spt.previous_page(next_page_2)
previous_page_1 === next_page_1 # True
Sync Client API 🎸¶
- class pyfy.sync_client.Spotify(access_token=None, client_creds=<pyfy.creds.ClientCreds object>, user_creds=None, ensure_user_auth=False, proxies={}, timeout=7, max_retries=10, backoff_factor=0.1, default_to_locale=True, cache=True, populate_user_creds=True)[source]¶
Bases:
pyfy.base_client._BaseClient
Spotify’s Synchronous Client
- Parameters
client_creds (pyfy.creds.ClientCreds) – A client credentials model
user_creds (pyfy.creds.UserCreds) – A user credentials model
ensure_user_auth (bool) –
Whether or not to fail upon instantiation if user_creds provided where invalid and not refresheable.
Default: False
proxies –
timeout (int) –
Seconds before request raises a timeout error
Default: 7
max_retries (int) –
Max retries before a request fails
Default: 10
backoff_factor (float) –
Factor by which requests delays the next request when encountring a 429 too-many-requests error
Default: 0.1
default_to_locale (bool) –
Will pass methods decorated with @_default_to_locale the user’s locale if available.
Default: True
cache –
Whether or not to cache HTTP requests for the user
Default: True
populate_user_creds (bool) –
Sets user_creds info from Spotify to client’s user_creds object. e.g. country.
Default: True
- IS_ASYNC = False¶
- add_playlist_tracks(*args, **kwargs)[source]¶
Add tracks to a playlist
- Parameters
playlist_id –
Required
track_ids (str, list) –
Required
position –
Optional
- Returns
- Return type
dict
- Raises
- album_tracks(*args, **kwargs)[source]¶
List tracks of an album
- Parameters
album_id (str) –
Required
market –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- albums(*args, **kwargs)[source]¶
List Albums
- Parameters
album_ids (str, list) –
Required
market –
Optional
- Returns
- Return type
dict
- Raises
- artist_albums(*args, **kwargs)[source]¶
List albums of an artist
- Parameters
artist_id (str) –
Required
include_groups –
Optional
market –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
List artists related to an artist
- Parameters
artist_id (str) –
Required
- Returns
- Return type
dict
- Raises
- artist_top_tracks(*args, **kwargs)[source]¶
List top tracks of an artist
- Parameters
artist_id (str) –
Required
country –
Optional
- Returns
- Return type
dict
- Raises
- artists(*args, **kwargs)[source]¶
List artists
- Parameters
artist_ids (str, list) –
- Returns
Required
- Return type
dict
- Raises
- auth_uri(state=None, client_id=None, scopes=None, redirect_uri=None, show_dialog=None, response_type=None)¶
Generates OAuth2 URI for authentication Arguments will default to the attributes of self.client_creds
- Parameters
client_id (str) – OAuth2 client_id (Defaults to self.client_creds.client_id)
scopes (list) – OAuth2 scopes. (Defaults to self.client_creds.scopes)
redirect_uri (str) – OAuth2 redirect uri. (Defaults to self.client_creds.redirect_uri)
show_dialog (bool) – if set to false, Spotify will not show a new authentication request if user already authorized the client (Defaults to self.client_creds.show_dialog)
response_type (str) – Defaults to “code” for OAuth2 Authorization Code Flow
- Returns
OAuth2 Auth URI
- Return type
str
- authorize_client_creds(client_creds=None)[source]¶
Authorize with client credentials oauth flow i.e. Only with client secret and client id.
Call this to send request using client credentials.
https://developer.spotify.com/documentation/general/guides/authorization-guide/
Note
This will give you limited access to most endpoints
- Parameters
client_creds (pyfy.creds.ClientCreds) – Client Credentials object. Defaults to
self.client_creds
.- Raises
pyfy.excs.AuthErrror –
- available_genre_seeds(*args, **kwargs)[source]¶
Available genre seeds
- Returns
- Return type
dict
- Raises
- build_user_creds(grant, set_user_creds=True)[source]¶
Second part of OAuth2 authorization code flow, Raises an AuthError if unauthorized
- Parameters
grant (str) – Code returned to user after authorizing your application
set_user_creds (bool) – Whether or not to set the user created to the client as the current active user
- Returns
User Credentials Model
- Return type
- categories(*args, **kwargs)[source]¶
List Categories
- Parameters
country –
Optional
locale –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- category(*args, **kwargs)[source]¶
List Category
- Parameters
category_id –
Required
country –
Optional
locale –
Optional
- Returns
- Return type
dict
- Raises
- category_playlist(*args, **kwargs)[source]¶
List playlists from a category
- Parameters
category_id –
Required
country –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- create_playlist(*args, **kwargs)[source]¶
Creates a playlist
- Parameters
name –
Required
description –
Optional
public –
Optional
Default: False
collaborative –
Optional
default: False
- Returns
- Return type
dict
- Raises
- currently_playing(*args, **kwargs)[source]¶
Lists currenly playing
- Parameters
market (str) –
Optional
- Returns
- Return type
dict
- Raises
- currently_playing_info(*args, **kwargs)[source]¶
Lists currently playing info
- Parameters
market (str) –
Optional
- Returns
- Return type
dict
- Raises
- delete_albums(*args, **kwargs)[source]¶
Delete Albums
- Parameters
album_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- delete_playlist(*args, **kwargs)[source]¶
An alias to unfollow_playlist
- Parameters
playlist_id –
Required
- Returns
- Return type
dict
- Raises
- delete_playlist_tracks(*args, **kwargs)[source]¶
Delete tracks from a playlist
https://developer.spotify.com/console/delete-playlist-tracks/
Examples
track_ids
types supported:1) 'track_id' 2) ['track_id', 'track_id', 'track_id'] 3) [ { 'id': track_id, 'positions': [ position1, position2 ] }, { 'id': track_id, 'positions': position1 }, track_id ]
- Parameters
playlist_id –
Required
track_ids –
Required
- Returns
- Return type
dict
- Raises
- delete_tracks(*args, **kwargs)[source]¶
Delete user’s tracks
- Parameters
track_ids (str, list) –
- Returns
Required
- Return type
dict
- Raises
- featured_playlists(*args, **kwargs)[source]¶
Featured Playlists
- Parameters
country –
Optional
locale –
Optional
timestamp –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- follow_artists(*args, **kwargs)[source]¶
Follow an artist(s)
- Parameters
artist_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- follow_playlist(*args, **kwargs)[source]¶
Follows a playlist
- Parameters
playlist_id –
Required
public –
Optional
Default: False
- Returns
- Return type
dict
- Raises
- follow_users(*args, **kwargs)[source]¶
Follow a user
- Parameters
user_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- followed_artists(*args, **kwargs)[source]¶
List artists followed by current user
- Parameters
after –
Optional
limit –
Optional
- Returns
- Return type
dict
- Raises
- follows_artists(*args, **kwargs)[source]¶
Whether or not current user follows an artist(s)
- Parameters
artist_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- follows_playlist(*args, **kwargs)[source]¶
Lists whether or not user follows a playlist
- Parameters
playlist_id –
Required
user_ids (list, str) –
Optional
- Returns
- Return type
dict
- Raises
- follows_users(*args, **kwargs)[source]¶
Whether or not current user follows a user(s)
- Parameters
user_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- property is_active¶
Checks if user_creds or client_creds are valid (depending on who was last set)
- property is_oauth_ready¶
Whether Client Credentials have enough information to perform OAuth2 Authorization Code FLow
Returns
bool:
Checks whether user is premium or not
- Returns
- Return type
bool
- new_releases(*args, **kwargs)[source]¶
New Releases
- Parameters
country –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- next(*args, **kwargs)[source]¶
Next playback
- Parameters
device_id –
Optional
- Returns
- Return type
dict
- Raises
- next_page(*args, **kwargs)[source]¶
Next Page
Note
You can either provide a response or a url
Providing a URL will be slightly faster as Pyfy will not have to search for the key in the response dict
- Parameters
response (dict) –
Optional
url (str) –
Optional
- Returns
- Return type
dict
- Raises
- owns_albums(*args, **kwargs)[source]¶
Whether or not current user owns an album(s)
- Parameters
album_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- owns_tracks(*args, **kwargs)[source]¶
Lists whether or not current user owns tracks
- Parameters
track_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- pause(*args, **kwargs)[source]¶
Pauses playback
- Parameters
device_id (str) –
Optional
- Returns
- Return type
dict
- Raises
- play(*args, **kwargs)[source]¶
Starts playback
Play a list of one or more tracks, or a specific artist, album or playlist. Only one of track_ids, album_id, artist_id, playlist_id should be specified. Start playback at offset_position OR offset_uri, only if artist_id is not being used.
- Parameters
track_ids (list, tuple, str) –
Optional
List, string or tuple containing track ID(s).
album_id (str) –
Optional
artist_id (str) –
Optional
playlist_id (str) –
Optional
device_id (str) –
Optional
offset_position (int) –
Optional
offset_uri (str) –
Optional
poition_ms (int) –
Optional
- Returns
- Return type
dict
- Raises
- playback_transfer(*args, **kwargs)[source]¶
Transfer playback to another device
- Parameters
device_ids (list, str) –
Required
- Returns
- Return type
dict
- Raises
- playlist(*args, **kwargs)[source]¶
Lists playlist
- Parameters
playlist_id –
Required
market –
Optional
fields –
Optional
- Returns
- Return type
dict
- Raises
- playlist_cover(*args, **kwargs)[source]¶
Get a Playlist Cover Image
- Parameters
playlist_id –
Required
- Returns
- Return type
list
- Raises
- playlist_tracks(*args, **kwargs)[source]¶
List tracks in a playlist
- Parameters
playlist_id –
Required
market –
Optional
fields –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- populate_user_creds()[source]¶
Populates self.user_creds with Spotify’s info on user. Data is fetched from self.me() and set to user recursively
- previous(*args, **kwargs)[source]¶
Previous Playback
- Parameters
device_id –
Optional
- Returns
- Return type
dict
- Raises
- previous_page(*args, **kwargs)[source]¶
Previous Page
Note
You can either provide a response or a url
Providing a URL will be slightly faster as Pyfy will not have to search for the key in the response dict
- Parameters
response (dict) –
Optional
url (str) –
Optional
- Returns
- Return type
dict
- Raises
- queue(*args, **kwargs)[source]¶
Add an item to the end of the user’s current playback queue
- Parameters
track_id (str) –
Required
device_id –
Optional
- Returns
- Return type
dict
- Raises
- recently_played_tracks(*args, **kwargs)[source]¶
Lists recently played tracks
- Parameters
limit (int) –
Optional
after –
Optional
before –
Optional
- Returns
- Return type
dict
- Raises
- recommendations(*args, **kwargs)[source]¶
List Recommendations
https://developer.spotify.com/documentation/web-api/reference/browse/get-recommendations/
- Parameters
limit –
Optional
market –
Optional
seed_artists –
Optional
seed_genres –
Optional
seed_tracks –
Optional
min_acousticness –
Optional
max_acousticness –
Optional
target_acousticness –
Optional
min_danceability –
Optional
max_danceability –
Optional
target_danceability –
Optional
min_duration_ms –
Optional
max_duration_ms –
Optional
target_duration_ms –
Optional
min_energy –
Optional
max_energy –
Optional
target_energy –
Optional
min_instrumentalness –
Optional
max_instrumentalness –
Optional
target_instrumentalness –
Optional
min_key –
Optional
max_key –
Optional
target_key –
Optional
min_liveness –
Optional
max_liveness –
Optional
target_liveness –
Optional
min_loudness –
Optional
max_loudness –
Optional
target_loudness –
Optional
min_mode –
Optional
max_mode –
Optional
target_mode –
Optional
min_popularity –
Optional
max_popularity –
Optional
target_popularity –
Optional
min_speechiness –
Optional
max_speechiness –
Optional
target_speechiness –
Optional
min_tempo –
Optional
max_tempo –
Optional
target_tempo –
Optional
min_time_signature –
Optional
max_time_signature –
Optional
target_time_signature –
Optional
min_valence –
Optional
max_valence –
Optional
target_valence –
Optional
- Returns
- Return type
dict
- Raises
- reorder_playlist_track(*args, **kwargs)[source]¶
Reorder tracks in a playlist
- Parameters
playlist_id –
Required
range_start –
Optional
range_length –
Optional
insert_before –
Optional
- Returns
- Return type
dict
- Raises
- repeat(*args, **kwargs)[source]¶
Toggle repeat
- Parameters
state –
Optional
Default: ‘context’
device_id –
Optional
- Returns
- Return type
dict
- Raises
- replace_playlist_tracks(*args, **kwargs)[source]¶
Replace all tracks of a playlist with tracks of your choice
- Parameters
playlist_id –
Required
track_ids –
track_ids not full URIs
Optional
- Returns
- Return type
dict
- Raises
- save_albums(*args, **kwargs)[source]¶
Save Albums
- Parameters
album_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- save_tracks(*args, **kwargs)[source]¶
Save tracks
- Parameters
track_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- search(*args, **kwargs)[source]¶
Search
Examples
tracks parameter example:
'track' or ['track'] or 'artist' or ['track','artist']
- Parameters
q –
Query
Required
types –
Optional
Default:
'track'
market –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- seek(*args, **kwargs)[source]¶
Seek Playback
- Parameters
posiotion_ms –
Required
device_id –
Optional
- Returns
- Return type
dict
- Raises
- shuffle(*args, **kwargs)[source]¶
Shuffle Playback
- Parameters
state –
Optional
Default: True
device_id –
Optional
- Returns
- Return type
dict
- Raises
- track_audio_analysis(*args, **kwargs)[source]¶
List audio analysis of a track
- Parameters
track_id –
Required
- Returns
- Return type
dict
- Raises
- tracks(*args, **kwargs)[source]¶
List tracks
- Parameters
track_ids (str, list) –
Required
market –
Optional
- Returns
- Return type
dict
- Raises
- tracks_audio_features(*args, **kwargs)[source]¶
List audio features of tracks
- Parameters
track_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- unfollow_artists(*args, **kwargs)[source]¶
Unfollow artist(s)
- Parameters
artist_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- unfollow_playlist(*args, **kwargs)[source]¶
Unfollow a playlist
- Parameters
playlist_id –
Required
- Returns
- Return type
dict
- Raises
- unfollow_users(*args, **kwargs)[source]¶
Unfollow user(s)
- Parameters
user_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- update_playlist(*args, **kwargs)[source]¶
Updates a playlist
- Parameters
playlist_id –
Required
name –
Optional
description –
Optional
public –
Optional
collaborative –
Optional
- Returns
- Return type
dict
- Raises
- user_albums(*args, **kwargs)[source]¶
Albums owned by current user
- Parameters
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- property user_creds¶
- user_playlists(*args, **kwargs)[source]¶
Lists playlists owned by a user
- Parameters
user_id –
Optional
Defaults to user’s
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- user_profile(*args, **kwargs)[source]¶
List a user’s profile
- Parameters
user_id (str) –
Required
- Returns
- Return type
dict
- Raises
- user_top_artists(*args, **kwargs)[source]¶
List top artists of a user
- Parameters
time_range –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- user_top_tracks(*args, **kwargs)[source]¶
List top tracks of a user
- Parameters
time_range –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- user_tracks(*args, **kwargs)[source]¶
List user’s tracks
- Parameters
market –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
Async Client API 🎼¶
- class pyfy.sync_client.Spotify(access_token=None, client_creds=<pyfy.creds.ClientCreds object>, user_creds=None, ensure_user_auth=False, proxies={}, timeout=7, max_retries=10, backoff_factor=0.1, default_to_locale=True, cache=True, populate_user_creds=True)[source]¶
Bases:
pyfy.base_client._BaseClient
Spotify’s Synchronous Client
- Parameters
client_creds (pyfy.creds.ClientCreds) – A client credentials model
user_creds (pyfy.creds.UserCreds) – A user credentials model
ensure_user_auth (bool) –
Whether or not to fail upon instantiation if user_creds provided where invalid and not refresheable.
Default: False
proxies –
timeout (int) –
Seconds before request raises a timeout error
Default: 7
max_retries (int) –
Max retries before a request fails
Default: 10
backoff_factor (float) –
Factor by which requests delays the next request when encountring a 429 too-many-requests error
Default: 0.1
default_to_locale (bool) –
Will pass methods decorated with @_default_to_locale the user’s locale if available.
Default: True
cache –
Whether or not to cache HTTP requests for the user
Default: True
populate_user_creds (bool) –
Sets user_creds info from Spotify to client’s user_creds object. e.g. country.
Default: True
- IS_ASYNC = False¶
- add_playlist_tracks(*args, **kwargs)[source]¶
Add tracks to a playlist
- Parameters
playlist_id –
Required
track_ids (str, list) –
Required
position –
Optional
- Returns
- Return type
dict
- Raises
- album_tracks(*args, **kwargs)[source]¶
List tracks of an album
- Parameters
album_id (str) –
Required
market –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- albums(*args, **kwargs)[source]¶
List Albums
- Parameters
album_ids (str, list) –
Required
market –
Optional
- Returns
- Return type
dict
- Raises
- artist_albums(*args, **kwargs)[source]¶
List albums of an artist
- Parameters
artist_id (str) –
Required
include_groups –
Optional
market –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- artist_related_artists(*args, **kwargs)[source]¶
List artists related to an artist
- Parameters
artist_id (str) –
Required
- Returns
- Return type
dict
- Raises
- artist_top_tracks(*args, **kwargs)[source]¶
List top tracks of an artist
- Parameters
artist_id (str) –
Required
country –
Optional
- Returns
- Return type
dict
- Raises
- artists(*args, **kwargs)[source]¶
List artists
- Parameters
artist_ids (str, list) –
- Returns
Required
- Return type
dict
- Raises
- auth_uri(state=None, client_id=None, scopes=None, redirect_uri=None, show_dialog=None, response_type=None)¶
Generates OAuth2 URI for authentication Arguments will default to the attributes of self.client_creds
- Parameters
client_id (str) – OAuth2 client_id (Defaults to self.client_creds.client_id)
scopes (list) – OAuth2 scopes. (Defaults to self.client_creds.scopes)
redirect_uri (str) – OAuth2 redirect uri. (Defaults to self.client_creds.redirect_uri)
show_dialog (bool) – if set to false, Spotify will not show a new authentication request if user already authorized the client (Defaults to self.client_creds.show_dialog)
response_type (str) – Defaults to “code” for OAuth2 Authorization Code Flow
- Returns
OAuth2 Auth URI
- Return type
str
- authorize_client_creds(client_creds=None)[source]¶
Authorize with client credentials oauth flow i.e. Only with client secret and client id.
Call this to send request using client credentials.
https://developer.spotify.com/documentation/general/guides/authorization-guide/
Note
This will give you limited access to most endpoints
- Parameters
client_creds (pyfy.creds.ClientCreds) – Client Credentials object. Defaults to
self.client_creds
.- Raises
pyfy.excs.AuthErrror –
- available_genre_seeds(*args, **kwargs)[source]¶
Available genre seeds
- Returns
- Return type
dict
- Raises
- build_user_creds(grant, set_user_creds=True)[source]¶
Second part of OAuth2 authorization code flow, Raises an AuthError if unauthorized
- Parameters
grant (str) – Code returned to user after authorizing your application
set_user_creds (bool) – Whether or not to set the user created to the client as the current active user
- Returns
User Credentials Model
- Return type
- categories(*args, **kwargs)[source]¶
List Categories
- Parameters
country –
Optional
locale –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- category(*args, **kwargs)[source]¶
List Category
- Parameters
category_id –
Required
country –
Optional
locale –
Optional
- Returns
- Return type
dict
- Raises
- category_playlist(*args, **kwargs)[source]¶
List playlists from a category
- Parameters
category_id –
Required
country –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- create_playlist(*args, **kwargs)[source]¶
Creates a playlist
- Parameters
name –
Required
description –
Optional
public –
Optional
Default: False
collaborative –
Optional
default: False
- Returns
- Return type
dict
- Raises
- currently_playing(*args, **kwargs)[source]¶
Lists currenly playing
- Parameters
market (str) –
Optional
- Returns
- Return type
dict
- Raises
- currently_playing_info(*args, **kwargs)[source]¶
Lists currently playing info
- Parameters
market (str) –
Optional
- Returns
- Return type
dict
- Raises
- delete_albums(*args, **kwargs)[source]¶
Delete Albums
- Parameters
album_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- delete_playlist(*args, **kwargs)[source]¶
An alias to unfollow_playlist
- Parameters
playlist_id –
Required
- Returns
- Return type
dict
- Raises
- delete_playlist_tracks(*args, **kwargs)[source]¶
Delete tracks from a playlist
https://developer.spotify.com/console/delete-playlist-tracks/
Examples
track_ids
types supported:1) 'track_id' 2) ['track_id', 'track_id', 'track_id'] 3) [ { 'id': track_id, 'positions': [ position1, position2 ] }, { 'id': track_id, 'positions': position1 }, track_id ]
- Parameters
playlist_id –
Required
track_ids –
Required
- Returns
- Return type
dict
- Raises
- delete_tracks(*args, **kwargs)[source]¶
Delete user’s tracks
- Parameters
track_ids (str, list) –
- Returns
Required
- Return type
dict
- Raises
- featured_playlists(*args, **kwargs)[source]¶
Featured Playlists
- Parameters
country –
Optional
locale –
Optional
timestamp –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- follow_artists(*args, **kwargs)[source]¶
Follow an artist(s)
- Parameters
artist_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- follow_playlist(*args, **kwargs)[source]¶
Follows a playlist
- Parameters
playlist_id –
Required
public –
Optional
Default: False
- Returns
- Return type
dict
- Raises
- follow_users(*args, **kwargs)[source]¶
Follow a user
- Parameters
user_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- followed_artists(*args, **kwargs)[source]¶
List artists followed by current user
- Parameters
after –
Optional
limit –
Optional
- Returns
- Return type
dict
- Raises
- follows_artists(*args, **kwargs)[source]¶
Whether or not current user follows an artist(s)
- Parameters
artist_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- follows_playlist(*args, **kwargs)[source]¶
Lists whether or not user follows a playlist
- Parameters
playlist_id –
Required
user_ids (list, str) –
Optional
- Returns
- Return type
dict
- Raises
- follows_users(*args, **kwargs)[source]¶
Whether or not current user follows a user(s)
- Parameters
user_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- property is_active¶
Checks if user_creds or client_creds are valid (depending on who was last set)
- property is_oauth_ready¶
Whether Client Credentials have enough information to perform OAuth2 Authorization Code FLow
Returns
bool:
- property is_premium¶
Checks whether user is premium or not
- Returns
- Return type
bool
- new_releases(*args, **kwargs)[source]¶
New Releases
- Parameters
country –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- next(*args, **kwargs)[source]¶
Next playback
- Parameters
device_id –
Optional
- Returns
- Return type
dict
- Raises
- next_page(*args, **kwargs)[source]¶
Next Page
Note
You can either provide a response or a url
Providing a URL will be slightly faster as Pyfy will not have to search for the key in the response dict
- Parameters
response (dict) –
Optional
url (str) –
Optional
- Returns
- Return type
dict
- Raises
- owns_albums(*args, **kwargs)[source]¶
Whether or not current user owns an album(s)
- Parameters
album_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- owns_tracks(*args, **kwargs)[source]¶
Lists whether or not current user owns tracks
- Parameters
track_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- pause(*args, **kwargs)[source]¶
Pauses playback
- Parameters
device_id (str) –
Optional
- Returns
- Return type
dict
- Raises
- play(*args, **kwargs)[source]¶
Starts playback
Play a list of one or more tracks, or a specific artist, album or playlist. Only one of track_ids, album_id, artist_id, playlist_id should be specified. Start playback at offset_position OR offset_uri, only if artist_id is not being used.
- Parameters
track_ids (list, tuple, str) –
Optional
List, string or tuple containing track ID(s).
album_id (str) –
Optional
artist_id (str) –
Optional
playlist_id (str) –
Optional
device_id (str) –
Optional
offset_position (int) –
Optional
offset_uri (str) –
Optional
poition_ms (int) –
Optional
- Returns
- Return type
dict
- Raises
- playback_transfer(*args, **kwargs)[source]¶
Transfer playback to another device
- Parameters
device_ids (list, str) –
Required
- Returns
- Return type
dict
- Raises
- playlist(*args, **kwargs)[source]¶
Lists playlist
- Parameters
playlist_id –
Required
market –
Optional
fields –
Optional
- Returns
- Return type
dict
- Raises
- playlist_cover(*args, **kwargs)[source]¶
Get a Playlist Cover Image
- Parameters
playlist_id –
Required
- Returns
- Return type
list
- Raises
- playlist_tracks(*args, **kwargs)[source]¶
List tracks in a playlist
- Parameters
playlist_id –
Required
market –
Optional
fields –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- populate_user_creds()[source]¶
Populates self.user_creds with Spotify’s info on user. Data is fetched from self.me() and set to user recursively
- previous(*args, **kwargs)[source]¶
Previous Playback
- Parameters
device_id –
Optional
- Returns
- Return type
dict
- Raises
- previous_page(*args, **kwargs)[source]¶
Previous Page
Note
You can either provide a response or a url
Providing a URL will be slightly faster as Pyfy will not have to search for the key in the response dict
- Parameters
response (dict) –
Optional
url (str) –
Optional
- Returns
- Return type
dict
- Raises
- queue(*args, **kwargs)[source]¶
Add an item to the end of the user’s current playback queue
- Parameters
track_id (str) –
Required
device_id –
Optional
- Returns
- Return type
dict
- Raises
- recently_played_tracks(*args, **kwargs)[source]¶
Lists recently played tracks
- Parameters
limit (int) –
Optional
after –
Optional
before –
Optional
- Returns
- Return type
dict
- Raises
- recommendations(*args, **kwargs)[source]¶
List Recommendations
https://developer.spotify.com/documentation/web-api/reference/browse/get-recommendations/
- Parameters
limit –
Optional
market –
Optional
seed_artists –
Optional
seed_genres –
Optional
seed_tracks –
Optional
min_acousticness –
Optional
max_acousticness –
Optional
target_acousticness –
Optional
min_danceability –
Optional
max_danceability –
Optional
target_danceability –
Optional
min_duration_ms –
Optional
max_duration_ms –
Optional
target_duration_ms –
Optional
min_energy –
Optional
max_energy –
Optional
target_energy –
Optional
min_instrumentalness –
Optional
max_instrumentalness –
Optional
target_instrumentalness –
Optional
min_key –
Optional
max_key –
Optional
target_key –
Optional
min_liveness –
Optional
max_liveness –
Optional
target_liveness –
Optional
min_loudness –
Optional
max_loudness –
Optional
target_loudness –
Optional
min_mode –
Optional
max_mode –
Optional
target_mode –
Optional
min_popularity –
Optional
max_popularity –
Optional
target_popularity –
Optional
min_speechiness –
Optional
max_speechiness –
Optional
target_speechiness –
Optional
min_tempo –
Optional
max_tempo –
Optional
target_tempo –
Optional
min_time_signature –
Optional
max_time_signature –
Optional
target_time_signature –
Optional
min_valence –
Optional
max_valence –
Optional
target_valence –
Optional
- Returns
- Return type
dict
- Raises
- reorder_playlist_track(*args, **kwargs)[source]¶
Reorder tracks in a playlist
- Parameters
playlist_id –
Required
range_start –
Optional
range_length –
Optional
insert_before –
Optional
- Returns
- Return type
dict
- Raises
- repeat(*args, **kwargs)[source]¶
Toggle repeat
- Parameters
state –
Optional
Default: ‘context’
device_id –
Optional
- Returns
- Return type
dict
- Raises
- replace_playlist_tracks(*args, **kwargs)[source]¶
Replace all tracks of a playlist with tracks of your choice
- Parameters
playlist_id –
Required
track_ids –
track_ids not full URIs
Optional
- Returns
- Return type
dict
- Raises
- save_albums(*args, **kwargs)[source]¶
Save Albums
- Parameters
album_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- save_tracks(*args, **kwargs)[source]¶
Save tracks
- Parameters
track_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- search(*args, **kwargs)[source]¶
Search
Examples
tracks parameter example:
'track' or ['track'] or 'artist' or ['track','artist']
- Parameters
q –
Query
Required
types –
Optional
Default:
'track'
market –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- seek(*args, **kwargs)[source]¶
Seek Playback
- Parameters
posiotion_ms –
Required
device_id –
Optional
- Returns
- Return type
dict
- Raises
- shuffle(*args, **kwargs)[source]¶
Shuffle Playback
- Parameters
state –
Optional
Default: True
device_id –
Optional
- Returns
- Return type
dict
- Raises
- track_audio_analysis(*args, **kwargs)[source]¶
List audio analysis of a track
- Parameters
track_id –
Required
- Returns
- Return type
dict
- Raises
- tracks(*args, **kwargs)[source]¶
List tracks
- Parameters
track_ids (str, list) –
Required
market –
Optional
- Returns
- Return type
dict
- Raises
- tracks_audio_features(*args, **kwargs)[source]¶
List audio features of tracks
- Parameters
track_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- unfollow_artists(*args, **kwargs)[source]¶
Unfollow artist(s)
- Parameters
artist_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- unfollow_playlist(*args, **kwargs)[source]¶
Unfollow a playlist
- Parameters
playlist_id –
Required
- Returns
- Return type
dict
- Raises
- unfollow_users(*args, **kwargs)[source]¶
Unfollow user(s)
- Parameters
user_ids (str, list) –
Required
- Returns
- Return type
dict
- Raises
- update_playlist(*args, **kwargs)[source]¶
Updates a playlist
- Parameters
playlist_id –
Required
name –
Optional
description –
Optional
public –
Optional
collaborative –
Optional
- Returns
- Return type
dict
- Raises
- user_albums(*args, **kwargs)[source]¶
Albums owned by current user
- Parameters
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- property user_creds¶
- user_playlists(*args, **kwargs)[source]¶
Lists playlists owned by a user
- Parameters
user_id –
Optional
Defaults to user’s
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- user_profile(*args, **kwargs)[source]¶
List a user’s profile
- Parameters
user_id (str) –
Required
- Returns
- Return type
dict
- Raises
- user_top_artists(*args, **kwargs)[source]¶
List top artists of a user
- Parameters
time_range –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- user_top_tracks(*args, **kwargs)[source]¶
List top tracks of a user
- Parameters
time_range –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
- user_tracks(*args, **kwargs)[source]¶
List user’s tracks
- Parameters
market –
Optional
limit –
Optional
offset –
Optional
- Returns
- Return type
dict
- Raises
Exceptions API ⚠️¶
- exception pyfy.excs.ApiError(msg, http_response=None, http_request=None, e=None)[source]¶
Bases:
pyfy.excs.SpotifyError
Almost any HTTP error other than 401 raises this error https://developer.spotify.com/documentation/web-api/#response-schema // regular error object
- msg¶
Error msg returned from Spotify
- Type
str
- http_response¶
Full HTTP response
- http_request¶
Full HTTP request that caused this error
- code¶
HTTP status code
- Type
int
- args¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception pyfy.excs.AuthError(msg, http_response=None, http_request=None, e=None)[source]¶
Bases:
pyfy.excs.SpotifyError
Raised when a 401 or any Authentication error is encountered https://developer.spotify.com/documentation/web-api/#response-schema // authentication error object
- msg¶
Error msg returned from Spotify
- Type
str
- http_response¶
Full HTTP response
- http_request¶
Full HTTP request that caused this error
- code¶
HTTP status code
- Type
int
- args¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
Credentials API 📇¶
- pyfy.creds.ALL_SCOPES = ['streaming', 'app-remote-control', 'user-follow-modify', 'user-follow-read', 'playlist-read-private', 'playlist-modify-private', 'playlist-read-collaborative', 'playlist-modify-public', 'user-modify-playback-state', 'user-read-playback-state', 'user-read-currently-playing', 'user-read-private', 'user-read-email', 'user-library-read', 'user-library-modify', 'user-top-read', 'user-read-recently-played']¶
List of all scopes provided by Spotify
- class pyfy.creds.ClientCreds(client_id=None, client_secret=None, scopes=None, redirect_uri=None, show_dialog=False)[source]¶
Bases:
pyfy.creds._Creds
OAuth2 Client Credentials
- Parameters
client_id (str) – OAuth2 client_id
client_secret (str) – OAuth2 client_secret
scopes (list) – OAuth2 scopes. Defaults to all scopes
redirect_uri (str) – OAuth2 redirect uri. Defaults to http://localhost
show_dialog (bool) – if set to false, Spotify will not show a new authentication request if user already authorized the client
- property access_is_expired¶
Returns:
bool: Whether access token expired or not
- get(key)¶
- property is_oauth_ready¶
- load_from_env()[source]¶
Load client creds from OS environment
SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET and SPOTiFY_REDIRECT_URI environment variables must be present
- load_from_json(path=None, name=None)¶
Loads credentials from JSON file
- Parameters
path (str) – path of the directory the file is located in
name (str) – name of the file.
- pickle(path=None, name=None)¶
Pickles Credentials
- Parameters
path (str) – path of the directory to store pickle in
name (str) – name of the file.
- save_as_json(path=None, name=None)¶
Saves credentials as a json file
- Parameters
path (str) – path of the directory you want to save the file in
name (str) – name of the file.
- classmethod unpickle(path=None, name=None)¶
Loads a Credentials Pickle from file
- Parameters
path (str) – path of the directory you want to unpickle from
name (str) – name of the file.
- class pyfy.creds.UserCreds(access_token=None, refresh_token=None, scopes=None, expiry=None, user_id=None)[source]¶
Bases:
pyfy.creds._Creds
OAuth2 User Credentials + Spotify’s User info
Note
For convenience, if you set the populate_user_creds flag to True in any of Pyfy’s clients, this will set all of Spotify’s basic information on user to this model
- Parameters
access_token (str) – OAuth2 access token
refresh_token (str) – OAuth2 refresh token
scopes (list) – OAuth2 scopes
expiry (datetime.datetime) – Datetime access token expires
user_id (str) – Not to be confused with OpenID, this is the user’s Spotify ID
- birthdate¶
From Spotify’s /me endpoint
- Type
str
- country¶
From Spotify’s /me endpoint
- Type
str
- display_name¶
From Spotify’s /me endpoint
- Type
str
- email¶
From Spotify’s /me endpoint
- Type
str
- external_urls¶
From Spotify’s /me endpoint
- Type
dict
- followers¶
From Spotify’s /me endpoint
- Type
dict
- href¶
From Spotify’s /me endpoint
- Type
str
- id¶
From Spotify’s /me endpoint
- Type
str
- images¶
From Spotify’s /me endpoint
- Type
list
- product¶
From Spotify’s /me endpoint
- Type
str
- type¶
From Spotify’s /me endpoint
- Type
str
- uri¶
From Spotify’s /me endpoint
- Type
str
- property access_is_expired¶
Returns:
bool: Whether access token expired or not
- get(key)¶
- load_from_env()[source]¶
Load user creds from env
SPOTIFY_ACCESS_TOKEN and SPOTIFY_REFRESH_TOKEN environment variables must be present
This method will not fail if it didn’t find a refresh token, but will fail if no access token was found
- load_from_json(path=None, name=None)¶
Loads credentials from JSON file
- Parameters
path (str) – path of the directory the file is located in
name (str) – name of the file.
- pickle(path=None, name=None)¶
Pickles Credentials
- Parameters
path (str) – path of the directory to store pickle in
name (str) – name of the file.
- save_as_json(path=None, name=None)¶
Saves credentials as a json file
- Parameters
path (str) – path of the directory you want to save the file in
name (str) – name of the file.
- classmethod unpickle(path=None, name=None)¶
Loads a Credentials Pickle from file
- Parameters
path (str) – path of the directory you want to unpickle from
name (str) – name of the file.
Testing 👩🔬¶
Unit tests¶
$ tox
Integration tests¶
Open tox.ini and change thoee values to:
SPOTIFY_CLIENT_ID
Create an appSPOTIFY_CLIENT_SECRET
Create an appSPOTIFY_ACCESS_TOKEN
Get one or perform OAuth2 Auth Code Flow.Note
Check all scopes when getting an access token.
SPOTIFY_REFRESH_TOKEN
Note
To avoid manually refreshing your access token from the dev console, run the Oauth2 example in the examples dir. Then copy and paste the refresh token returned to your tox file.
SPOTIFY_REDIRECT_URI = 'http://localhost:5000/callback/spotify'
Note
You have to register this callback in your Application’s dashboard https://developer.spotify.com/dashboard/applications
PYFY_TEST_INTEGRATION_SYNC` = true
PYFY_TEST_INTEGRATION_ASYNC = true
Run:
Note
This will run some tests using your client ID, client secret and access token.
Unfortunately Spotify does not have a sandbox API, so we have to test it against the live API
Tests will carefully teardown all resources created and/or modified
Integration tests will not be abusive to the API and should only test for successful integration with minimum API calls
OAuth2 flow isn’t tested in the tests folder (yet). Instead you can manually test it in the examples folder by running:
pip install flask pyfy && python examples/oauth2.py
$ tox