### Create Virtual Environment and Install Dependencies Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Guides users through creating a Python virtual environment, installing project dependencies, and running tests. This ensures a clean and isolated development setup. ```bash $ virtualenv --python=python3.12 env (env) $ pip install --user -e . (env) $ python -m unittest discover -v tests ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://spotipy.readthedocs.io/en/2.25.1/index Provides commands for setting up a virtual environment, installing Spotipy and its dependencies, and running the test suite. This ensures the library is correctly installed and functioning. ```Bash $ virtualenv –python=python3.12 env (env) $ pip install –user -e . (env) $ python -m unittest discover -v tests ``` -------------------------------- ### Install Spotipy Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Installs or upgrades the Spotipy library using pip. This is the standard method for adding the library to your Python environment. ```bash pip install spotipy --upgrade ``` -------------------------------- ### Install Spotipy Source: https://spotipy.readthedocs.io/en/2.25.1/index Installs or upgrades the Spotipy library using pip. This is the primary method for obtaining the library. ```Shell pip install spotipy --upgrade ``` -------------------------------- ### Get Artist Top Tracks with Samples and Cover Art using Spotipy Source: https://spotipy.readthedocs.io/en/2.25.1/index This example shows how to retrieve the top 10 tracks for a given artist using Spotipy. It also extracts the preview audio URL and the cover art URL for each track. `SpotifyClientCredentials` is used for authentication. ```Python import spotipy from spotipy.oauth2 import SpotifyClientCredentials lz_uri = 'spotify:artist:36QJpDe2go2KgaRleHCDTp' spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) results = spotify.artist_top_tracks(lz_uri) for track in results['tracks'][:10]: print('track : ' + track['name']) print('audio : ' + track['preview_url']) print('cover art: ' + track['album']['images'][0]['url']) print() ``` -------------------------------- ### Start or Resume Spotify Playback Source: https://spotipy.readthedocs.io/en/2.25.1/index Initiates or resumes playback on Spotify. Can start playback from a context (album, artist, playlist), a list of tracks, or a specific offset within a track. Requires device ID and optionally context URI, track URIs, offset, or position in milliseconds. ```python start_playback(_device_id =None_, _context_uri =None_, _uris =None_, _offset =None_, _position_ms =None_) ``` -------------------------------- ### Get User Devices Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of the user's available devices. ```Python devices() ``` -------------------------------- ### Get Artist Image URL by Name using Spotipy Source: https://spotipy.readthedocs.io/en/2.25.1/index This example demonstrates how to find an artist by name using Spotipy's search functionality and retrieve the URL for their primary image. It handles command-line arguments for the artist name, defaulting to 'Radiohead' if none is provided. `SpotifyClientCredentials` is used for authentication. ```Python import spotipy import sys from spotipy.oauth2 import SpotifyClientCredentials spotify = spotipy.Spotify(auth_manager=SpotifyClientCredentials()) if len(sys.argv) > 1: name = ' '.join(sys.argv[1:]) else: name = 'Radiohead' results = spotify.search(q='artist:' + name, type='artist') items = results['artists']['items'] if len(items) > 0: artist = items[0] print(artist['name'], artist['images'][0]['url']) ``` -------------------------------- ### Get Multiple Episodes Source: https://spotipy.readthedocs.io/en/2.25.1/index Returns a list of episodes given their IDs, URIs, or URLs. Optionally filters by market. ```Python episodes(_episodes_ , _market =None_) # Parameters: # episodes - a list of episode IDs, URIs, or URLs # market - an ISO 3166-1 alpha-2 country code. ``` -------------------------------- ### Initialize Spotipy Client and Fetch Data Source: https://spotipy.readthedocs.io/en/2.25.1/index Demonstrates how to initialize the Spotipy client and perform basic API calls to retrieve artist and user information. This example showcases fetching an artist's details using their URI and retrieving user information by username. ```Python import spotipy urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu' sp = spotipy.Spotify() artist = sp.artist(urn) print(artist) user = sp.user('plamere') print(user) ``` -------------------------------- ### Get Recommendation Genre Seeds Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of available genre seeds that can be used for music recommendations. ```python recommendation_genre_seeds() ``` -------------------------------- ### Spotipy Client Credentials Flow Example Source: https://spotipy.readthedocs.io/en/2.25.1/index Demonstrates using Spotipy's SpotifyClientCredentials for server-to-server authentication. It allows access to endpoints not requiring user information and provides a higher rate limit. ```Python import spotipy from spotipy.oauth2 import SpotifyClientCredentials auth_manager = SpotifyClientCredentials() sp = spotipy.Spotify(auth_manager=auth_manager) playlists = sp.user_playlists('spotify') while playlists: for i, playlist in enumerate(playlists['items']): print(f"{i + 1 + playlists['offset']:4d} {playlist['uri']} {playlist['name']}") if playlists['next']: playlists = sp.next(playlists) else: playlists = None ``` -------------------------------- ### Get User Playlists Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of playlists created by the current user. Supports pagination with limit and offset parameters. ```python current_user_playlists(_limit =50_, _offset =0_) ``` -------------------------------- ### Spotipy Authorization Code Flow Example Source: https://spotipy.readthedocs.io/en/2.25.1/index Demonstrates how to use Spotipy's SpotifyOAuth class for the Authorization Code flow. It requires setting a scope and authenticates requests to fetch user-saved tracks. ```Python import spotipy from spotipy.oauth2 import SpotifyOAuth scope = "user-library-read" sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) results = sp.current_user_saved_tracks() for idx, item in enumerate(results['items']): track = item['track'] print(idx, track['artists'][0]['name'], " – ", track['name']) ``` -------------------------------- ### Get Current Playback Queue Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves the user's current playback queue. ```python queue() ``` -------------------------------- ### Spotipy Authorization Code Flow Example Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Demonstrates how to authenticate using the Authorization Code Flow with Spotipy. It initializes the Spotify client with a specified scope and retrieves the current user's saved tracks, printing the artist and track name. ```Python import spotipy from spotipy.oauth2 import SpotifyOAuth scope = "user-library-read" sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) results = sp.current_user_saved_tracks() for idx, item in enumerate(results['items']): track = item['track'] print(idx, track['artists'][0]['name'], " – ", track['name']) ``` -------------------------------- ### Get Spotify Show Episodes Source: https://spotipy.readthedocs.io/en/2.25.1/index Fetches a list of episodes for a given Spotify show. Supports pagination with limit and offset, and filtering by market availability. ```python show_episodes(_show_id_ , _limit =50_, _offset =0_, _market =None_) ``` -------------------------------- ### List Artist Albums using Spotipy Source: https://spotipy.readthedocs.io/en/2.25.1/index This example demonstrates how to use Spotipy to fetch and print the names of all albums released by a specific artist. It utilizes `SpotifyClientCredentials` for authentication and iterates through paginated results to gather all albums. ```Python import spotipy from spotipy.oauth2 import SpotifyClientCredentials birdy_uri = 'spotify:artist:2WX2uTcsvV5OnS0inACecP' spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) results = spotify.artist_albums(birdy_uri, album_type='album') albums = results['items'] while results['next']: results = spotify.next(results) albums.extend(results['items']) for album in albums: print(album['name']) ``` -------------------------------- ### Get Currently Playing Track Source: https://spotipy.readthedocs.io/en/2.25.1/index Fetches information about the track the current user is currently playing. ```python current_user_playing_track() ``` -------------------------------- ### Get Artist Top Tracks with Preview and Cover Art Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Retrieves the top 10 tracks for a given artist, displaying the track name, a 30-second preview URL, and the album's cover art URL. ```Python import spotipy from spotipy.oauth2 import SpotifyClientCredentials lz_uri = 'spotify:artist:36QJpDe2go2KgaRleHCDTp' spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) results = spotify.artist_top_tracks(lz_uri) for track in results['tracks'][:10]: print('track : ' + track['name']) print('audio : ' + track['preview_url']) print('cover art: ' + track['album']['images'][0]['url']) print() ``` -------------------------------- ### Get Multiple Audiobooks by IDs Source: https://spotipy.readthedocs.io/en/2.25.1/index Fetches Spotify catalog information for multiple audiobooks based on their Spotify IDs. Requires a list of audiobook IDs and optionally accepts a market code. ```python sp.get_audiobooks(_ids_ , _market =None_) ``` -------------------------------- ### Get Audiobook Chapters Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves catalog information for an audiobook's chapters. Requires the audiobook ID and allows filtering by market, limit, and offset. ```python sp.get_audiobook_chapters(_id_ , _market =None_, _limit =20_, _offset =0_) ``` -------------------------------- ### Get Multiple Spotify Shows Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of Spotify shows based on their IDs, URIs, or URLs. Allows filtering by market availability. ```python shows(_shows_ , _market =None_) ``` -------------------------------- ### Get Categories Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of music categories. Allows filtering by country and locale, with options to limit and offset results. ```python categories(_country =None_, _locale =None_, _limit =20_, _offset =0_) ``` -------------------------------- ### Get Tracks from Spotify Playlist Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves tracks from a specified playlist. Optional parameters include fields to return, limit, offset, and market. ```python user_playlist_tracks(_user =None_, _playlist_id =None_, _fields =None_, _limit =100_, _offset =0_, _market =None_) ``` -------------------------------- ### Get Spotify User Profile Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves basic profile information for a Spotify user, identified by their user ID. ```python user(_user_) ``` -------------------------------- ### Get Previous Paged Result Source: https://spotipy.readthedocs.io/en/2.25.1/index Returns the previous result set from a paginated API response. ```python previous(_result_) ``` -------------------------------- ### Get Current Playback Information Source: https://spotipy.readthedocs.io/en/2.25.1/index Fetches information about the user's current playback activity. Allows specifying the market and additional types for podcast track information. ```python current_playback(_market =None_, _additional_types =None_) ``` -------------------------------- ### Get Playlist Cover Image Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves the cover image for a given playlist. Requires the playlist ID, URI, or URL. ```python sp.playlist_cover_image(_playlist_id_) ``` -------------------------------- ### Get User's Spotify Playlists Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of playlists owned by a specified user. Parameters include limit and offset for pagination. ```python user_playlists(_user_ , _limit =50_, _offset =0_) Gets playlists of a user Parameters: * user - the id of the usr * limit - the number of items to return * offset - the index of the first item to return ``` -------------------------------- ### Get New Album Releases Source: https://spotipy.readthedocs.io/en/2.25.1/index Fetches a list of new album releases featured on Spotify. Supports filtering by country and pagination using limit and offset. ```python sp.new_releases(_country =None_, _limit =20_, _offset =0_) ``` -------------------------------- ### Get Current User Profile Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves detailed profile information for the currently authenticated user. This is an alias for the 'me' method. ```python current_user() ``` -------------------------------- ### Get User Top Artists Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves the current user's top artists based on a specified time range. Supports pagination. ```Python current_user_top_artists(_limit =20_, _offset =0_, _time_range ='medium_term'_) # Parameters: # limit - the number of entities to return (max 50) # offset - the index of the first entity to return # time_range - Over what time frame are the affinities computed Valid-values: short_term, medium_term, long_term ``` -------------------------------- ### Get Audiobook by ID Source: https://spotipy.readthedocs.io/en/2.25.1/index Fetches Spotify catalog information for a single audiobook using its unique Spotify ID. Requires the audiobook ID and optionally accepts a market code for availability. ```python sp.get_audiobook(_id_ , _market =None_) ``` -------------------------------- ### Get Authorization URL Source: https://spotipy.readthedocs.io/en/2.25.1/index Generates the URL required to authorize the application. This URL is used to redirect the user to Spotify's authorization page, where they can grant permissions to the application. ```Python get_authorize_url(_state =None_) ``` -------------------------------- ### Get User Top Tracks Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves the current user's top tracks based on a specified time range. Supports pagination. ```Python current_user_top_tracks(_limit =20_, _offset =0_, _time_range ='medium_term'_) # Parameters: # limit - the number of entities to return # offset - the index of the first entity to return # time_range - Over what time frame are the affinities computed Valid-values: short_term, medium_term, long_term ``` -------------------------------- ### Get Followed Artists Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of artists that the current authorized user follows. Supports limiting the number of results and fetching based on a cursor. ```python current_user_followed_artists(_limit =20_, _after =None_) ``` -------------------------------- ### Get Available Markets Source: https://spotipy.readthedocs.io/en/2.25.1/index Fetches a list of countries where Spotify is available. Returns country codes based on ISO 3166-1 alpha-2 standard, including special territories. ```python available_markets() ``` -------------------------------- ### Get Currently Playing Track Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves the user's currently playing track. Supports country and additional types for podcast information. ```Python currently_playing(_market =None_, _additional_types =None_) # Parameters: # market - an ISO 3166-1 alpha-2 country code. # additional_types - episode to get podcast track information ``` -------------------------------- ### Get Playlist by ID Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a playlist by its ID. Allows specifying which fields to return, the market for availability, and additional item types (track or episode). ```python sp.playlist(_playlist_id_ , _fields =None_, _market =None_, _additional_types =('track',)_) ``` -------------------------------- ### Get Playlists for a Category Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of playlists associated with a specific Spotify category. Supports filtering by country and pagination with limit and offset. ```python category_playlists(_category_id =None_, _country =None_, _limit =20_, _offset =0_) ``` -------------------------------- ### Get Current User Profile Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves detailed profile information for the currently authenticated user. This method serves as an alias for the 'current_user' method. ```python sp.me() ``` -------------------------------- ### Get Category Information Source: https://spotipy.readthedocs.io/en/2.25.1/index Fetches detailed information about a specific music category using its Spotify ID. Supports filtering by country and locale. ```python category(_category_id_ , _country =None_, _locale =None_) ``` -------------------------------- ### Get Track Recommendations Source: https://spotipy.readthedocs.io/en/2.25.1/index Generates a list of recommended tracks based on artist, genre, or track seeds. Requires at least one seed type. Optional parameters include country, limit, and tuneable track attributes for filtering. ```python recommendations(_seed_artists =None_, _seed_genres =None_, _seed_tracks =None_, _limit =20_, _country =None_, _** kwargs_) ``` -------------------------------- ### Get Single Spotify Track Source: https://spotipy.readthedocs.io/en/2.25.1/index Fetches details for a single Spotify track using its ID, URI, or URL. Allows filtering by market availability. ```python track(_track_id_ , _market =None_) ``` -------------------------------- ### Retrieve Artist Albums Source: https://spotipy.readthedocs.io/en/2.25.1/index Explains how to get catalog information about an artist's albums. The `artist_albums` method takes the artist's ID, URI, or URL, and allows filtering by `album_type`, `include_groups`, `country`, `limit`, and `offset`. ```Python sp.artist_albums(_artist_id_, _album_type=None_, _include_groups=None_, _country=None_, _limit=20_, _offset=0_) ``` -------------------------------- ### SpotifyOAuth Get Authorization URL Source: https://spotipy.readthedocs.io/en/2.25.1/index Generates the URL required to initiate the authorization process with Spotify. This URL is used to redirect the user to Spotify's authorization page to grant permissions to the application. An optional state parameter can be provided for security. ```Python get_authorize_url(_state =None_) ``` -------------------------------- ### Get Multiple Spotify Tracks Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves details for a list of Spotify tracks using their IDs, URIs, or URLs. Supports up to 50 tracks and allows filtering by market availability. ```python tracks(_tracks_ , _market =None_) ``` -------------------------------- ### Get Playlist Items Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves detailed information about tracks and episodes within a playlist. Supports filtering by fields, pagination (limit, offset), market, and additional item types. ```python sp.playlist_items(_playlist_id_ , _fields =None_, _limit =100_, _offset =0_, _market =None_, _additional_types =('track', 'episode')_) ``` -------------------------------- ### Get Single Episode Source: https://spotipy.readthedocs.io/en/2.25.1/index Returns a single episode given its ID, URI, or URL. Requires the episode ID and optionally a market code. The episode must be available in the specified market. ```Python episode(_episode_id_ , _market =None_) # Parameters: # episode_id - the episode ID, URI or URL # market - an ISO 3166-1 alpha-2 country code. # The episode must be available in the given market. If user-based authorization is in use, the user’s country takes precedence. If neither market nor user country are provided, the content is considered unavailable for the client. ``` -------------------------------- ### Package Spotipy for PyPI Distribution Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Provides commands for packaging the Spotipy library into source and wheel distributions using setuptools and uploading them to PyPI using twine. This is for maintainers to publish new versions. ```bash python setup.py sdist bdist_wheel python3 setup.py sdist bdist_wheel twine check dist/* twine upload --repository-url https://upload.pypi.org/legacy/ --skip-existing dist/*.(whl|gz|zip)~dist/*linux*.whl ``` -------------------------------- ### Get Saved Albums Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of albums saved in the current authorized user's music library. Supports limiting results, pagination, and market filtering. ```python current_user_saved_albums(_limit =20_, _offset =0_, _market =None_) ``` -------------------------------- ### Get Next Paged Result Source: https://spotipy.readthedocs.io/en/2.25.1/index Returns the next set of results from a previously paginated API response. Requires the previous result object as input. ```python sp.next(_result_) ``` -------------------------------- ### Retrieve Album Tracks Source: https://spotipy.readthedocs.io/en/2.25.1/index Shows how to get catalog information about an album's tracks. The `album_tracks` method accepts the album's ID, URI, or URL, along with optional `limit`, `offset`, and `market` parameters for pagination and country-specific results. ```Python sp.album_tracks(_album_id_, _limit=50_, _offset=0_, _market=None_) ``` -------------------------------- ### Get Authorization Code Source: https://spotipy.readthedocs.io/en/2.25.1/index This function is used to obtain the authorization code, which is a crucial step in the OAuth 2.0 flow for authorizing applications to access user data on Spotify. ```Python get_authorization_code(_response =None_) ``` -------------------------------- ### Get Spotify Show Information Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves details for a single Spotify show using its ID, URI, or URL. Requires the show identifier and an optional market (country code) to check availability. ```python show(_show_id_ , _market =None_) ``` -------------------------------- ### Spotipy Get Access Token Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves an authentication token for Spotipy. It prioritizes fetching the token from the cache but can also obtain it through user interaction if necessary. The function accepts optional state and response parameters. ```python get_access_token(_state =None_, _response =None_, _check_cache =True_) ``` -------------------------------- ### Package and Publish to PyPI Source: https://spotipy.readthedocs.io/en/2.25.1/index Details the steps for packaging the Spotipy library into distributable formats (sdist, wheel) and publishing it to the Python Package Index (PyPI) using `twine`. This includes version bumping and changelog updates. ```Bash python setup.py sdist bdist_wheel python3 setup.py sdist bdist_wheel twine check dist/* twine upload –repository-url https://upload.pypi.org/legacy/ –skip-existing dist/* ``` -------------------------------- ### Get User Saved Episodes Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of episodes saved in the current authorized user's "Your Music" library. Supports pagination with limit and offset, and country filtering. ```Python current_user_saved_episodes(_limit =20_, _offset =0_, _market =None_) # Parameters: # limit - the number of episodes to return # offset - the index of the first episode to return # market - an ISO 3166-1 alpha-2 country code ``` -------------------------------- ### Get PKCE Handshake Parameters Source: https://spotipy.readthedocs.io/en/2.25.1/index Obtains the necessary parameters for the Proof Key for Code Exchange (PKCE) handshake. PKCE is an extension to the OAuth 2.0 authorization code flow that adds security by preventing authorization code interception attacks. ```Python get_pkce_handshake_parameters() ``` -------------------------------- ### Get User Saved Shows Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of shows saved in the current authorized user's "Your Music" library. Supports pagination and country filtering. ```Python current_user_saved_shows(_limit =20_, _offset =0_, _market =None_) # Parameters: # limit - the number of shows to return # offset - the index of the first show to return # market - an ISO 3166-1 alpha-2 country code ``` -------------------------------- ### Get Spotify Featured Playlists Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of Spotify's featured playlists. Supports filtering by locale, country, and timestamp, with options for pagination using limit and offset. ```python sp.featured_playlists(_locale =None_, _country =None_, _timestamp =None_, _limit =20_, _offset =0_) ``` -------------------------------- ### Spotipy Client Initialization Parameters Source: https://spotipy.readthedocs.io/en/2.25.1/index Explains the various parameters available when initializing the `spotipy.client.Spotify` class. These parameters control authentication, network requests, session management, and error handling for API interactions. ```Python sp = spotipy.Spotify( auth=None, requests_session=True, client_credentials_manager=None, oauth_manager=None, auth_manager=None, proxies=None, requests_timeout=5, status_forcelist=None, retries=3, status_retries=3, backoff_factor=0.3, language=None ) ``` -------------------------------- ### Get Recently Played Tracks Source: https://spotipy.readthedocs.io/en/2.25.1/index Fetches the current user's recently played tracks. Supports limiting results and fetching tracks before or after a specific timestamp. ```python current_user_recently_played(_limit =50_, _after =None_, _before =None_) ``` -------------------------------- ### SpotifyOAuth Get Access Token Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves an access token for the application using a provided authorization code. The token can be returned as a dictionary or a string. It also includes an option to check the cache for an existing token. ```Python get_access_token(_code =None_, _as_dict =True_, _check_cache =True_) ``` -------------------------------- ### Get User Saved Tracks Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a list of tracks saved in the current authorized user's "Your Music" library. Supports pagination and country filtering. ```Python current_user_saved_tracks(_limit =20_, _offset =0_, _market =None_) # Parameters: # limit - the number of tracks to return # offset - the index of the first track to return # market - an ISO 3166-1 alpha-2 country code ``` -------------------------------- ### SpotifyPKCE Class Initialization Source: https://spotipy.readthedocs.io/en/2.25.1/index Initializes the SpotifyPKCE object for the Proof Key for Code Exchange (PKCE) Authorization Flow. This flow is preferred for mobile and desktop clients as it allows authorization with only a client ID and redirect URI, and provides both access and refresh tokens after initial user authorization. ```Python spotipy.oauth2.SpotifyPKCE(_client_id =None_, _redirect_uri =None_, _state =None_, _scope =None_, _cache_path =None_, _username =None_, _proxies =None_, _requests_timeout =None_, _requests_session =True_, _open_browser =True_, _cache_handler =None_) ``` -------------------------------- ### Spotipy: Navigation and Queue Source: https://spotipy.readthedocs.io/en/2.25.1/genindex Methods for navigating through tracks and managing the playback queue. This includes playing the next or previous track and adding items to the queue. ```Python next() next_track() previous() previous_track() queue() ``` -------------------------------- ### Get Audio Features for Tracks Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves audio features for one or multiple tracks using their Spotify IDs. Supports a maximum of 100 track IDs per request. ```python audio_features(_tracks =[]) ``` -------------------------------- ### Get Playlist Tracks Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves detailed information about the tracks in a playlist. Requires the playlist ID. Optional parameters include fields to return, limit, offset, market, and additional item types (track, episode). ```python playlist_tracks(_playlist_id_ , _fields =None_, _limit =100_, _offset =0_, _market =None_, _additional_types =('track',)_) ``` -------------------------------- ### Export Environment Variables for Spotipy Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Sets up the necessary environment variables for Spotipy, including client ID, client secret, username, and redirect URI. These are essential for authenticating with the Spotify API. ```bash export SPOTIPY_CLIENT_ID=client_id_here export SPOTIPY_CLIENT_SECRET=client_secret_here export SPOTIPY_CLIENT_USERNAME=client_username_here # This is actually an id not spotify display name export SPOTIPY_REDIRECT_URI=http://127.0.0.1:8080 # Make url is set in app you created to get your ID and SECRET ``` -------------------------------- ### Spotipy: Core Classes and Modules Source: https://spotipy.readthedocs.io/en/2.25.1/genindex Core classes and modules within the Spotipy library, including the main Spotify client, authentication classes, and utility modules. ```Python Spotify SpotifyClientCredentials SpotifyImplicitGrant SpotifyOAuth SpotifyPKCE spotipy.client spotipy.oauth2 spotipy.util ``` -------------------------------- ### Authenticate and Fetch User Playlists Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Demonstrates how to authenticate using the Client Credentials Flow with Spotipy and retrieve a user's playlists. It iterates through paginated results to fetch all playlists. ```Python import spotipy from spotipy.oauth2 import SpotifyClientCredentials auth_manager = SpotifyClientCredentials() sp = spotipy.Spotify(auth_manager=auth_manager) playlists = sp.user_playlists('spotify') while playlists: for i, playlist in enumerate(playlists['items']): print(f"{i + 1 + playlists['offset']:4d} {playlist['uri']} {playlist['name']}") if playlists['next']: playlists = sp.next(playlists) else: playlists = None ``` -------------------------------- ### Get Access Token Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves the access token for the application. If no code is provided and no cached token is found, an authentication window will be displayed to the user to obtain a new code. It checks for a locally stored token before requesting a new one. ```Python get_access_token(_code =None_, _check_cache =True_) ``` -------------------------------- ### Reorder Items in a Playlist Source: https://spotipy.readthedocs.io/en/2.25.1/index Reorders tracks within a playlist. Requires the playlist ID, the starting position of the tracks to reorder, and the position where they should be inserted. Optional parameters include the number of tracks to reorder and a snapshot ID. ```python playlist_reorder_items(_playlist_id_ , _range_start_ , _insert_before_ , _range_length =1_, _snapshot_id =None_) ``` -------------------------------- ### Create Spotify Playlist Source: https://spotipy.readthedocs.io/en/2.25.1/index Creates a new playlist for a specified user. Users can define the playlist's name, public/private status, collaborative status, and description. ```python user_playlist_create(_user_ , _name_ , _public =True_, _collaborative =False_, _description =''_) Creates a playlist for a user Parameters: * user - the id of the user * name - the name of the playlist * public - is the created playlist public * collaborative - is the created playlist collaborative * description - the description of the playlist ``` -------------------------------- ### Manage Import Lists Source: https://spotipy.readthedocs.io/en/2.25.1/index Explains how to use `isort` to ensure that import statements are correctly sorted and organized, which helps in maintaining code readability and consistency. ```Bash pip install isort isort . -c -v ``` -------------------------------- ### Lint and Verify Code Style with Autopep8 and Flake8 Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Demonstrates how to use autopep8 to automatically format code and flake8 to verify code style compliance. These tools help maintain consistent code quality. ```bash pip install autopep8 autopep8 --in-place --aggressive --recursive . ``` ```bash pip install flake8 flake8 . ``` -------------------------------- ### Spotipy Client Properties and Attributes Source: https://spotipy.readthedocs.io/en/2.25.1/genindex This section lists properties and attributes of the Spotipy client, providing access to configuration details and constants. ```python auth_manager default_retry_codes country_codes max_retries ``` -------------------------------- ### SpotifyOAuth Class Initialization Source: https://spotipy.readthedocs.io/en/2.25.1/index Initializes the SpotifyOAuth object for the Authorization Code Flow. Requires client ID, client secret, and redirect URI, which can be supplied directly or set as environment variables. Supports various optional parameters for scope, caching, proxies, and browser interaction. ```Python spotipy.oauth2.SpotifyOAuth(_client_id =None_, _client_secret =None_, _redirect_uri =None_, _state =None_, _scope =None_, _cache_path =None_, _username =None_, _proxies =None_, _show_dialog =False_, _requests_session =True_, _requests_timeout =None_, _open_browser =True_, _cache_handler =None_) ``` -------------------------------- ### Set Spotify API Credentials Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Sets the SPOTIPY_CLIENT_ID and SPOTIPY_CLIENT_SECRET environment variables for authentication with the Spotify API. ```Shell export SPOTIPY_CLIENT_ID='your-spotify-client-id' export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret' ``` -------------------------------- ### Export Environment Variables Source: https://spotipy.readthedocs.io/en/2.25.1/index Demonstrates how to export necessary environment variables for Spotipy, including client ID, client secret, username, and redirect URI. These variables are essential for the authentication process. ```Bash export SPOTIPY_CLIENT_ID=client_id_here export SPOTIPY_CLIENT_SECRET=client_secret_here export SPOTIPY_CLIENT_USERNAME=client_username_here export SPOTIPY_REDIRECT_URI=http://127.0.0.1:8080 ``` -------------------------------- ### Get Cached Token Source: https://spotipy.readthedocs.io/en/2.25.1/index Retrieves a previously stored (cached) authorization token. This avoids the need to re-authenticate the user if a valid token is already available. ```Python get_cached_token() ``` -------------------------------- ### Spotipy: Utility Functions Source: https://spotipy.readthedocs.io/en/2.25.1/genindex Utility functions provided by the Spotipy library, such as prompting the user for authentication tokens. ```Python prompt_for_user_token() ``` -------------------------------- ### Spotipy Authentication Parameters Source: https://spotipy.readthedocs.io/en/2.25.1/index Defines the parameters required for authenticating with the Spotipy library. These include client ID, redirect URI, state, scope, and cache handling options. Some parameters can be set via environment variables. ```python client_id: Must be supplied or set as environment variable redirect_uri: Must be supplied or set as environment variable state: May be supplied, no verification is performed scope: Optional, either a list of scopes or comma separated string of scopes. e.g, “playlist-read-private,playlist-read-collaborative” cache_handler: An instance of the CacheHandler class to handle getting and saving cached authorization tokens. May be supplied, will otherwise use CacheFileHandler. (takes precedence over cache_path and username) cache_path: (deprecated) May be supplied, will otherwise be generated (takes precedence over username) username: (deprecated) May be supplied or set as environment variable (will set cache_path to .cache-{username}) show_dialog: Interpreted as boolean ``` -------------------------------- ### Retrieve Multiple Artists Source: https://spotipy.readthedocs.io/en/2.25.1/index Demonstrates the `artists` method for retrieving a list of artists by their IDs, URIs, or URLs. ```Python sp.artists(_artists_) ``` -------------------------------- ### Set Spotipy Environment Variables Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Shows how to set environment variables for Spotify API credentials (Client ID, Client Secret, and Redirect URI). This method avoids hardcoding sensitive information directly in the source code. ```bash export SPOTIPY_CLIENT_ID='your-spotify-client-id' export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret' export SPOTIPY_REDIRECT_URI='your-app-redirect-url' ``` -------------------------------- ### Spotipy: Search and Recommendations Source: https://spotipy.readthedocs.io/en/2.25.1/genindex Functions for searching Spotify's catalog for artists, tracks, albums, and shows, as well as generating recommendations based on various criteria. ```Python search() search_markets() recommendation_genre_seeds() recommendations() ``` -------------------------------- ### Prompt for User Token Source: https://spotipy.readthedocs.io/en/2.25.1/index Prompts the user to authenticate and obtain an authorization token. This utility function handles the entire OAuth flow, including setting environment variables and managing the cache. ```Python spotipy.util.prompt_for_user_token(_username =None_, _scope =None_, _client_id =None_, _client_secret =None_, _redirect_uri =None_, _cache_path =None_, _oauth_manager =None_, _show_dialog =False_) ``` -------------------------------- ### Spotipy OAuth2 Methods Source: https://spotipy.readthedocs.io/en/2.25.1/genindex This section details the methods related to authentication and authorization using Spotipy's OAuth2 utilities. It includes functions for obtaining access tokens, managing authorization flows, and handling PKCE parameters. ```python get_access_token() get_auth_response() get_authorization_code() get_authorize_url() get_cached_token() get_pkce_handshake_parameters() ``` -------------------------------- ### Spotipy Modules Source: https://spotipy.readthedocs.io/en/2.25.1/genindex This section lists the core modules within the Spotipy library, indicating the organization of its functionalities. ```python spotipy.client spotipy.oauth2 spotipy.util ``` -------------------------------- ### Spotipy: New Releases Source: https://spotipy.readthedocs.io/en/2.25.1/genindex Method to retrieve information about new releases on Spotify. ```Python new_releases() ``` -------------------------------- ### Set Spotipy Environment Variables (Authorization Code Flow) Source: https://spotipy.readthedocs.io/en/2.25.1/index Sets environment variables for Spotify API credentials (client ID, client secret, redirect URI) required for the Authorization Code flow. Use `$env:"credentials"` on Windows. ```Shell export SPOTIPY_CLIENT_ID='your-spotify-client-id' export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret' export SPOTIPY_REDIRECT_URI='your-app-redirect-url' ``` -------------------------------- ### Spotipy Client Methods Source: https://spotipy.readthedocs.io/en/2.25.1/genindex This section lists various methods available in the Spotipy client for interacting with the Spotify API. These methods cover functionalities such as managing playlists, retrieving album and artist information, and handling user data. ```python add_to_queue() album() album_tracks() albums() artist() artist_albums() artist_related_artists() artist_top_tracks() artists() audio_analysis() audio_features() available_markets() categories() category() category_playlists() current_playback() current_user() current_user_follow_playlist() current_user_followed_artists() current_user_following_artists() current_user_following_users() current_user_playing_track() current_user_playlists() current_user_recently_played() current_user_saved_albums() current_user_saved_albums_add() current_user_saved_albums_contains() current_user_saved_albums_delete() current_user_saved_episodes() current_user_saved_episodes_add() current_user_saved_episodes_contains() current_user_saved_episodes_delete() current_user_saved_shows() current_user_saved_shows_add() current_user_saved_shows_contains() current_user_saved_shows_delete() current_user_saved_tracks() current_user_saved_tracks_add() current_user_saved_tracks_contains() current_user_saved_tracks_delete() current_user_top_artists() current_user_top_tracks() current_user_unfollow_playlist() currently_playing() devices() episode() episodes() featured_playlists() get_audiobook() get_audiobook_chapters() get_audiobooks() me() ``` -------------------------------- ### Check and Sort Imports with isort Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Explains how to use isort to check and sort import statements in the project. This ensures imports are organized according to defined standards. ```bash pip install isort isort . -c -v ``` -------------------------------- ### Add Song to Playback Queue Source: https://spotipy.readthedocs.io/en/2.25.1/index Provides the method signature for adding a song to a user's playback queue. It highlights the `uri` parameter for the song and the optional `device_id` to specify the playback device, recommending leaving it as `None` to target the active device. ```Python sp.add_to_queue(_uri_, _device_id=None_) ``` -------------------------------- ### Retrieve Multiple Albums Source: https://spotipy.readthedocs.io/en/2.25.1/index Demonstrates the `albums` method for retrieving a list of albums by their IDs, URIs, or URLs. The `market` parameter can be used to specify a country for the results. ```Python sp.albums(_albums_, _market=None_) ``` -------------------------------- ### Add User Saved Shows Source: https://spotipy.readthedocs.io/en/2.25.1/index Adds one or more shows to the current user's "Your Music" library. Requires a list of show URIs, URLs, or IDs. ```Python current_user_saved_shows_add(_shows =[])_ # Parameters: # shows - a list of show URIs, URLs or IDs ``` -------------------------------- ### Lint Code Style Source: https://spotipy.readthedocs.io/en/2.25.1/index Shows how to use `autopep8` to automatically fix code style issues and `flake8` to verify code style compliance, ensuring adherence to PEP 8 guidelines. ```Bash pip install autopep8 autopep8 –in-place –aggressive –recursive . pip install flake8 flake8 . ``` -------------------------------- ### Spotipy: Track and Show Information Source: https://spotipy.readthedocs.io/en/2.25.1/genindex Methods to retrieve detailed information about tracks, albums, and shows available on Spotify. This includes fetching track details, album contents, and show episodes. ```Python track() tracks() show() show_episodes() ``` -------------------------------- ### Spotipy Exception Handling Source: https://spotipy.readthedocs.io/en/2.25.1/genindex This section lists exceptions that can be raised by the Spotipy library, particularly related to client operations and OAuth2 errors. ```python SpotifyClientException SpotifyClientCredentials SpotifyImplicitGrant SpotifyOAuth SpotifyOauthError SpotifyPKCE SpotifyStateError ``` -------------------------------- ### Search for Artist Image URL by Name Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Searches for an artist by name and retrieves the URL of their primary image. It handles command-line arguments for the artist name or defaults to 'Radiohead'. ```Python import spotipy import sys from spotipy.oauth2 import SpotifyClientCredentials spotify = spotipy.Spotify(auth_manager=SpotifyClientCredentials()) if len(sys.argv) > 1: name = ' '.join(sys.argv[1:]) else: name = 'Radiohead' results = spotify.search(q='artist:' + name, type='artist') items = results['artists']['items'] if len(items) > 0: artist = items[0] print(artist['name'], artist['images'][0]['url']) ``` -------------------------------- ### Retrieve Artist Information Source: https://spotipy.readthedocs.io/en/2.25.1/index Details the `artist` method for fetching a single artist's data using their ID, URI, or URL. ```Python sp.artist(_artist_id_) ``` -------------------------------- ### List Artist Albums Source: https://spotipy.readthedocs.io/en/2.25.1/_sources/index Fetches and prints the names of all albums released by a given artist. It uses the artist's Spotify URI and handles pagination for albums. ```Python import spotipy from spotipy.oauth2 import SpotifyClientCredentials birdy_uri = 'spotify:artist:2WX2uTcsvV5OnS0inACecP' spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials()) results = spotify.artist_albums(birdy_uri, album_type='album') albums = results['items'] while results['next']: results = spotify.next(results) albums.extend(results['items']) for album in albums: print(album['name']) ``` -------------------------------- ### Reorder Tracks in Spotify Playlist Source: https://spotipy.readthedocs.io/en/2.25.1/index Reorders tracks within a playlist for a user. This function is deprecated; refer to the warning for the recommended alternative. It requires the start position, insert position, and optionally the range length and snapshot ID. ```python user_playlist_reorder_tracks(_user_ , _playlist_id_ , _range_start_ , _insert_before_ , _range_length =1_, _snapshot_id =None_) This function is no longer in use, please use the recommended function in the warning! Reorder tracks in a playlist from a user Parameters: * user - the id of the user * playlist_id - the id of the playlist * range_start - the position of the first track to be reordered * range_length - optional the number of tracks to be reordered (default: 1) * insert_before - the position where the tracks should be inserted * snapshot_id - optional playlist’s snapshot ID ``` -------------------------------- ### Add User Saved Episodes Source: https://spotipy.readthedocs.io/en/2.25.1/index Adds one or more episodes to the current user's "Your Music" library. Requires a list of episode URIs, URLs, or IDs. ```Python current_user_saved_episodes_add(_episodes =None_) # Parameters: # episodes - a list of episode URIs, URLs or IDs ``` -------------------------------- ### Set Spotipy Environment Variables (Client Credentials Flow) Source: https://spotipy.readthedocs.io/en/2.25.1/index Sets environment variables for Spotify API client ID and client secret, used for the Client Credentials flow. The redirect URI is not required for this flow. ```Shell export SPOTIPY_CLIENT_ID='your-spotify-client-id' export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret' ``` -------------------------------- ### Spotipy: User Information and Following Source: https://spotipy.readthedocs.io/en/2.25.1/genindex Methods to retrieve and manage user-specific data, including user profiles, playlists, and followed artists/users. These functions interact with the Spotify API on behalf of the authenticated user. ```Python user() user_follow_artists() user_follow_users() user_playlist() user_playlist_add_episodes() user_playlist_add_tracks() user_playlist_change_details() user_playlist_create() user_playlist_follow_playlist() user_playlist_is_following() user_playlist_remove_all_occurrences_of_tracks() user_playlist_remove_specific_occurrences_of_tracks() user_playlist_reorder_tracks() user_playlist_replace_tracks() user_playlist_tracks() user_playlist_unfollow() user_playlists() user_unfollow_artists() user_unfollow_users() ``` -------------------------------- ### Skip to Next Track Source: https://spotipy.readthedocs.io/en/2.25.1/index Advances the user's playback to the next track. Optionally targets a specific device for playback control. ```python sp.next_track(_device_id =None_) ``` -------------------------------- ### Search Items Across Multiple Markets Source: https://spotipy.readthedocs.io/en/2.25.1/index An experimental function to search for items across multiple specified markets. Requires a search query and accepts limit, offset, type, and a list of markets. ```python search_markets(_q_ , _limit =10_, _offset =0_, _type ='track'_, _markets =None_, _total =None_) ``` -------------------------------- ### Spotipy: Playback Transfer Source: https://spotipy.readthedocs.io/en/2.25.1/genindex Method to transfer playback between different devices or contexts on Spotify. ```Python transfer_playback() ``` -------------------------------- ### Spotipy: Authentication and Token Management Source: https://spotipy.readthedocs.io/en/2.25.1/genindex Classes and methods for handling Spotify authentication, including OAuth flows and token management. This is crucial for authorizing access to user data and API functionalities. ```Python OAUTH_AUTHORIZE_URL OAUTH_TOKEN_URL parse_auth_response_url() parse_response_code() parse_response_token() refresh_access_token() set_auth() validate_token() SpotifyImplicitGrant SpotifyOAuth SpotifyPKCE ```