Welcome to Pyfy’s documentation!¶

Pyfy is an Async/Sync Pythonic Spotify Client

Features 📯¶

  • Async and Sync clients
  • Authenticate using:
    1. OAuth2 client credentials flow
    2. OAuth2 authroization code flow
    3. Access token only authorization
  • Covers every parameter for every endpoint in Spotify’s Web API
  • Automatically refreshes tokens for clients and users
  • Descriptive errors
  • Able to automatically default to user’s locales
  • Rate limiting
  • HTTP and SOCKS proxies
  • HTTP caching (Sync only)
  • Unit and integration tested
  • Fit for both production and experimental/personal environments
  • Begginner friendly interface
  • Almost identical Async and Sync Interfaces

Setup 🥁¶

Pip

$ pip install pyfy

Quick Start 🎛️¶

Sync

from pyfy import Spotify

spt = Spotify('your_access_token')

spt.user_playlists()
spt.play()
spt.volume(85)
spt.next()
spt.pause()
results = spt.search(q='alice in chains them bones')
print(results)

Async

1. Make a single call:

import asyncio
from pyfy import AsyncSpotify

spt = AsyncSpotify('your_access_token')

async def query():
    return await spt.search('Like a motherless child')

asyncio.run(query())

Or even:

awaited_search_result = asyncio.run(spt.search('A tout le monde'))

2. Make multiple calls using a single TCP connection (no async/await syntax):

from pprint import pprint
from pyfy import AsyncSpotify

spt = AsyncSpotify('your_access_token')

gathered_results = spt.gather_now(
    spt.search('Seize the day', to_gather=True),
    spt.search('Feel good inc', to_gather=True),
    spt.search('In your room', to_gather=True),
    spt.search('Tout Petit Moineau', to_gather=True)
)

pprint(gathered_results)

3. To manually await the results:

import asyncio
from pyfy import AsyncSpotify

spt = AsyncSpotify('your_access_token')

async def search():
    return await spt.gather(
        spt.search('Saeed', to_gather=True),
        spt.search('Killing time', to_gather=True),
        spt.search('Project 100', to_gather=True),
        spt.search('Tout Petit Moineau', to_gather=True)
    )

results = asyncio.run(search())

Authentication and Authorization 👩‍🎤¶

1. With User’s Access Token: get from here

from pyfy import Spotify

spt = Spotify('your access token')

2. With Client Credentials Flow (OAauth2): get from here

from pyfy import ClientCreds, Spotify

client = ClientCreds(client_id=client_id, client_secret=client_secret)
spt = Spotify(client_creds=client)
spt.authorize_client_creds()

3. With Authorization Code Flow (OAuth2) examples with Sanic(async) and Flask(sync)

from pyfy import Spotify, ClientCreds, UserCreds, AuthError, ApiError

client = ClientCreds(client_id='clientid', client_secret='client_secret')
spt = Spotify(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)

Load User and Client Credentials 👨‍🎤¶

# Instantiate directly
client = ClientCreds(client_id='aclientid', client_secret='averysecrettoken')

# Load from environment
client = ClientCreds()
client.load_from_env()

# Load from json file
client = ClientCreds()
client.load_from_json(path='full/dir/path', name='name_of_the_json_file')

# From a pickle
client = ClientCreds.unpickle()

Sync Client 🎸¶

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:

pyfy.excs.ApiError

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:

pyfy.excs.ApiError

albums(*args, **kwargs)[source]¶

List Albums

Parameters:
  • album_ids (str, list) –
    • Required
  • market –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

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:

pyfy.excs.ApiError

List artists related to an artist

Parameters:artist_id (str) –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
artist_top_tracks(*args, **kwargs)[source]¶

List top tracks of an artist

Parameters:
  • artist_id (str) –
    • Required
  • country –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

artists(*args, **kwargs)[source]¶

List artists

Parameters:artist_ids (str, list) –
Returns:
  • Required
Return type:dict
Raises:pyfy.excs.ApiError
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:pyfy.excs.ApiError
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:

pyfy.creds.UserCreds

categories(*args, **kwargs)[source]¶

List Categories

Parameters:
  • country –
    • Optional
  • locale –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

category(*args, **kwargs)[source]¶

List Category

Parameters:
  • category_id –
    • Required
  • country –
    • Optional
  • locale –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

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:

pyfy.excs.ApiError

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:

pyfy.excs.ApiError

