### Install SpotAPI Source: https://github.com/aran404/spotapi/blob/main/README.md Install the SpotAPI library using pip. ```bash pip install spotapi ``` -------------------------------- ### Install SpotAPI with Optional Extras Source: https://context7.com/aran404/spotapi/llms.txt Install the base SpotAPI library using pip. Optional extras for WebSocket support, MongoDB, or Redis session storage can be included. ```bash pip install spotapi # Optional extras pip install spotapi[websocket] # WebSocket / real-time events pip install spotapi[pymongo] # MongoDB session storage pip install spotapi[redis] # Redis session storage ``` -------------------------------- ### Public API Example: Paginate Songs Source: https://github.com/aran404/spotapi/blob/main/README.md Example of paginating through songs by a given artist without user authentication. This demonstrates fetching songs in batches. ```python from spotapi import Song song = Song() gen = song.paginate_songs("weezer") # Paginates 100 songs at a time till there's no more for batch in gen: for idx, item in enumerate(batch): print(idx, item['item']['data']['name']) ``` -------------------------------- ### User Authentication with SpotAPI Source: https://github.com/aran404/spotapi/blob/main/README.md Example of logging in with user credentials, creating a private playlist, and saving the session. Requires a Capsolver API key and optionally a proxy. ```python from spotapi import ( Login, Config, NoopLogger, solver_clients, PrivatePlaylist, MongoSaver ) cfg = Config( solver=solver_clients.Capsolver("YOUR_API_KEY", proxy="YOUR_PROXY"), # Proxy is optional logger=NoopLogger(), # You can add a proxy by passing a custom TLSClient ) instance = Login(cfg, "YOUR_PASSWORD", email="YOUR_EMAIL") # Now we have a valid Login instance to pass around instance.login() # Do whatever you want now playlist = PrivatePlaylist(instance) playlist.create_playlist("SpotAPI Showcase!") # Save the session instance.save(MongoSaver()) ``` -------------------------------- ### Public API Example: Query Specific Number of Songs Source: https://github.com/aran404/spotapi/blob/main/README.md Example of querying a specific number of songs by a given artist without user authentication. This demonstrates fetching a limited set of results. ```python # Alternatively, you can query a specfic amount songs = song.query_songs("weezer", limit=20) data = songs["data"]["searchV2"]["tracksV2"]["items"] for idx, item in enumerate(data): print(idx, item['item']['data']['name']) ``` -------------------------------- ### Get Plan Information Source: https://github.com/aran404/spotapi/blob/main/docs/user.md Retrieves detailed information about the user's current plan. ```APIDOC ## get_plan_info(self) -> Mapping[str, Any] ### Description Retrieves the user's plan information. ### Returns - `Mapping[str, Any]` - A dictionary containing the user's plan information. ### Raises - `UserError` if there is an issue retrieving the plan information or if the response is not in the expected format. ``` -------------------------------- ### Get User Information Source: https://github.com/aran404/spotapi/blob/main/docs/user.md Retrieves the user's account information. ```APIDOC ## get_user_info(self) -> Mapping[str, Any] ### Description Retrieves the user's account information. ### Returns - `Mapping[str, Any]` - A dictionary containing the user's account information. ### Raises - `UserError` if there is an issue retrieving the user information or if the response is not in the expected format. ``` -------------------------------- ### EventManager Class Initialization Source: https://github.com/aran404/spotapi/blob/main/docs/status.md Initializes the EventManager class, which extends PlayerStatus. It sets up and starts a websocket listener in a separate thread for real-time event management. ```APIDOC ## EventManager Class ### Description Extends `PlayerStatus` and adds functionality for subscribing to and managing events from the Spotify websocket. ### Parameters - **login**: `Login` - The login instance used for authentication. - **s_device_id**: `Optional[str]` - The device ID to use for the player. If `None`, a new device ID will be generated. ### Method `__init__(self, login: Login, s_device_id: str | None = None) -> None` ### Args: - `login`: `Login` - The login instance for authentication. - `s_device_id`: `Optional[str]` - The device ID for the player (optional). ``` -------------------------------- ### PublicAlbum - Get album info Source: https://context7.com/aran404/spotapi/llms.txt Fetches information about a public album. ```APIDOC ## PublicAlbum - Get album info ### Description Retrieves detailed information for a public album using its ID or URL. ### Method `PublicAlbum.get_album_info(limit: int = 25)` ### Parameters #### Path Parameters - **album_id_or_url** (str) - Required - The ID or full URL of the album. - **limit** (int) - Optional - The maximum number of tracks to return. Defaults to 25. ### Response Example ```json { "data": { "albumUnion": { "name": "OK Computer", "artists": { "items": [ { "profile": { "name": "Radiohead" } } ] } } } } ``` ``` -------------------------------- ### Get Full Track Metadata by ID Source: https://context7.com/aran404/spotapi/llms.txt Fetches detailed metadata for a given track ID and prints its name. Ensure the 'song' object is initialized. ```python info = song.get_track_info("4uLU6hMCjMI75M1A2tKUQC") print(info["data"]["trackUnion"]["name"]) ``` -------------------------------- ### Artist - Get artist overview Source: https://context7.com/aran404/spotapi/llms.txt Retrieves a full overview of an artist by their Spotify ID. ```APIDOC ## Artist - Get artist overview ### Description Fetches detailed information about an artist using their Spotify ID. ### Method `Artist.get_artist(artist_id: str)` ### Parameters #### Path Parameters - **artist_id** (str) - Required - The Spotify ID of the artist. ### Response Example ```json { "data": { "artistUnion": { "profile": { "name": "Radiohead" } } } } ``` ``` -------------------------------- ### PublicPlaylist - Get playlist info Source: https://context7.com/aran404/spotapi/llms.txt Fetches metadata and tracks for any public playlist. ```APIDOC ## PublicPlaylist - Get playlist info ### Description Retrieves information and tracks for a public playlist using its ID or URL. ### Method `PublicPlaylist.get_playlist_info(limit: int = 50, offset: int = 0, language: str = 'en')` ### Parameters #### Path Parameters - **playlist_id_or_url** (str) - Required - The ID or full URL of the public playlist. - **limit** (int) - Optional - The maximum number of tracks to return. Defaults to 50. - **offset** (int) - Optional - The number of tracks to skip. Defaults to 0. - **language** (str) - Optional - The language for the response. Defaults to 'en'. ### Response Example ```json { "data": { "playlistV2": { "name": "Today's Top Hits", "content": { "totalCount": 50 } } } } ``` ``` -------------------------------- ### PrivatePlaylist Class Source: https://github.com/aran404/spotapi/blob/main/docs/playlist.md Interact with a playlist while logged in, enabling operations such as adding to and removing from the library, creating, and getting recommendations. ```APIDOC ## PrivatePlaylist ### Description Allows interaction with a playlist while logged in, enabling operations such as adding to and removing from the library, creating, and getting recommendations. ### Parameters - **login**: `Login` - The login object used for authenticated requests. - **playlist**: `str | None` - The Spotify URI of the playlist. If provided, it is used to initialize the playlist. ### Methods #### `__init__(self, login: Login, playlist: str | None = None) -> None` Initializes the `PrivatePlaylist` class with a `Login` object and an optional playlist URI. - **Raises:** `ValueError` if not logged in or if playlist ID cannot be extracted from the provided URI. #### `set_playlist(self, playlist: str) -> None` Sets or updates the playlist ID. - **Args:** - `playlist`: `str` - The Spotify URI or ID of the playlist to set. - **Raises:** `ValueError` if the playlist URI is invalid. #### `add_to_library(self) -> None` Adds the playlist to the user's library. - **Raises:** `ValueError` if the playlist ID is not set. `PlaylistError` if there is an issue adding the playlist. #### `remove_from_library(self) -> None` Removes the playlist from the user's library. - **Raises:** `ValueError` if the playlist ID is not set. `PlaylistError` if there is an issue removing the playlist. #### `delete_playlist(self) -> None` Deletes the playlist from the user's library. This is the same as removing it from the library. - **Raises:** `ValueError` if the playlist ID is not set. `PlaylistError` if there is an issue deleting the playlist. #### `get_saved_tracks_info(self, limit: int = 25, *, offset: int = 0) -> Mapping[str, Any]` Fetches information about the user's Liked Songs. - **Args:** - `limit`: `int` - The maximum number of results to return. Default is 25. - `offset`: `int` - The offset for pagination. Default is 0. - **Returns:** `Mapping[str, Any]` - The saved tracks information. - **Raises:** `PlaylistError` if there is an issue retrieving the playlist information or if the response is invalid. #### `paginate_saved_tracks(self) -> Generator[Mapping[str, Any], None, None]` Generator that fetches Liked Songs information in chunks. - **Returns:** `Generator[Mapping[str, Any], None, None]` - A generator yielding playlist information in chunks. - **Note:** If the total number of tracks is 343 or fewer, pagination is not required. #### `get_library(self, limit: int = 50, /) -> Mapping[str, Any]` Fetches all playlists in the user's library. - **Args:** - `limit`: `int` - The maximum number of playlists to return. Default is 50. - **Returns:** `Mapping[str, Any]` - The user's library information. - **Raises:** `PlaylistError` if there is an issue retrieving the library information. ``` -------------------------------- ### Fetch Podcast Episode Information Source: https://github.com/aran404/spotapi/blob/main/docs/public.md Get detailed information for a specific podcast episode using its Spotify ID. This method returns a dictionary with the episode's details. ```python episode = Public.podcast_episode_info("1HpkG1StJQsNN09awYFTB3") print(episode) ``` -------------------------------- ### Initialize PublicAlbum with Language Support Source: https://github.com/aran404/spotapi/blob/main/docs/album.md Demonstrates initializing the PublicAlbum with a specific language ('ko') and retrieving album information. It also shows how to change the language at runtime. ```python from spotapi import PublicAlbum # Initialize with Korean language album = PublicAlbum("4m2880jivSbbyEGAKfITCa", language="ko") # Get album info with Korean language responses info = album.get_album_info() # Change language at runtime album.base.set_language("zh") # Switch to Chinese ``` -------------------------------- ### __init__ Source: https://github.com/aran404/spotapi/blob/main/docs/player.md Initializes the Player class and sets up the player to interact with the specified device or active device. ```APIDOC ## __init__(self, login: Login, device_id: str | None = None) -> None ### Description Initializes the `Player` class and sets up the player to interact with the specified device or active device. ### Parameters - **`login (Login)`**: The login instance used for authentication. - **`device_id (str, optional)`**: The device ID to connect to for the player. If not provided, it will use the active device. - **`use_active_device (bool)`**: If True, the player will use the active device. ### Example ```python login_instance = Login(username, password) player = Player(login_instance) ``` ``` -------------------------------- ### Get Username Source: https://github.com/aran404/spotapi/blob/main/docs/user.md Retrieves the username of the user. ```APIDOC ## username(self) -> str ### Description Property that returns the username of the user. ### Returns - `str` - The user's username. ``` -------------------------------- ### Initializing and Switching Languages Source: https://context7.com/aran404/spotapi/llms.txt Shows how to initialize SpotAPI objects with a specific language and how to switch the language at runtime. Supports any ISO 639-1 code. ```python from spotapi import Artist, PublicPlaylist, Song # Initialize with a specific language artist = Artist(language="ko") playlist = PublicPlaylist("37i9dQZF1DXcBWIGoYBM5M", language="ja") # Switch language at runtime song = Song(language="en") song.base.set_language("zh") # now returns Chinese-locale responses # Supported: any ISO 639-1 code — ko, ja, zh, en, de, fr, es, ... ``` -------------------------------- ### Initialize Song Class with Korean Language Support Source: https://github.com/aran404/spotapi/blob/main/docs/song.md Demonstrates initializing the Song class with a specific language ('ko' for Korean) and performing a song search. It also shows how to change the language at runtime. ```python from spotapi import Song # Initialize with Korean language song_ko = Song(language="ko") # Search for songs with Korean responses results = song_ko.query_songs("BTS", limit=20) # Change language at runtime song_ko.base.set_language("ja") # Switch to Japanese ``` -------------------------------- ### Initialize PublicPlaylist with Language Support Source: https://github.com/aran404/spotapi/blob/main/docs/playlist.md Demonstrates initializing the PublicPlaylist class with a specific language and then changing it at runtime. Ensure the correct playlist URI and language codes are used. ```python from spotapi import PublicPlaylist # Initialize with Korean language playlist = PublicPlaylist("37i9dQZF1DXcBWIGoYBM5M", language="ko") # Get playlist info with Korean language responses info = playlist.get_playlist_info() # Change language at runtime playlist.base.set_language("ja") # Switch to Japanese ``` -------------------------------- ### Podcast - Get episode Source: https://context7.com/aran404/spotapi/llms.txt Fetches data for a specific podcast episode by its ID. ```APIDOC ## Podcast - Get episode ### Description Retrieves detailed information for a specific podcast episode using its unique ID. ### Method `Podcast.get_episode(episode_id: str)` ### Parameters #### Path Parameters - **episode_id** (str) - Required - The unique identifier of the podcast episode. ### Response Example ```json { "data": { "episodeUnionV2": { "name": "Episode Name" } } } ``` ``` -------------------------------- ### Initialize SpotAPI Objects with Language Source: https://github.com/aran404/spotapi/blob/main/docs/language.md Instantiate SpotAPI classes like Artist, Song, PublicPlaylist, and PublicAlbum with a specific language code to receive localized data. ```python from spotapi import Artist, Song, PublicPlaylist, PublicAlbum # Initialize with Korean language artist = Artist(language="ko") song = Song(language="ko") playlist = PublicPlaylist("37i9dQZF1DXcBWIGoYBM5M", language="ko") album = PublicAlbum("4m2880jivSbbyEGAKfITCa", language="ko") ``` -------------------------------- ### Language Support Source: https://context7.com/aran404/spotapi/llms.txt Explains how to initialize classes with a specific language and switch languages at runtime. ```APIDOC ## Language Support — ISO 639-1 locale codes Every public-facing class accepts a `language` keyword argument and supports runtime language switching via `base.set_language()`. ### Initialize with Specific Language ```python from spotapi import Artist, PublicPlaylist, Song # Initialize with a specific language artist = Artist(language="ko") playlist = PublicPlaylist("37i9dQZF1DXcBWIGoYBM5M", language="ja") ``` ### Switch Language at Runtime ```python from spotapi import Song song = Song(language="en") song.base.set_language("zh") # now returns Chinese-locale responses ``` ### Supported Languages Supported locales include any ISO 639-1 code (e.g., `ko`, `ja`, `zh`, `en`, `de`, `fr`, `es`). ``` -------------------------------- ### PrivatePlaylist - Get library Source: https://context7.com/aran404/spotapi/llms.txt Retrieves a paginated list of playlists in the user's library. ```APIDOC ## PrivatePlaylist - Get library ### Description Fetches a list of playlists that the user has saved in their library. ### Method `PrivatePlaylist.get_library(limit: int = 50)` ### Parameters #### Path Parameters - **limit** (int) - Optional - The maximum number of playlists to return per request. Defaults to 50. ### Response Example ```json { "data": { "me": { "libraryV3": { "items": [ { "item": { "data": { "name": "My SpotAPI Playlist" } } } ] } } } } ``` ``` -------------------------------- ### Initialize Player Instance Source: https://github.com/aran404/spotapi/blob/main/docs/player.md Initializes the Player class with a Login instance. If a device ID is not provided, it defaults to the active device. ```python login_instance = Login(username, password) player = Player(login_instance) ``` -------------------------------- ### Language Support in SpotAPI Source: https://github.com/aran404/spotapi/blob/main/README.md Demonstrates initializing SpotAPI clients with a specific language and changing the language at runtime. Supports ISO 639-1 codes. ```python from spotapi import Artist, PublicPlaylist, Song # Initialize with Korean language artist = Artist(language="ko") playlist = PublicPlaylist("37i9dQZF1DXcBWIGoYBM5M", language="ko") # Change language at runtime song = Song(language="en") song.base.set_language("ja") # Switch to Japanese # Supported languages: ko, ja, zh, en, and any ISO 639-1 code ``` -------------------------------- ### Get full track metadata by ID Source: https://context7.com/aran404/spotapi/llms.txt Retrieves comprehensive metadata for a given track ID. ```APIDOC ## Get full track metadata by ID ### Description Retrieves the full metadata for a track using its ID. ### Method `song.get_track_info(track_id: str)` ### Parameters #### Path Parameters - **track_id** (str) - Required - The unique identifier of the track. ### Response Example ```json { "data": { "trackUnion": { "name": "Never Gonna Give You Up" } } } ``` ``` -------------------------------- ### Initialize Artist with Language and Set Runtime Language Source: https://github.com/aran404/spotapi/blob/main/docs/artist.md Demonstrates initializing the Artist class with a specific language ('ko') and then changing the API request language at runtime ('ja'). Use this when you need to fetch artist data in a language other than the default 'en'. ```python from spotapi import Artist # Initialize with Korean language artist_ko = Artist(language="ko") # Change language at runtime artist_ko.base.set_language("ja") # Switch to Japanese # Query artist with Japanese responses results = artist_ko.get_artist("4tZwfgrHOc3mvqYlEYSvVi") ``` -------------------------------- ### Inspect Player State with PlayerStatus Source: https://context7.com/aran404/spotapi/llms.txt Instantiate PlayerStatus with a logged-in instance to inspect the current playback state, track information, and available devices. Requires an active login instance. ```python from spotapi import Login from spotapi.status import PlayerStatus login_instance = Login(...) # already logged in status = PlayerStatus(login_instance) state = status.state print(state.is_playing) # True / False print(state.is_paused) # True / False print(state.track.uri) # spotify:track:... print(state.options.shuffling_context) devices = status.device_ids print(devices.active_device_id) for dev_id, dev in devices.devices.items(): print(dev_id, dev.name, dev.volume) next_track = status.next_song_in_queue if next_track: print(next_track.uri) last = status.last_played if last: print(last.uri) ``` -------------------------------- ### Get Track Info Source: https://github.com/aran404/spotapi/blob/main/docs/song.md Retrieves detailed information about a specific song using its track ID. ```APIDOC ## get_track_info ### Description Retrieves detailed information about a specific song from the Spotify catalog using its track ID. ### Method `get_track_info(track_id: str)` ### Parameters #### Path Parameters - **track_id** (str) - Required - The ID of the song. Not the URI. ### Returns - `Mapping[str, Any]` - The raw track result. ### Raises: - `SongError` if there is an issue retrieving the song or if the response is invalid. ``` -------------------------------- ### Configure SpotAPI with Different Loggers and Solvers Source: https://context7.com/aran404/spotapi/llms.txt Create a Config object to bundle CAPTCHA solvers, loggers, and TLS clients for authenticated operations. Minimal configuration omits logging and proxies, while full configuration includes them. ```python from spotapi import Config, NoopLogger, Logger from spotapi.solvers import Capsolver, CapMonster from spotapi.http.request import TLSClient # Minimal config (no logging, no proxy) cfg = Config( solver=Capsolver("CAP_API_KEY"), logger=NoopLogger(), ) # Full config with a proxy and a custom TLS client cfg_full = Config( solver=Capsolver("CAP_API_KEY", proxy="user:pass@1.2.3.4:8080"), logger=Logger(), # colored stdout logger client=TLSClient("chrome_120", "", auto_retries=3), ) # CapMonster alternative cfg_cm = Config( solver=CapMonster("CM_API_KEY"), logger=NoopLogger(), ) ``` -------------------------------- ### Play Specific Track Source: https://github.com/aran404/spotapi/blob/main/docs/player.md Overrides the current playback and starts playing a specific track from a given playlist. Requires both track and playlist URIs. ```python player.play_track("spotify:track:6rqhFgbbKwnb9MLmUQDhG6", "spotify:playlist:37i9dQZF1DXcBWIGoYBM5M") ``` -------------------------------- ### PublicAlbum Initialization Source: https://github.com/aran404/spotapi/blob/main/docs/album.md Initializes the PublicAlbum class with an album URI and an optional TLSClient instance and language code. ```APIDOC ## PublicAlbum ### Description Initializes the `PublicAlbum` class with an optional album URI and a `TLSClient` instance. ### Parameters #### Path Parameters - **album** (str) - Required - The Spotify URI of the album, it is used to initialize the album. - **client** (TLSClient) - Optional - An instance of `TLSClient` used for making HTTP requests. Defaults to a new instance with specified parameters. - **language** (str) - Optional - The language for API responses using ISO 639-1 language codes (e.g., 'ko', 'ja', 'zh', 'en'). Default is 'en'. ``` -------------------------------- ### Saving and Restoring Sessions with Different Savers Source: https://context7.com/aran404/spotapi/llms.txt Demonstrates how to save and restore login sessions using JSON, SQLite, MongoDB, and Redis savers. Ensure the respective databases/services are running if using MongoDB or Redis. ```python from spotapi import Login, Config, NoopLogger, JSONSaver, MongoSaver from spotapi.utils.saver import SqliteSaver, RedisSaver from spotapi.solvers import Capsolver cfg = Config(solver=Capsolver("CAP_API_KEY"), logger=NoopLogger()) instance = Login(cfg, "MyPass!", email="user@example.com") instance.login() # JSON (default path: sessions.json) json_saver = JSONSaver("my_sessions.json") instance.save(json_saver) restored = Login.from_saver(json_saver, cfg, identifier="user@example.com") # SQLite sqlite_saver = SqliteSaver("sessions.db") instance.save(sqlite_saver) # MongoDB mongo_saver = MongoSaver( host="mongodb://localhost:27017/", database_name="spotify", collection="sessions", ) instance.save(mongo_saver) restored_mongo = Login.from_saver(mongo_saver, cfg, identifier="user@example.com") # Redis redis_saver = RedisSaver(host="localhost", port=6379, db=0) instance.save(redis_saver) ``` -------------------------------- ### Song Initialization Source: https://github.com/aran404/spotapi/blob/main/docs/song.md Initializes the Song class with optional playlist and client configurations, and supports language selection. ```APIDOC ## Song Class Initialization ### Description Initializes the `Song` class with an optional `PrivatePlaylist` instance and a `TLSClient` instance. Supports language customization for API responses. ### Parameters - **playlist**: `PrivatePlaylist | None` - An optional instance of `PrivatePlaylist`. If not provided, the client is used directly. - **client**: `TLSClient` - The client used for making HTTP requests. Defaults to a new `TLSClient` instance. - **language**: `str`, optional - The language for API responses using ISO 639-1 language codes (e.g., 'ko', 'ja', 'zh', 'en'). Default is 'en'. ### Raises: - `ValueError` if no playlist is provided and no client is set. ``` -------------------------------- ### Fetch Playlist Information Source: https://github.com/aran404/spotapi/blob/main/docs/public.md Get public information for a specific playlist using its Spotify ID. This method returns a generator that yields playlist details. ```python for playlist in Public.playlist_info("37i9dQZF1DXcBWIGoYBM5M"): print(playlist) ``` -------------------------------- ### Login Class Initialization Source: https://github.com/aran404/spotapi/blob/main/docs/login.md Initializes the Login class with configuration and user credentials. Either an email or username must be provided. ```APIDOC ## Login Class ### `__init__(self, cfg: Config, password: str, *, email: str | None = None, username: str | None = None) -> None` Initializes the `Login` class with configuration, password, and either email or username. #### Parameters - **cfg** (`Config`) - Configuration object. - **password** (`str`) - User's password. - **email** (`Optional[str]`) - User's email. Defaults to `None`. - **username** (`Optional[str]`) - User's username. Defaults to `None`. Either an email or username must be provided. ``` -------------------------------- ### WebsocketStreamer Initialization Source: https://github.com/aran404/spotapi/blob/main/docs/websocket.md Initializes the WebsocketStreamer with a Login instance. This sets up the websocket connection and requires the user to be logged in. ```APIDOC ## `__init__(self, login: Login) -> None` ### Description Initializes the `WebsocketStreamer` with a `Login` instance and sets up the websocket connection. ### Parameters - **login** (`Login`) - The `Login` instance for the user. The user must be logged in for this class to function. ### Raises - `ValueError` if the user is not logged in. ``` -------------------------------- ### Creator Class Initialization Source: https://github.com/aran404/spotapi/blob/main/docs/creator.md Initializes the Creator class with configuration and optional account details. ```APIDOC ## Creator Class The `Creator` class is responsible for creating new Spotify accounts. ### Parameters - **cfg**: `Config` The configuration object. - **email**: `str`, optional The email address to use for the account. Defaults to a randomly generated email. - **display_name**: `str`, optional The display name to use for the account. Defaults to a randomly generated string. - **password**: `str`, optional The password to use for the account. Defaults to a randomly generated string. ### Method `__init__(self, cfg: Config, email: str = random_email(), display_name: str = random_string(10), password: str = random_string(10, True)) -> None` Initializes the `Creator` class with the given configuration and optional parameters for email, display name, and password. ``` -------------------------------- ### Run Generic Player Command Source: https://github.com/aran404/spotapi/blob/main/docs/player.md Sends a generic command to the player, specifying the source and destination devices. ```python player.run_command("device_1", "device_2", "pause") ``` -------------------------------- ### Register a New Spotify Account with Creator Source: https://context7.com/aran404/spotapi/llms.txt Automate the Spotify signup process using Creator, which handles CAPTCHA and challenge resolution. New accounts can be registered with custom or random credentials and their details saved. ```python from spotapi import Creator, Config, NoopLogger, JSONSaver from spotapi.solvers import Capsolver cfg = Config(solver=Capsolver("CAP_API_KEY"), logger=NoopLogger()) # Custom credentials creator = Creator( cfg, email="newuser@example.com", display_name="CoolUser42", password="Str0ng!Pass", ) creator.register() # Random credentials (defaults) creator_random = Creator(cfg) creator_random.register() # Save the new account saver = JSONSaver("accounts.json") saver.save([{"identifier": creator.email, "password": creator.password, "cookies": {}}]) ``` -------------------------------- ### AccountChallenge Class Initialization Source: https://github.com/aran404/spotapi/blob/main/docs/creator.md Initializes the AccountChallenge class with the client, raw response, and configuration. ```APIDOC # AccountChallenge Class The `AccountChallenge` class handles challenges encountered during account creation. ## Parameters - **client**: `TLSClient` The client used for making requests to the API. - **raw_response**: `str` The raw response containing challenge details. - **cfg**: `Config` The configuration object. ## Methods ### `__init__(self, client: TLSClient, raw_response: str, cfg: Config) -> None` Initializes the `AccountChallenge` class with the client, raw response, and configuration. ``` -------------------------------- ### Perform Multi-Language Searches with SpotAPI Source: https://github.com/aran404/spotapi/blob/main/docs/language.md Execute searches for songs in different languages by initializing separate Song objects with distinct language codes. This demonstrates how to retrieve localized search results. ```python from spotapi import Song # Search in Korean song_ko = Song(language="ko") korean_results = song_ko.query_songs("BTS") # Search in Japanese song_ja = Song(language="ja") japanese_results = song_ja.query_songs("BTS") # Search in English song_en = Song(language="en") english_results = song_en.query_songs("BTS") ``` -------------------------------- ### run_command Source: https://github.com/aran404/spotapi/blob/main/docs/player.md Sends a generic command to the player. ```APIDOC ## run_command(self, from_device_id: str, to_device_id: str, command: str) -> None ### Description Sends a generic command to the player. ### Parameters - **`from_device_id (str)`**: The device ID to send the command from. - **`to_device_id (str)`**: The device ID to send the command to. - **`command (str)`**: The command to send. ### Example ```python player.run_command("device_1", "device_2", "pause") ``` ``` -------------------------------- ### Artist Class Initialization Source: https://github.com/aran404/spotapi/blob/main/docs/artist.md Initializes the Artist class. It can accept optional Login, TLSClient, and language parameters. If a Login object is provided, it checks for user login status. ```APIDOC ## Artist Class Initialization ### Description Initializes the `Artist` class. If a `Login` object is provided, it checks if the user is logged in. If not, a `ValueError` is raised. ### Parameters - **login**: `Optional[Login]`, optional - A logged-in `Login` object. Required for certain methods. If not provided, some methods will raise a `ValueError`. - **client**: `TLSClient`, optional - A `TLSClient` used for making requests to the API. If not provided, a default one will be used. - **language**: `str`, optional - The language for API responses using ISO 639-1 language codes (e.g., 'ko', 'ja', 'zh', 'en'). Default is 'en'. ``` -------------------------------- ### PlayerStatus Class Initialization Source: https://github.com/aran404/spotapi/blob/main/docs/status.md Initializes the PlayerStatus class with a login instance and an optional device ID. This class is used to fetch and manage Spotify player states. ```APIDOC ## PlayerStatus Class ### Description Provides information about the current state of the Spotify player, including methods for accessing player state, device IDs, and queue information. ### Parameters - **login**: `Login` - The login instance used for authentication. - **s_device_id**: `Optional[str]` - The device ID to use for the player. If `None`, a new device ID will be generated. ### Method `__init__(self, login: Login, s_device_id: str | None = None) -> None` ### Args: - `login`: `Login` - The login instance for authentication. - `s_device_id`: `Optional[str]` - The device ID for the player (optional). ``` -------------------------------- ### LoginChallenge Class Initialization Source: https://github.com/aran404/spotapi/blob/main/docs/login.md Initializes the LoginChallenge class with a Login instance and challenge data. ```APIDOC # LoginChallenge Class ## Parameters - **login**: `Login` The `Login` instance. - **dump**: `Mapping[str, Any]` The challenge data. ### `__init__(self, login: Login, dump: Mapping[str, Any]) -> None` Initializes the `LoginChallenge` class with the `Login` instance and challenge data. ``` -------------------------------- ### resume Source: https://github.com/aran404/spotapi/blob/main/docs/player.md Resumes the player. ```APIDOC ## resume(self) -> None ### Description Resumes the player. ### Example ```python player.resume() ``` ``` -------------------------------- ### create_playlist Source: https://github.com/aran404/spotapi/blob/main/docs/playlist.md Creates a new playlist with the specified name. ```APIDOC ## create_playlist(name: str) -> str ### Description Creates a new playlist. ### Method ```python create_playlist ``` ### Parameters #### Arguments - **name** (str) - Required - The name of the new playlist. ### Returns - **str** - The URI of the newly created playlist. ### Raises - **PlaylistError** - If there is an issue creating the playlist. ``` -------------------------------- ### User Class Initialization Source: https://github.com/aran404/spotapi/blob/main/docs/user.md Initializes the User class with a Login instance. Requires the user to be logged in. ```APIDOC ## __init__(self, login: Login) -> None ### Description Initializes the `User` class with a `Login` instance. ### Parameters #### Path Parameters - **login** (Login) - Required - The `Login` instance for the user. The user must be logged in for this class to function. ### Raises - `ValueError` if the user is not logged in. ``` -------------------------------- ### Creator Source: https://context7.com/aran404/spotapi/llms.txt Automate the full Spotify signup flow, including embedded CAPTCHA and challenge resolution. Supports custom or random credentials. ```APIDOC ## Creator — register a new Spotify account `Creator` automates the full Spotify signup flow, including embedded CAPTCHA and challenge resolution. ```python from spotapi import Creator, Config, NoopLogger, JSONSaver from spotapi.solvers import Capsolver cfg = Config(solver=Capsolver("CAP_API_KEY"), logger=NoopLogger()) # Custom credentials creator = Creator( cfg, email="newuser@example.com", display_name="CoolUser42", password="Str0ng!Pass", ) creator.register() # Random credentials (defaults) creator_random = Creator(cfg) creator_random.register() # Save the new account saver = JSONSaver("accounts.json") saver.save([{"identifier": creator.email, "password": creator.password, "cookies": {}}]) ``` ``` -------------------------------- ### Creator Register Method Source: https://github.com/aran404/spotapi/blob/main/docs/creator.md Registers a new Spotify account by solving a CAPTCHA and processing the registration. ```APIDOC ### `register(self) -> None` Registers a new Spotify account by solving a CAPTCHA and processing the registration. - **Raises:** `GeneratorError` if no CAPTCHA solver is set. ``` -------------------------------- ### Password Class Initialization Source: https://github.com/aran404/spotapi/blob/main/docs/password.md Initializes the Password class with configuration settings and recovery credentials. Either email or username must be provided. ```APIDOC ## Password Class ### Description Handles password recovery for Spotify accounts, allowing users to initiate the reset process by providing either an email or username and handling captcha solving. ### Parameters - **cfg** (`Config`) - Required - A configuration object containing the solver, client, and logger instances. - **email** (`Optional[str]`) - Optional - The email address to use for recovery. - **username** (`Optional[str]`) - Optional - The username to use for recovery. **Note:** Either `email` or `username` must be provided. ### Methods #### `__init__` Initializes the `Password` class. - **Args:** - `cfg`: `Config` - Configuration object containing the `solver`, `client`, and `logger`. - `email`: `Optional[str]` - The email address to use for recovery (optional). - `username`: `Optional[str]` - The username to use for recovery (optional). - **Raises:** `ValueError` if neither `email` nor `username` is provided. ``` -------------------------------- ### Create and Manage Private Playlists Source: https://context7.com/aran404/spotapi/llms.txt Manages user-specific playlists, including creation, adding/removing songs, and retrieving library contents. Requires an authenticated `Login` object. ```python from spotapi import Login, PrivatePlaylist login_instance = Login(...) # already logged in pl = PrivatePlaylist(login_instance) # Create a new playlist — returns spotify:playlist: new_id = pl.create_playlist("My SpotAPI Playlist") print(new_id) # Work with an existing playlist pl.set_playlist(new_id) pl.add_to_library() # Get recommended songs for the playlist recs = pl.recommended_songs(num_songs=10) for track in recs["tracks"]: print(track["name"]) # Retrieve your full library (playlists) library = pl.get_library(limit=50) for item in library["data"]["me"]["libraryV3"]["items"]: print(item["item"]["data"]["name"]) # Saved tracks for chunk in pl.paginate_saved_tracks(): for item in chunk["items"]: print(item["itemV2"]["data"]["name"]) # Remove / delete pl.remove_from_library() pl.delete_playlist() ``` -------------------------------- ### Login Class Methods Source: https://github.com/aran404/spotapi/blob/main/docs/login.md Provides methods for saving sessions, constructing login instances from cookies or savers, checking login status, and performing the login action. ```APIDOC ## Login Class Methods ### `save(self, saver: SaverProtocol) -> None` Saves the session with the provided `Saver`. #### Args: - **saver** (`SaverProtocol`) - The saver to save the session to. #### Raises: - `ValueError` if the session is not logged in. ### `from_cookies(cls, dump: Mapping[str, Any], cfg: Config) -> Login` Constructs a `Login` instance using cookie data and configuration. #### Args: - **dump** (`Mapping[str, Any]`) - The session dump. - **cfg** (`Config`) - The configuration object. #### Returns: - `Login` instance. #### Raises: - `ValueError` if the dump format is invalid. ### `from_saver(cls, saver: SaverProtocol, cfg: Config, identifier: str, **kwargs) -> Login` Loads a session from a `Saver` class. #### Args: - **saver** (`SaverProtocol`) - The saver to load the session from. - **cfg** (`Config`) - The configuration object. - **identifier** (`str`) - The identifier of the session. #### Returns: - `Login` instance. ### `logged_in(self) -> bool` Property indicating whether the user is logged in. ### `__str__(self) -> str` Returns a string representation of the `Login` instance. ### `login(self) -> None` Logs the user in, handling captcha if necessary. #### Raises: - `LoginError` if login fails or captcha cannot be solved. ``` -------------------------------- ### PrivatePlaylist - Create playlist Source: https://context7.com/aran404/spotapi/llms.txt Creates a new, empty private playlist for the authenticated user. ```APIDOC ## PrivatePlaylist - Create playlist ### Description Creates a new private playlist for the authenticated user. ### Method `PrivatePlaylist.create_playlist(name: str)` ### Parameters #### Path Parameters - **name** (str) - Required - The name for the new playlist. ### Response Example ``` spotify:playlist: ``` ``` -------------------------------- ### JoinFamily Class Source: https://github.com/aran404/spotapi/blob/main/docs/family.md Provides functionality for a user to join a Spotify family plan hosted by another user. ```APIDOC ## JoinFamily Class ### Description The `JoinFamily` class provides functionality for a user to join a Spotify family plan hosted by another user. ### Parameters - **user_login**: `Login` - The user's login object. - **host**: `Family` - The host user's family object. - **country**: `str` - The country to restrict the autocomplete to. ### Methods #### `__init__(self, user_login: Login, host: "Family", country: str) -> None` Initializes the `JoinFamily` class with the user's login, host family object, and country. #### `add_to_family(self) -> None` Adds the user to the host's family plan by retrieving the address and making the necessary API calls. - **Raises:** `FamilyError` if unable to add the user to the family. ``` -------------------------------- ### Subscribe to Playback Events with EventManager Source: https://context7.com/aran404/spotapi/llms.txt Extend PlayerStatus with EventManager to subscribe to real-time playback events like track changes and play/pause actions using WebSocket. Requires an active login instance and keeps the main thread alive to receive events. ```python from spotapi import Login from spotapi.status import EventManager login_instance = Login(...) # already logged in em = EventManager(login_instance) @em.subscribe("TRACK_CHANGED") def on_track_change(payload): print("Track changed:", payload) @em.subscribe("PLAY_PAUSE") def on_play_pause(payload): print("Play/Pause event:", payload) # Keep main thread alive to receive events import time while True: time.sleep(1) # Unsubscribe when done em.unsubscribe("TRACK_CHANGED", on_track_change) ``` -------------------------------- ### Connect Device Source: https://github.com/aran404/spotapi/blob/main/docs/websocket.md Connects the device to Spotify and returns the response from the connection. ```APIDOC ## `connect_device(self) -> dict[str, Any]` ### Description Connects the device to Spotify and returns the response. ### Method `connect_device` ### Returns - `dict[str, Any]` - A dictionary containing the response from Spotify. ### Raises - `WebSocketError` if there is an issue connecting the device. ``` -------------------------------- ### LoginChallenge Class Methods Source: https://github.com/aran404/spotapi/blob/main/docs/login.md Provides methods for defeating login challenges. ```APIDOC ### `defeat(self) -> None` Defeats the login challenge by performing the necessary steps. #### Raises: - `LoginError` if unable to get challenge, submit challenge, or complete challenge. ``` -------------------------------- ### Fetch Podcast and Episode Data Source: https://context7.com/aran404/spotapi/llms.txt Retrieves data for specific podcast episodes or all episodes from a show. Supports pagination for shows. ```python from spotapi import Podcast # Fetch a specific episode pod = Podcast() ep = pod.get_episode("6D15TgOtW3rqX8jCrKQqFN") print(ep["data"]["episodeUnionV2"]["name"]) # Fetch all episodes from a show (paginated) show = Podcast("5CnDmMUG0S5bSSw612fs8C") # accepts show ID or URL for chunk in show.paginate_podcast(): for episode in chunk: print(episode["entity"]["data"]["name"]) ``` -------------------------------- ### Player - Skip to next song Source: https://context7.com/aran404/spotapi/llms.txt Skips the current track and plays the next one in the queue. ```APIDOC ## Player - Skip to next song ### Description Advances playback to the next track in the queue. ### Method `Player.skip_next()` ### Parameters None ``` -------------------------------- ### recommended_songs Source: https://github.com/aran404/spotapi/blob/main/docs/playlist.md Fetches a specified number of recommended songs for the playlist. ```APIDOC ## recommended_songs(num_songs: int = 20) -> Mapping[str, Any] ### Description Fetches recommended songs for the playlist. ### Method ```python recommended_songs ``` ### Parameters #### Arguments - **num_songs** (int) - Optional - The number of recommended songs to fetch. Default is 20. ### Returns - **Mapping[str, Any]** - The recommended songs. ### Raises - **PlaylistError** - If there is an issue retrieving recommended songs. ``` -------------------------------- ### skip_prev Source: https://github.com/aran404/spotapi/blob/main/docs/player.md Skips to the previous track. ```APIDOC ## skip_prev(self) -> None ### Description Skips to the previous track. ### Example ```python player.skip_prev() ``` ``` -------------------------------- ### Public.podcast_episode_info Source: https://github.com/aran404/spotapi/blob/main/docs/public.md Fetches detailed information about a specific podcast episode using its Spotify ID. Returns a dictionary containing detailed episode information. ```APIDOC ## Public.podcast_episode_info(episode_id: str, /) ### Description Fetches detailed information about a specific podcast episode using its Spotify ID. ### Parameters #### Path Parameters - **episode_id** (str) - Required - The Spotify ID of the episode. ### Returns `Mapping[str, Any]` - A dictionary containing detailed episode information. ### Usage Example ```python episode = Public.podcast_episode_info("1HpkG1StJQsNN09awYFTB3") print(episode) ``` ``` -------------------------------- ### Player - Restart song Source: https://context7.com/aran404/spotapi/llms.txt Restarts the current track from the beginning. ```APIDOC ## Player - Restart song ### Description Restarts the current track from the beginning. ### Method `Player.restart_song()` ### Parameters None ```