API

Inheritance diagram of musify.libraries.remote.core.api

The framework for interacting with a remote API.

All methods that interact with the API should return raw, unprocessed responses.

Classes:

RemoteAPI(authoriser,Β wrangler[,Β cache])

Collection of endpoints for a remote API.

class musify.libraries.remote.core.api.RemoteAPI(authoriser, wrangler, cache=None)

Bases: Generic

Collection of endpoints for a remote API. See RequestHandler and Authoriser for more info on which params to pass to authorise and execute requests.

Parameters:
  • wrangler (RemoteDataWrangler) – The RemoteDataWrangler for this API type.

  • authoriser (TypeVar(A, bound= Authoriser)) – The authoriser to use when authorising requests to the API.

  • cache (ResponseCache | None (default: None)) – When given, attempt to use this cache for certain request types before calling the API. Repository and cachable request types can be set up by child classes.

Attributes:

collection_item_map

Map of RemoteObjectType for remote collections to the RemoteObjectType of the items they hold

user_item_types

A set of possible saved item types that can be retrieved for the currently authenticated user

id_key

The key to use when getting an ID from a response

url_key

The key to use when getting the URL from a response

user_id

ID of the currently authorised user

user_name

Name of the currently authorised user

url

The base URL of the API

source

The name of the API service

logger

The MusifyLogger for this object

wrangler

A RemoteDataWrangler object for processing URIs

handler

The RequestHandler for handling authorised requests to the API

user_data

Stores the loaded user data for the currently authorised user

user_playlist_data

Stores the loaded user playlists data for the currently authorised user

Methods:

authorise()

Main method for authorisation, tests/refreshes/reauthorises as needed

close()

Close the current session.

load_user()

Load and store user data for the currently authorised user in this API object

load_user_playlists()

Load and store user playlists data for the currently authorised user in this API object

print_item(i,Β name,Β uri[,Β length,Β total,Β ...])

Pretty print item data for displaying to the user.

print_collection([value,Β kind,Β limit])

Pretty print collection data for displaying to the user.

get_playlist_url(playlist)

Determine the type of the given playlist and return its API URL.

get_self([update_user_data])

GET - Get API response for information on current user

query(query,Β kind[,Β limit])

GET - Query for items.

extend_items(response[,Β kind,Β key,Β leave_bar])

Extend the items for a given API response.

get_items(values[,Β kind,Β limit,Β extend])

GET - Get information for given values.

get_tracks(values[,Β limit])

Wrapper for get_items() which only returns Track type responses.

get_user_items([user,Β kind,Β limit])

GET - Get saved items for a given user.

create_playlist(name,Β *args,Β **kwargs)

POST - Create an empty playlist for the current user with the given name.

add_to_playlist(playlist,Β items[,Β limit,Β ...])

POST - Add list of tracks to a given playlist.

get_or_create_playlist(name,Β *args,Β **kwargs)

Attempt to find the playlist with the given name and return it.

follow_playlist(playlist,Β *args,Β **kwargs)

PUT - Follow a given playlist.

delete_playlist(playlist)

DELETE - Unfollow/delete a given playlist.

clear_from_playlist(playlist[,Β items,Β limit])

DELETE - Clear tracks from a given playlist.

collection_item_map = {RemoteObjectType.PLAYLIST: RemoteObjectType.TRACK, RemoteObjectType.ALBUM: RemoteObjectType.TRACK, RemoteObjectType.SHOW: RemoteObjectType.EPISODE, RemoteObjectType.AUDIOBOOK: RemoteObjectType.CHAPTER}

Map of RemoteObjectType for remote collections to the RemoteObjectType of the items they hold

user_item_types = {RemoteObjectType.PLAYLIST, RemoteObjectType.TRACK, RemoteObjectType.ALBUM, RemoteObjectType.ARTIST, RemoteObjectType.SHOW, RemoteObjectType.EPISODE, RemoteObjectType.AUDIOBOOK}

A set of possible saved item types that can be retrieved for the currently authenticated user

id_key = 'id'

The key to use when getting an ID from a response

url_key = 'href'

The key to use when getting the URL from a response

abstract property user_id: str | None

ID of the currently authorised user

abstract property user_name: str | None

Name of the currently authorised user

property url: URL

The base URL of the API

property source: str

The name of the API service

logger: MusifyLogger

The MusifyLogger for this object

wrangler

A RemoteDataWrangler object for processing URIs

handler: RequestHandler[TypeVar(A, bound= Authoriser), dict[str, str | int | float | list | dict | bool | None]]

The RequestHandler for handling authorised requests to the API

user_data: dict[str, Any]