currently_playing(*args, **kwargs)[source]¶

Lists currenly playing

Parameters:market (str) –
  • Optional
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
currently_playing_info(*args, **kwargs)[source]¶

Lists currently playing info

Parameters:market (str) –
  • Optional
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
delete_albums(*args, **kwargs)[source]¶

Delete Albums

Parameters:album_ids (str, list) –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
delete_playlist(*args, **kwargs)[source]¶

An alias to unfollow_playlist

Parameters:playlist_id –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
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:

pyfy.excs.ApiError

delete_tracks(*args, **kwargs)[source]¶

Delete user’s tracks

Parameters:track_ids (str, list) –
Returns:
  • Required
Return type:dict
Raises:pyfy.excs.ApiError
devices(*args, **kwargs)[source]¶

Lists user’s devices

Returns:
Return type:dict
Raises:pyfy.excs.ApiError
featured_playlists(*args, **kwargs)[source]¶

Featured Playlists

Parameters:
  • country –
    • Optional
  • locale –
    • Optional
  • timestamp –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

follow_artists(*args, **kwargs)[source]¶

Follow an artist(s)

Parameters:artist_ids (str, list) –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
follow_playlist(*args, **kwargs)[source]¶

Follows a playlist

Parameters:
  • playlist_id –
    • Required
  • public –
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

follow_users(*args, **kwargs)[source]¶

Follow a user

Parameters:user_ids (str, list) –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
followed_artists(*args, **kwargs)[source]¶

List artists followed by current user

Parameters:
  • after –
    • Optional
  • limit –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

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:pyfy.excs.ApiError
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:

pyfy.excs.ApiError

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:pyfy.excs.ApiError
is_active¶

Checks if user_creds or client_creds are valid (depending on who was last set)

is_oauth_ready¶

Whether Client Credentials have enough information to perform OAuth2 Authorization Code FLow

Returns

bool:
is_premium¶

Checks whether user is premium or not

Returns:
Return type:bool
me(*args, **kwargs)[source]¶

List current user’s profile

Returns:
Return type:dict
Raises:pyfy.excs.ApiError
new_releases(*args, **kwargs)[source]¶

New Releases

Parameters:
  • country –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

next(*args, **kwargs)[source]¶

Next playback

Parameters:device_id –
  • Optional
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
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:

pyfy.excs.ApiError

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:pyfy.excs.ApiError
owns_tracks(*args, **kwargs)[source]¶

Lists whether or not current user owns tracks

Parameters:track_ids (str, list) –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
pause(*args, **kwargs)[source]¶

Pauses playback

Parameters:device_id (str) –
  • Optional
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
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:

pyfy.excs.ApiError

playback_transfer(*args, **kwargs)[source]¶

Transfer playback to another device

Parameters:device_ids (list, str) –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
playlist(*args, **kwargs)[source]¶

Lists playlist

Parameters:
  • playlist_id –
    • Required
  • market –
    • Optional
  • fields –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

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:

pyfy.excs.ApiError

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:pyfy.excs.ApiError
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:

pyfy.excs.ApiError

recently_played_tracks(*args, **kwargs)[source]¶

Lists recently played tracks

Parameters:
  • limit (int) –
    • Optional
  • after –
    • Optional
  • before –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

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:

pyfy.excs.ApiError

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:

pyfy.excs.ApiError

repeat(*args, **kwargs)[source]¶

Toggle repeat

Parameters:
  • state –
    • Optional
    • Default: ‘context’
  • device_id –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

save_albums(*args, **kwargs)[source]¶

Save Albums

Parameters:album_ids (str, list) –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
save_tracks(*args, **kwargs)[source]¶

Save tracks

Parameters:track_ids (str, list) –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
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:

pyfy.excs.ApiError

seek(*args, **kwargs)[source]¶

Seek Playback

Parameters:
  • posiotion_ms –
    • Required
  • device_id –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

shuffle(*args, **kwargs)[source]¶

Shuffle Playback

Parameters:
  • state –
    • Optional
    • Default: True
  • device_id –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

track_audio_analysis(*args, **kwargs)[source]¶

List audio analysis of a track

Parameters:track_id –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
tracks(*args, **kwargs)[source]¶

List tracks

Parameters:
  • track_ids (str, list) –
    • Required
  • market –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

tracks_audio_features(*args, **kwargs)[source]¶

List audio features of tracks

