API Reference¶
Main Classes¶
Deezer¶
- class yutipy.deezer.Deezer
Bases:
BaseServiceA class to interact with the Deezer API.
- close_session() None
Closes the current session(s).
- get_album(album_id: int) Album | None
Retrieves album information for a given album ID. Use it if you already have the album ID from Deezer.
- Parameters:
album_id (int) – The ID of the album.
- Returns:
An Album object containing album information or None if not found.
- Return type:
Album | None
- get_track(track_id: int) Track | None
Retrieves track information for a given track ID. Use it if you already have the track ID from Deezer.
- Parameters:
track_id (int) – The ID of the track.
- Returns:
A Track object containing track information or None if not found.
- Return type:
Track | None
- search(artist: str = '', song: str = '', limit: int = 10) List[Track | Album] | None
Searches for a song by artist and title.
- Parameters:
artist (str, optional) – The name of the artist.
song (str, optional) – The title of the song.
limit (int, optional) – The number of items to retrieve from API.
limit >= 1 and <= 50. Default is10.
- Returns:
A list of Track or Album objects containing search results, or None if an error occurs.
- Return type:
list[Track | Album] | None
- Raises:
InvalidValueException – If the artist or song names are invalid or if the limit is out of range.
iTunes¶
- class yutipy.itunes.Itunes
Bases:
BaseServiceA class to interact with the iTunes API.
- close_session() None
Closes the current session(s).
- search(artist: str = '', song: str = '', limit: int = 10) List[Track | Album] | None
Searches for a song by artist and title.
- Parameters:
artist (str, optional) – The name of the artist.
song (str, optional) – The title of the song.
limit (int, optional) – The number of items to retrieve from API.
limit >= 1 and <= 50. Default is10.
- Returns:
A list of Track or Album objects if found, otherwise None.
- Return type:
list[Track | Album] | None
- Raises:
InvalidValueException – If the artist or song name is invalid, or if the limit is out of range.
KKBox¶
- class yutipy.kkbox.KKBox(client_id: str | None = None, client_secret: str | None = None, defer_load: bool = False)
Bases:
BaseClientA class to interact with KKBOX Open API.
This class reads the
KKBOX_CLIENT_IDandKKBOX_CLIENT_SECRETfrom environment variables or the.envfile by default. Alternatively, you can manually provide these values when creating an object.- Parameters:
client_id (str, optional) – The Client ID for the KKBOX Open API. Defaults to
KKBOX_CLIENT_IDfrom .env file.client_secret (str, optional) – The Client secret for the KKBOX Open API. Defaults to
KKBOX_CLIENT_SECRETfrom .env file.defer_load (bool, optional) – Whether to defer loading the access token during initialization. Default is
False.
- Raises:
AuthenticationException – If the Client ID or Client Secret is not provided.
- close_session() None
Closes the current session(s).
- get_album(album_id: str, territory: str = 'SG') Album | None
Retrieves album information for a given album ID. Use it if you already have the album ID from KKBox.
- Parameters:
album_id (int) – The ID of the album.
territory (str) – Two-letter country codes from ISO 3166-1 alpha-2. Default is
SG. Allowed values:HK,JP,MY,SG,TW.
- Returns:
An Album object containing album information or None if not found.
- Return type:
Album | None
- Raises:
InvalidValueException – If the input values are invalid.
- get_artist(artist_id: str, territory: str = 'SG') Artist | None
Retrieves artist information for a given artist ID. Use it if you already have the artist ID from KKBox.
- Parameters:
artist_id (str) – The ID of the artist.
territory (str) – Two-letter country codes from ISO 3166-1 alpha-2. Default is
SG. Allowed values:HK,JP,MY,SG,TW.
- Returns:
An Artist object containing artist information or None if not found.
- Return type:
Artist | None
- Raises:
InvalidValueException – If the input values are invalid.
- get_html_widget(id: str, content_type: str, territory: str = 'SG', widget_lang: str = 'EN', autoplay: bool = False, loop: bool = False) str
Return KKBOX HTML widget for “Playlist”, “Album” or “Song”. It does not return actual HTML code, the URL returned can be used in an HTML
iframewith the help ofsrcattribute.- Parameters:
id (str) –
IDof playlist, album or track.content_type (str) – Content type can be
playlist,albumorsong.territory (str, optional) – Territory code, i.e. “TW”, “HK”, “JP”, “SG”, “MY”, by default “SG”
widget_lang (str, optional) – The display language of the widget. Can be “TC”, “SC”, “JA”, “EN”, “MS”, by default “EN”
autoplay (bool, optional) – Whether to start playing music automatically in widget, by default False
loop (bool, optional) – Repeat/loop song(s), by default False
- Returns:
KKBOX HTML widget URL.
- Return type:
str
- get_track(track_id: str, territory: str = 'SG') Track | None
Retrieves track information for a given track ID. Use it if you already have the track ID from KKBox.
- Parameters:
track_id (int) – The ID of the track.
territory (str) – Two-letter country codes from ISO 3166-1 alpha-2. Default is
SG. Allowed values:HK,JP,MY,SG,TW.
- Returns:
A Track object containing track information or None if not found.
- Return type:
Track | None
- Raises:
InvalidValueException – If the input values are invalid.
- load_access_token() dict
Loads the access token and related information.
This method must be overridden in a subclass to retrieve the access token and other related information (e.g., expiration time) from persistent storage. If not implemented, the access token will not be loaded, and it will be requested each time the application restarts.
- Returns:
A dictionary containing the access token and related information, such as refresh token, expiration time, etc., or None if no token is found.
- Return type:
dict | None
- Raises:
NotImplementedError – If the method is not overridden in a subclass.
- load_token_after_init() None
Explicitly load the access token after initialization. This is useful when
defer_loadis set toTrueduring initialization.
- save_access_token(token_info: dict) None
Saves the access token and related information.
This method must be overridden in a subclass to persist the access token and other related information (e.g., expiration time). If not implemented, the access token will not be saved, and it will be requested each time the application restarts.
- Parameters:
token_info (dict) – A dictionary containing the access token and related information, such as refresh token, expiration time, etc.
- Raises:
NotImplementedError – If the method is not overridden in a subclass.
- search(artist: str = '', song: str = '', territory: str = 'SG', limit: int = 10) List[Track | Album] | None
Searches for a song by artist and title.
- Parameters:
artist (str, optional) – The name of the artist.
song (str, optional) – The title of the song.
territory (str) – Two-letter country codes from ISO 3166-1 alpha-2. Default is
SG. Allowed values:HK,JP,MY,SG,TW.limit (int, optional) – The number of items to retrieve from API.
limit >= 1 and <= 50. Default is10.
- Returns:
A list of Track and Album objects matching the search criteria, or None if no results found.
- Return type:
list[Track | Album] | None
- Raises:
InvalidValueException – If the input values are invalid.
Lastfm¶
- class yutipy.lastfm.LastFm(api_key: str | None = None)
Bases:
BaseServiceA class to interact with the Last.fm API for fetching user music data.
This class reads the
LASTFM_API_KEYfrom environment variables or the.envfile by default. Alternatively, you can manually provide this values when creating an object.- Parameters:
lastfm_api_key (str, optional) – The Lastfm API Key (<https://www.last.fm/api>). Defaults to
LASTFM_API_KEYfrom environment variable or the.envfile.- Raises:
AuthenticationException – If the Lastfm API key is not provided or found in environment variables.
- close_session() None
Closes the current session(s).
- get_currently_playing(username: str) dict | None
Fetches information about the currently playing track for a user.
- Parameters:
username (str) – The Last.fm username to fetch data for.
- Returns:
A dictionary containing details about the currently playing track if available, or
Noneif the request fails or no data is available.- Return type:
dict | None
- get_user_profile(username: str) dict | None
Fetches the user profile information for the provided username.
- Parameters:
username (str) – The Last.fm username to fetch profile information for.
- Returns:
A dictionary containing the user’s profile information or
Noneif username does not exist.- Return type:
dict | None
Spotify¶
- class yutipy.spotify.Spotify(client_id: str | None = None, client_secret: str | None = None, defer_load: bool = False)
Bases:
BaseClientA class to interact with the Spotify API. It uses “Client Credentials” grant type (or flow).
This class reads the
SPOTIFY_CLIENT_IDandSPOTIFY_CLIENT_SECRETfrom environment variables or the.envfile by default. Alternatively, you can manually provide these values when creating an object.- Parameters:
client_id (str, optional) – The Client ID for the Spotify API. Defaults to
SPOTIFY_CLIENT_IDfrom environment variable or the.envfile.client_secret (str, optional) – The Client secret for the Spotify API. Defaults to
SPOTIFY_CLIENT_SECRETfrom environment variable or the.envfile.defer_load (bool, optional) – Whether to defer loading the access token during initialization, by default
False
- Raises:
AuthenticationException – If the Client ID or Client Secret is not provided.
- close_session() None
Closes the current session(s).
- get_album(album_id: str) Album | None
Retrieves album information for a given album ID. Use it if you already have the album ID from Spotify.
- Parameters:
album_id (str) – The ID of the album.
- Returns:
An Album object containing album information or None if not found.
- Return type:
Album | None
- get_artist(artist_id: str) Artist | None
Retrieves artist information for a given artist ID. Use it if you already have the artist ID from Spotify.
- Parameters:
artist_id (str) – The ID of the artist.
- Returns:
An Artist object containing artist information or None if not found.
- Return type:
Artist | None
- get_track(track_id: str) Track | None
Retrieves track information for a given track ID. Use it if you already have the track ID from Spotify.
- Parameters:
track_id (str) – The ID of the track.
- Returns:
A Track object containing track information or None if not found.
- Return type:
Track | None
- load_access_token() dict
Loads the access token and related information.
This method must be overridden in a subclass to retrieve the access token and other related information (e.g., expiration time) from persistent storage. If not implemented, the access token will not be loaded, and it will be requested each time the application restarts.
- Returns:
A dictionary containing the access token and related information, such as refresh token, expiration time, etc., or None if no token is found.
- Return type:
dict | None
- Raises:
NotImplementedError – If the method is not overridden in a subclass.
- load_token_after_init() None
Explicitly load the access token after initialization. This is useful when
defer_loadis set toTrueduring initialization.
- save_access_token(token_info: dict) None
Saves the access token and related information.
This method must be overridden in a subclass to persist the access token and other related information (e.g., expiration time). If not implemented, the access token will not be saved, and it will be requested each time the application restarts.
- Parameters:
token_info (dict) – A dictionary containing the access token and related information, such as refresh token, expiration time, etc.
- Raises:
NotImplementedError – If the method is not overridden in a subclass.
- search(artist: str = '', song: str = '', limit: int = 10) List[Track | Album] | None
Searches for a song by artist and title.
- Parameters:
artist (str, optional) – The name of the artist.
song (str, optional) – The title of the song.
limit (int, optional) – The number of items to retrieve from API.
limit >= 1 and <= 50. Default is10.
- Returns:
The music information if found, otherwise None.
- Return type:
list[Track | Album] | None
- Raises:
InvalidValueException – If the input values are invalid.
- class yutipy.spotify.SpotifyAuth(client_id: str | None = None, client_secret: str | None = None, redirect_uri: str | None = None, scopes: list[str] = [], defer_load: bool = False)
Bases:
BaseAuthClientA class to interact with the Spotify API. It uses “Authorization Code” grant type (or flow).
This class reads the
SPOTIFY_CLIENT_ID,SPOTIFY_CLIENT_SECRETandSPOTIFY_REDIRECT_URIfrom environment variables or the.envfile by default. Alternatively, you can manually provide these values when creating an object.- Parameters:
client_id (str, optional) – The Client ID for the Spotify API. Defaults to
SPOTIFY_CLIENT_IDfrom environment variable or the.envfile.client_secret (str, optional) – The Client secret for the Spotify API. Defaults to
SPOTIFY_CLIENT_SECRETfrom environment variable or the.envfile.redirect_uri (str, optional) – The Redirect URI for the Spotify API. Defaults to
SPOTIFY_REDIRECT_URIfrom environment variable or the.envfile.scopes (list[str], optional) – A list of scopes for the Spotify API. For example: [‘user-read-email’, ‘user-read-private’].
defer_load (bool, optional) – Whether to defer loading the access token during initialization. Default is
False.
- Raises:
AuthenticationException – If the Client ID or Client Secret is not provided.
- callback_handler(code, state, expected_state)
Handles the callback phase of the OAuth 2.0 authorization process.
This method processes the authorization code and state returned by Spotify after the user has granted permission. It validates the state to prevent CSRF attacks, exchanges the authorization code for an access token, and saves the token for future use.
- Parameters:
code (str) – The authorization code returned by Spotify after user authorization.
state (str) – The state parameter returned by Spotify to ensure the request’s integrity.
expected_state (str) – The original state parameter sent during the authorization request, used to validate the response.
- Raises:
SpotifyAuthException – If the returned state does not match the expected state.
Notes
This method can be used in a web application (e.g., Flask) in the /callback route to handle successful authorization.
Ensure that the
save_access_tokenandload_access_tokenmethods are implemented in a subclass if token persistence is required.
- close_session() None
Closes the current session(s).
- static generate_state() str
Generates a random state string for use in OAuth 2.0 authorization.
This method creates a cryptographically secure, URL-safe string that can be used to prevent cross-site request forgery (CSRF) attacks during the authorization process.
- Returns:
A random URL-safe string to be used as the state parameter in OAuth 2.0.
- Return type:
str
- get_authorization_url(state: str = '', show_dialog: bool = False) str
Constructs the Spotify authorization URL for user authentication.
This method generates a URL that can be used to redirect users to Spotify’s authorization page for user authentication.
- Parameters:
state (str, optional) –
A random string to maintain state between the request and callback. If not provided, no state parameter is included.
You may use
SpotifyAuth.generate_state()method to generate one.show_dialog (bool, optional) – Whether or not to force the user to approve the app again if they’ve already done so. If
False(default), a user who has already approved the application may be automatically redirected to the URI specified by redirect_uri. IfTrue, the user will not be automatically redirected and will have to approve the app again.
- Returns:
The full authorization URL to redirect users for Spotify authentication.
- Return type:
str
- get_currently_playing() CurrentlyPlaying | None
Fetches information about the currently playing track for the authenticated user.
- Returns:
An instance of the
CurrentlyPlayingmodel containing details about the currently playing track if available, orNoneif no track is currently playing or an error occurs.- Return type:
CurrentlyPlaying | None
Notes
The user must have granted the necessary permissions (e.g., user-read-currently-playing scope) for this method to work.
If the API response does not contain the expected data, the method will return None.
- get_user_profile() dict | None
Fetches the user’s display name and profile images.
Notes
user-read-emailanduser-read-privatescopes are required to access user profile information.
- Returns:
A dictionary containing the user’s display name and profile images.
- Return type:
dict | None
- load_access_token() dict
Loads the access token and related information.
This method must be overridden in a subclass to retrieve the access token and other related information (e.g., refresh token, expiration time) from persistent storage. If not implemented, the access token will not be loaded, and users will need to re-authenticate after application restarts.
- Returns:
A dictionary containing the access token and related information, such as refresh token, expiration time, etc., or None if no token is found.
- Return type:
dict | None
- Raises:
NotImplementedError – If the method is not overridden in a subclass.
- load_token_after_init()
Explicitly load the access token after initialization. This is useful when
defer_loadis set toTrueduring initialization.
- save_access_token(token_info: dict) None
Saves the access token and related information.
This method must be overridden in a subclass to persist the access token and other related information (e.g., refresh token, expiration time). If not implemented, the access token will not be saved, and users will need to re-authenticate after application restarts.
- Parameters:
token_info (dict) – A dictionary containing the access token and related information, such as refresh token, expiration time, etc.
- Raises:
NotImplementedError – If the method is not overridden in a subclass.
YouTube Music¶
- class yutipy.musicyt.MusicYT
Bases:
BaseServiceA class to interact with the YouTube Music API.
Initializes the service and sets up the session.
- Parameters:
service_name (str) – The service name class belongs to. For example, “ExampleService”.
service_url (str) – The service URL for the music service.
api_url (str) – The base API URL for the service.
session (bool, optional) – Whether to create a session for API calls. Default is
True.
- close_session() None
Closes the current session(s).
- property is_session_closed: bool
Checks if the session is closed.
- search(artist: str = '', song: str = '', limit: int = 10) List[Track | Album] | None
Searches for a song by artist and title.
- Parameters:
artist (str, optional) – The name of the artist.
song (str, optional) – The title of the song.
limit (int, optional) – The number of the items to retrieve from API.
limit >= 1 and <= 50. Default is10.
- Returns:
A list of Track or Album objects if found, otherwise None.
- Return type:
list[Track | Album] | None
- Raises:
InvalidValueException – If the input values are invalid.
Data Classes¶
Album¶
- class yutipy.models.Album(artists: List[ForwardRef('Artist')] | None = None, cover: str | None = None, duration: int | None = None, explicit: bool | None = None, genres: List[str] | None = None, id: int | None = None, label: str | None = None, release_date: str | None = None, title: str | None = None, total_tracks: int | None = None, tracks: List[ForwardRef('Track')] | None = None, type: str | None = None, upc: str | None = None, url: str | None = None, service_name: str | None = None, service_url: str | None = None)
Bases:
BaseModel- artists: List[Artist] | None = None
- cover: str | None = None
- duration: int | None = None
- explicit: bool | None = None
- genres: List[str] | None = None
- id: int | None = None
- label: str | None = None
- release_date: str | None = None
- service_name: str | None = None
- service_url: str | None = None
- title: str | None = None
- total_tracks: int | None = None
- tracks: List[Track] | None = None
- type: str | None = None
- upc: str | None = None
- url: str | None = None
Artist¶
- class yutipy.models.Artist(genres: List[str] | None = None, id: int | None = None, name: str | None = None, picture: str | None = None, role: str | None = None, url: str | None = None, service_name: str | None = None, service_url: str | None = None)
Bases:
BaseModel- genres: List[str] | None = None
- id: int | None = None
- name: str | None = None
- picture: str | None = None
- role: str | None = None
- service_name: str | None = None
- service_url: str | None = None
- url: str | None = None
Track¶
- class yutipy.models.Track(album: ForwardRef('Album') | None = None, artists: List[ForwardRef('Artist')] | None = None, bpm: float | None = None, duration: int | None = None, explicit: bool | None = None, genre: str | None = None, gain: float | None = None, id: int | None = None, isrc: str | None = None, preview_url: str | None = None, release_date: str | None = None, title: str | None = None, track_number: int | None = None, url: str | None = None, service_name: str | None = None, service_url: str | None = None)
Bases:
BaseModel- album: Album | None = None
- artists: List[Artist] | None = None
- bpm: float | None = None
- duration: int | None = None
- explicit: bool | None = None
- gain: float | None = None
- genre: str | None = None
- id: int | None = None
- isrc: str | None = None
- preview_url: str | None = None
- release_date: str | None = None
- service_name: str | None = None
- service_url: str | None = None
- title: str | None = None
- track_number: int | None = None
- url: str | None = None
CurrentlyPlaying¶
- class yutipy.models.CurrentlyPlaying(album: ForwardRef('Album') | None = None, artists: List[ForwardRef('Artist')] | None = None, bpm: float | None = None, duration: int | None = None, explicit: bool | None = None, genre: str | None = None, gain: float | None = None, id: int | None = None, isrc: str | None = None, preview_url: str | None = None, release_date: str | None = None, title: str | None = None, track_number: int | None = None, url: str | None = None, service_name: str | None = None, service_url: str | None = None, timestamp: int | None = None, progress: int | None = None, is_playing: bool | None = None, currently_playing_type: str | None = None)
Bases:
Track- album: Album | None = None
- artists: List[Artist] | None = None
- bpm: float | None = None
- currently_playing_type: str | None = None
- duration: int | None = None
- explicit: bool | None = None
- gain: float | None = None
- genre: str | None = None
- id: int | None = None
- is_playing: bool | None = None
- isrc: str | None = None
- preview_url: str | None = None
- progress: int | None = None
- release_date: str | None = None
- service_name: str | None = None
- service_url: str | None = None
- timestamp: int | None = None
- title: str | None = None
- track_number: int | None = None
- url: str | None = None
Exceptions¶
Base Exception¶
- class yutipy.exceptions.YutipyException
Bases:
ExceptionBase class for exceptions in the yutipy package.
Generic Exceptions¶
- class yutipy.exceptions.AuthenticationException
Bases:
YutipyExceptionException raised for authentication related errors.
This exception should be used when authentication fails, such as when invalid credentials are provided or required authentication tokens are missing.
- message
Explanation of the authentication error.
- Type:
str
- class yutipy.exceptions.InvalidValueException
Bases:
YutipyExceptionException raised for invalid values to the function arguments.
This exception should be used when a function receives an argument with a value that is not acceptable or outside the expected range.
- message
Explanation of the error.
- Type:
str