Stores the loaded user data for the currently authorised user

user_playlist_data: dict[str, dict[str, Any]]

Stores the loaded user playlists data for the currently authorised user

async authorise()

Main method for authorisation, tests/refreshes/reauthorises as needed

Returns:

Self – Self.

Raises:

APIError – If the token cannot be validated.

async close()

Close the current session. No more requests will be possible once this has been called.

Return type:

None

async load_user()

Load and store user data for the currently authorised user in this API object

Return type:

None

abstract async load_user_playlists()

Load and store user playlists data for the currently authorised user in this API object

Return type:

None

print_item(i, name, uri, length=0, total=1, max_width=50)

Pretty print item data for displaying to the user. Format = <i> - <name> | <length> | <URI> - <URL>.

Parameters:
  • i (int) – The position of this item in the collection.

  • name (str) – The name of the item.

  • uri (str) – The URI of the item.

  • length (float (default: 0)) – The duration of the item in seconds.

  • total (int (default: 1)) – The total number of items in the collection

  • max_width (int (default: 50)) – The maximum width to print names as. Any name lengths longer than this will be truncated.

Return type:

None

abstract async print_collection(value=None, kind=None, limit=20)

Pretty print collection data for displaying to the user. Runs print_item() for each item in the collection.

value may be:
  • A string representing a URL/URI/ID.

  • A remote API JSON response for a collection with a valid ID value under an id key.

  • A RemoteResponse representing some remote collection of items.

Parameters:
  • value (GenericAlias[RemoteResponse] | None (default: None)) – The value representing some remote collection. See description for allowed value types.

  • kind (RemoteIDType | None (default: None)) – When an ID is provided, give the kind of ID this is here. If None and ID is given, user will be prompted to give the kind anyway.

  • limit (int (default: 20)) – The number of results to call per request and, therefore, the number of items in each printed block.

Return type:

None

abstract async get_playlist_url(playlist)

Determine the type of the given playlist and return its API URL. If type cannot be determined, attempt to find the playlist in the list of the currently authenticated user’s playlists.

Parameters:

playlist (GenericAlias[RemoteResponse]) – In URL/URI/ID form, or the name of one of the currently authenticated user’s playlists.

Returns:

URL – The playlist URL.

Raises:

RemoteIDTypeError – Raised when the function cannot determine the item type of the input playlist. Or when it does not recognise the type of the input playlist parameter.

abstract async get_self(update_user_data=True)

GET - Get API response for information on current user

Parameters:

update_user_data (bool (default: True)) – When True, update the _user_data stored in this API object.

Return type:

dict[str, Any]

abstract async query(query, kind, limit=10)

GET - Query for items. Modify result types returned with kind parameter

Parameters:
  • query (str) – Search query.

  • kind (RemoteObjectType) – The remote object type to search for.

  • limit (int (default: 10)) – Number of results to get and return.

Returns:

list[dict[str, Any]] – The response from the endpoint.

abstract async extend_items(response, kind=None, key=None, leave_bar=None)

Extend the items for a given API response. The function requests each page of the collection returning a list of all items found across all pages for this URL.

Updates the value of the items key in-place by extending the value of the items key with new results.

If a RemoteResponse, this function will not refresh it with the new response. The user must call refresh manually after execution.

Parameters:
  • response (MutableMapping[str, Any] | RemoteResponse) – A remote API JSON response for an items type endpoint.

  • kind (RemoteObjectType | str | None (default: None)) – The type of response being extended. Optional, used only for logging.

  • key (RemoteObjectType | None (default: None)) – The type of response of the child objects.

  • leave_bar (bool | None (default: None)) – When a progress bar is displayed, toggle whether this bar should continue to be displayed after the operation is finished. When None, allow the logger to decide this setting.

Returns:

list[dict[str, Any]] – API JSON responses for each item

abstract async get_items(values, kind=None, limit=50, extend=True)

GET - Get information for given values.

values may be:
  • A string representing a URL/URI/ID.

  • A MutableSequence of strings representing URLs/URIs/IDs of the same type.

  • A remote API JSON response for a collection.

  • A MutableSequence of remote API JSON responses for a collection.

  • A RemoteResponse of the appropriate type for this RemoteAPI which holds a valid API JSON response as described above.

  • A Sequence of RemoteResponses as above.

If JSON response(s) given, this updates each response given by merging with the new response.

If RemoteResponse values are given, this function will call refresh on them.