Parameters:track_ids (str, list) –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
unfollow_artists(*args, **kwargs)[source]¶

Unfollow artist(s)

Parameters:artist_ids (str, list) –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
unfollow_playlist(*args, **kwargs)[source]¶

Unfollow a playlist

Parameters:playlist_id –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
unfollow_users(*args, **kwargs)[source]¶

Unfollow user(s)

Parameters:user_ids (str, list) –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
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:

pyfy.excs.ApiError

user_albums(*args, **kwargs)[source]¶

Albums owned by current user

Parameters:
  • limit –
    • Optional
  • offset –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

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:

pyfy.excs.ApiError

user_profile(*args, **kwargs)[source]¶

List a user’s profile

Parameters:user_id (str) –
  • Required
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
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:

pyfy.excs.ApiError

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:

pyfy.excs.ApiError

user_tracks(*args, **kwargs)[source]¶

List user’s tracks

Parameters:
  • market –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

volume(*args, **kwargs)[source]¶

Change volume

Parameters:
  • volume_percent (int) –
    • Required
  • device_id –
    • Optional
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

Async Client 🎼¶

class pyfy.async_client.AsyncSpotify(access_token=None, client_creds=<pyfy.creds.ClientCreds object>, user_creds=None, proxies=None, proxy_auth=None, timeout=7, max_retries=10, backoff_factor=0.1, default_to_locale=True, populate_user_creds=True, max_connections=1000)[source]¶

Bases: pyfy.base_client._BaseClient

Spotify’s Asynchronous 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 – Aiohttp proxy https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support
  • proxy_auth – Aiohttp proxy auth https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support
  • 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
  • populate_user_creds (bool) –
    • Sets user_creds info from Spotify to client’s user_creds object. e.g. country.
    • Default: True
  • max_connections (int) –
    • Max TCP connections per host from the same session
    • Default: 1000
IS_ASYNC = True¶
coroutine add_playlist_tracks(*args, **kwargs)[source]¶

Add tracks to a playlist

Parameters:
  • playlist_id –
    • Required
  • track_ids (str, list) –
    • Required
  • position –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine album_tracks(*args, **kwargs)[source]¶

List tracks of an album

Parameters:
  • album_id (str) –
    • Required
  • market –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine albums(*args, **kwargs)[source]¶

List Albums

Parameters:
  • album_ids (str, list) –
    • Required
  • market –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine artist_albums(*args, **kwargs)[source]¶

List albums of an artist

Parameters:
  • artist_id (str) –
    • Required
  • include_groups –
    • Optional
  • market –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

List artists related to an artist

Parameters:
  • artist_id (str) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine artist_top_tracks(*args, **kwargs)[source]¶

List top tracks of an artist

Parameters:
  • artist_id (str) –
    • Required
  • country –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine artists(*args, **kwargs)[source]¶

List artists

Parameters:
  • artist_ids (str, list) –
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

  • Required

Return type:

dict

Raises:

pyfy.excs.ApiError

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

coroutine 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
coroutine available_genre_seeds(*args, **kwargs)[source]¶

Available genre seeds

Parameters:to_gather (bool) –
  • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
  • Optional
  • Default: False
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
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:

pyfy.creds.UserCreds

coroutine categories(*args, **kwargs)[source]¶

List Categories

Parameters:
  • country –
    • Optional
  • locale –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine category(*args, **kwargs)[source]¶

List Category

Parameters:
  • category_id –
    • Required
  • country –
    • Optional
  • locale –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine category_playlist(*args, **kwargs)[source]¶

List playlists from a category

Parameters:
  • category_id –
    • Required
  • country –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine create_playlist(*args, **kwargs)[source]¶

Creates a playlist

Parameters:
  • name –
    • Required
  • description –
    • Optional
  • public –
    • Optional
    • Default: False
  • collaborative –
    • Optional
    • default: False
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine currently_playing(*args, **kwargs)[source]¶

Lists currenly playing

Parameters:
  • market (str) –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine currently_playing_info(*args, **kwargs)[source]¶

Lists currently playing info

Parameters:
  • market (str) –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine delete_albums(*args, **kwargs)[source]¶

Delete Albums

Parameters:
  • album_ids (str, list) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine delete_playlist(*args, **kwargs)[source]¶

An alias to unfollow_playlist

Parameters:
  • playlist_id –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine 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
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine delete_tracks(*args, **kwargs)[source]¶

Delete user’s tracks

Parameters:
  • track_ids (str, list) –
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

  • Required

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine devices(*args, **kwargs)[source]¶

Lists user’s devices

Parameters:to_gather (bool) –
  • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
  • Optional
  • Default: False
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
coroutine featured_playlists(*args, **kwargs)[source]¶

Featured Playlists

Parameters:
  • country –
    • Optional
  • locale –
    • Optional
  • timestamp –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine follow_artists(*args, **kwargs)[source]¶

Follow an artist(s)

Parameters:
  • artist_ids (str, list) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine follow_playlist(*args, **kwargs)[source]¶

Follows a playlist

Parameters:
  • playlist_id –
    • Required
  • public –
    • Optional
    • Default: False
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine follow_users(*args, **kwargs)[source]¶

Follow a user

Parameters:
  • user_ids (str, list) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine followed_artists(*args, **kwargs)[source]¶

List artists followed by current user

Parameters:
  • after –
    • Optional
  • limit –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine follows_artists(*args, **kwargs)[source]¶

Whether or not current user follows an artist(s)

Parameters:
  • artist_ids (str, list) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine follows_playlist(*args, **kwargs)[source]¶

Lists whether or not user follows a playlist

Parameters:
  • playlist_id –
    • Required
  • user_ids (list, str) –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine follows_users(*args, **kwargs)[source]¶

Whether or not current user follows a user(s)

Parameters:
  • user_ids (str, list) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine gather(*coros, return_exceptions=False, refresh_first=False)[source]¶

Use this insead of manually gathering individual requests to make all your requests that are to be gathered share one TCP connection

Note

It is recommended that you leave return_exceptions as False, as setting it to true will return exceptions as str instead of raising them. Having exceptions fly by isn’t a really a great idea.

Parameters:
gather_now(*coros, return_exceptions=False, refresh_first=False)[source]¶

Use this insead of manually gathering individual requests to make all your requests that are to be gathered share one TCP connection

same as async def AsyncSpotify.gather but can be called synchronously. Only works if there’s no loop running. Use the gather method if you have one already running.

Note

It is recommended that you leave return_exceptions as False, as setting it to true will return exceptions as str instead of raising them. Having exceptions fly by isn’t a really a great idea.

Parameters:
is_active¶

Checks if user_creds or client_creds are valid (depending on who was last set)

is_oauth_ready¶

Whether Client Credentials have enough information to perform OAuth2 Authorization Code FLow

Returns

bool:
is_premium¶

Checks whether user is premium or not

Returns:
Return type:bool
coroutine me(*args, **kwargs)[source]¶

List current user’s profile

Parameters:to_gather (bool) –
  • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
  • Optional
  • Default: False
Returns:
Return type:dict
Raises:pyfy.excs.ApiError
coroutine new_releases(*args, **kwargs)[source]¶

New Releases

Parameters:
  • country –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine next(*args, **kwargs)[source]¶

Next playback

Parameters:
  • device_id –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine 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
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine owns_albums(*args, **kwargs)[source]¶

Whether or not current user owns an album(s)

Parameters:
  • album_ids (str, list) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine owns_tracks(*args, **kwargs)[source]¶

Lists whether or not current user owns tracks

Parameters:
  • track_ids (str, list) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine pause(*args, **kwargs)[source]¶

Pauses playback

Parameters:
  • device_id (str) –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine 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
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine playback_transfer(*args, **kwargs)[source]¶

Transfer playback to another device

Parameters:
  • device_ids (list, str) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine playlist(*args, **kwargs)[source]¶

Lists playlist

Parameters:
  • playlist_id –
    • Required
  • market –
    • Optional
  • fields –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine playlist_tracks(*args, **kwargs)[source]¶

List tracks in a playlist

Parameters:
  • playlist_id –
    • Required
  • market –
    • Optional
  • fields –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine 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

coroutine previous(*args, **kwargs)[source]¶

Previous Playback

Parameters:
  • device_id –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine 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
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine recently_played_tracks(*args, **kwargs)[source]¶

Lists recently played tracks

Parameters:
  • limit (int) –
    • Optional
  • after –
    • Optional
  • before –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine 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
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine reorder_playlist_track(*args, **kwargs)[source]¶

Reorder tracks in a playlist