Parameters:
  • values (GenericAlias[RemoteResponse]) – The values representing some remote objects. See description for allowed value types. These items must all be of the same type of item i.e. all tracks OR all artists etc.

  • kind (RemoteObjectType | None (default: None)) – Item type if given string is ID.

  • limit (int (default: 50)) – When requests can be batched, size of batches to request. This value will be limited to be between 1 and 50.

  • extend (bool (default: True)) – When True and the given kind is a collection of items, extend the response to include all items in this collection.

Returns:

list[dict[str, Any]] – API JSON responses for each item.

Raises:

RemoteObjectTypeError – Raised when the function cannot determine the item type of the input values. Or when it does not recognise the type of the input values parameter.

abstract async get_tracks(values, limit=50, *args, **kwargs)

Wrapper for get_items() which only returns Track type responses. See get_items() for more info.

Return type:

list[dict[str, Any]]

abstract async get_user_items(user=None, kind=RemoteObjectType.PLAYLIST, limit=50)

GET - Get saved items for a given user.

Parameters:
  • user (str | None (default: None)) – The ID of the user to get playlists for. If None, use the currently authenticated user.

  • kind (RemoteObjectType (default: <RemoteObjectType.PLAYLIST: 1>)) – Item type to retrieve for the user.

  • limit (int (default: 50)) – Size of each batch of items to request in the collection items request. This value will be limited to be between 1 and 50.

Returns:

list[dict[str, Any]] – API JSON responses for each collection.

Raises:
abstract async create_playlist(name, *args, **kwargs)

POST - Create an empty playlist for the current user with the given name.

Parameters:

name (str) – Name of playlist to create.

Returns:

dict[str, Any] – API JSON response for the created playlist.

abstract async add_to_playlist(playlist, items, limit=50, skip_dupes=True)

POST - Add list of tracks to a given playlist.

Parameters:
  • playlist (GenericAlias[RemoteResponse]) – One of the following to identify the playlist to clear: - playlist URL/URI/ID, - the name of the playlist in the current user’s playlists, - the API response of a playlist. - a RemoteResponse object representing a remote playlist.

  • items (Sequence[str]) – List of URLs/URIs/IDs of the tracks to add.

  • limit (int (default: 50)) – Size of each batch of IDs to add. This value will be limited to be between 1 and 50.

  • skip_dupes (bool (default: True)) – Skip duplicates.

Returns:

int – The number of tracks added to the playlist.

Raises:
  • RemoteIDTypeError – Raised when the input playlist does not represent a playlist URL/URI/ID.

  • RemoteObjectTypeError – Raised when the item types of the input items are not all tracks or IDs.

async get_or_create_playlist(name, *args, **kwargs)

Attempt to find the playlist with the given name and return it. Otherwise, create a new playlist.

Any given args and kwargs are passed directly onto create_playlist() when a matching loaded playlist is not found.

When a playlist is created, persist the response back to the loaded playlists in this object.

Parameters:

name (str) – The case-sensitive name of the playlist to get/create.

Returns:

dict[str, Any] – API JSON response for the loaded/created playlist.

async follow_playlist(playlist, *args, **kwargs)

PUT - Follow a given playlist.

Parameters:

playlist (GenericAlias[RemoteResponse]) – One of the following to identify the playlist to clear: - playlist URL/URI/ID, - the name of the playlist in the current user’s playlists, - the API response of a playlist. - a RemoteResponse object representing a remote playlist.

Returns:

URL – API URL for playlist.

abstract async delete_playlist(playlist)

DELETE - Unfollow/delete a given playlist. WARNING: This function will destructively modify your remote playlists.

Parameters:

playlist (GenericAlias[RemoteResponse]) – One of the following to identify the playlist to clear: - playlist URL/URI/ID, - the name of the playlist in the current user’s playlists, - the API response of a playlist. - a RemoteResponse object representing a remote playlist.

Returns:

URL – API URL for playlist.

abstract async clear_from_playlist(playlist, items=None, limit=100)

DELETE - Clear tracks from a given playlist. WARNING: This function can destructively modify your remote playlists.

Parameters:
  • playlist (GenericAlias[RemoteResponse]) – One of the following to identify the playlist to clear: - playlist URL/URI/ID, - the name of the playlist in the current user’s playlists, - the API response of a playlist. - a RemoteResponse object representing a remote playlist.

  • items (Collection[str] | None (default: None)) – List of URLs/URIs/IDs of the tracks to remove. If None, clear all songs from the playlist.

  • limit (int (default: 100)) – Size of each batch of IDs to clear in a single request. This value will be limited to be between 1 and 100.

Returns:

int – The number of tracks cleared from the playlist.

Raises:
  • RemoteIDTypeError – Raised when the input playlist does not represent a playlist URL/URI/ID.

  • RemoteObjectTypeError – Raised when the item types of the input items are not all tracks or IDs.