Parameters:
  • playlist_id –
    • Required
  • range_start –
    • Optional
  • range_length –
    • Optional
  • insert_before –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine repeat(*args, **kwargs)[source]¶

Toggle repeat

Parameters:
  • state –
    • Optional
    • Default: ‘context’
  • device_id –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine save_albums(*args, **kwargs)[source]¶

Save Albums

Parameters:
  • album_ids (str, list) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine save_tracks(*args, **kwargs)[source]¶

Save tracks

Parameters:
  • track_ids (str, list) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine 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
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine seek(*args, **kwargs)[source]¶

Seek Playback

Parameters:
  • posiotion_ms –
    • Required
  • device_id –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine shuffle(*args, **kwargs)[source]¶

Shuffle Playback

Parameters:
  • state –
    • Optional
    • Default: True
  • device_id –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine track_audio_analysis(*args, **kwargs)[source]¶

List audio analysis of a track

Parameters:
  • track_id –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine tracks(*args, **kwargs)[source]¶

List tracks

Parameters:
  • track_ids (str, list) –
    • Required
  • market –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine tracks_audio_features(*args, **kwargs)[source]¶

List audio features of tracks

Parameters:
  • track_ids (str, list) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine unfollow_artists(*args, **kwargs)[source]¶

Unfollow artist(s)

Parameters:
  • artist_ids (str, list) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine unfollow_playlist(*args, **kwargs)[source]¶

Unfollow a playlist

Parameters:
  • playlist_id –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine unfollow_users(*args, **kwargs)[source]¶

Unfollow user(s)

Parameters:
  • user_ids (str, list) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine update_playlist(*args, **kwargs)[source]¶

Updates a playlist

Parameters:
  • playlist_id –
    • Required
  • name –
    • Optional
  • description –
    • Optional
  • public –
    • Optional
  • collaborative –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine user_albums(*args, **kwargs)[source]¶

Albums owned by current user

Parameters:
  • limit –
    • Optional
  • offset –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

user_creds¶
coroutine user_playlists(*args, **kwargs)[source]¶

Lists playlists owned by a user

Parameters:
  • user_id –
    • Optional
    • Defaults to user’s
  • limit –
    • Optional
  • offset –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine user_profile(*args, **kwargs)[source]¶

List a user’s profile

Parameters:
  • user_id (str) –
    • Required
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine user_top_artists(*args, **kwargs)[source]¶

List top artists of a user

Parameters:
  • time_range –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine user_top_tracks(*args, **kwargs)[source]¶

List top tracks of a user

Parameters:
  • time_range –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine user_tracks(*args, **kwargs)[source]¶

List user’s tracks

Parameters:
  • market –
    • Optional
  • limit –
    • Optional
  • offset –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

coroutine volume(*args, **kwargs)[source]¶

Change volume

Parameters:
  • volume_percent (int) –
    • Required
  • device_id –
    • Optional
  • to_gather (bool) –
    • Whether or not this resource/method will be gathered with AsyncSpotify.gather or AsyncSpotify.gather_now
    • Optional
    • Default: False
Returns:

Return type:

dict

Raises:

pyfy.excs.ApiError

Exceptions ⚠️¶

exception pyfy.excs.ApiError(msg, http_response=None, http_request=None, e=None)[source]¶

Bases: pyfy.excs.SpotifyError

Almost any HTTP error other that 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.

exception pyfy.excs.SpotifyError[source]¶

Bases: Exception

Base error class for ApiError and AuthError

args¶
with_traceback()¶

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

Credentials 📇¶

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-birthdate', '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
access_is_expired¶

Whether access token expired or not

Type:Returns
Type:bool
get(key)¶
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
access_is_expired¶

Whether access token expired or not

Type:Returns
Type:bool
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¶

  1. Open tox.ini and change thoee values to:

    1. SPOTIFY_CLIENT_ID Create an app

    2. SPOTIFY_CLIENT_SECRET Create an app

    3. SPOTIFY_ACCESS_TOKEN Get one or perform OAuth2 Auth Code Flow.

      Note

      Check all scopes when getting an access token.

    4. 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.

    5. 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

    6. PYFY_TEST_INTEGRATION_SYNC` = true

    7. PYFY_TEST_INTEGRATION_ASYNC = true

  2. Run:

    Warning

    • 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
    

Contribution¶

All contributions are welcome :)

Contributors¶

Indices and tables¶