### Setup Development Environment and Run Tests Source: https://spotipy.readthedocs.io/en/latest/_sources/index.rst.txt Commands to initialize a virtual environment, install dependencies, and execute the test suite. ```bash $ virtualenv --python=python3.12 env (env) $ pip install --user -e . (env) $ python -m unittest discover -v tests ``` -------------------------------- ### Example: Get Top Tracks, Preview URL, and Cover Art Source: https://spotipy.readthedocs.io/en/latest/_sources/index.rst.txt Demonstrates how to retrieve the top 10 tracks for an artist, including their preview URLs and cover art. ```APIDOC ## Example: Get Top Tracks, Preview URL, and Cover Art ### Description This example fetches the top 10 tracks for a specified artist and prints their name, preview URL, and the URL of their album's cover art. ### Method `spotify.artist_top_tracks()` ### Endpoint N/A (Method call within the Spotipy library) ### Parameters - **artist_uri** (string) - Required - The Spotify URI of the artist. ### Request Example ```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) ``` ### Response #### Success Response (200) Returns a dictionary containing a list of tracks, where each track object includes details like `name`, `preview_url`, and `album` information (which contains `images`). #### Response Example ```json { "tracks": [ { "name": "Stairway to Heaven", "preview_url": "https://p.scdn.co/mp3-preview/...". "album": { "images": [ { "url": "https://i.scdn.co/image/abc123def456..." // ... other image sizes } ] // ... other album details } // ... other track details } // ... more tracks ] } ``` ### Code Example (Full) ```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() ``` ``` -------------------------------- ### Authorization Code Flow - Quick Start Source: https://spotipy.readthedocs.io/en/latest/index.html Example demonstrating how to use the SpotifyOAuth class for the Authorization Code Flow to authenticate requests and retrieve saved tracks. ```APIDOC ## POST /authorize ### Description This endpoint is part of the Authorization Code Flow and is used to initiate the user authorization process. It redirects the user to Spotify's authorization page to grant permissions. ### Method GET ### Endpoint /authorize ### Parameters #### Query Parameters - **client_id** (string) - Required - Your Spotify application's client ID. - **response_type** (string) - Required - Set to 'code' for the Authorization Code Flow. - **redirect_uri** (string) - Required - The redirect URI configured in your Spotify application. - **scope** (string) - Optional - A space-separated list of scopes to request. - **state** (string) - Optional - Used to maintain state between the request and callback to prevent cross-site request forgery attacks. ### Request Example ``` https://accounts.spotify.com/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=YOUR_REDIRECT_URI&scope=user-library-read ``` ## POST /api/token ### Description This endpoint is used to exchange an authorization code for an access token and a refresh token, or to refresh an existing access token. ### Method POST ### Endpoint /api/token ### Parameters #### Request Body - **grant_type** (string) - Required - Either 'authorization_code' to exchange a code, or 'refresh_token' to refresh an existing token. - **code** (string) - Required if grant_type is 'authorization_code' - The authorization code received from the authorization endpoint. - **redirect_uri** (string) - Required if grant_type is 'authorization_code' - The redirect URI used in the authorization request. - **refresh_token** (string) - Required if grant_type is 'refresh_token' - The refresh token obtained previously. - **client_id** (string) - Required - Your Spotify application's client ID. - **client_secret** (string) - Required - Your Spotify application's client secret. ### Request Example (Authorization Code Exchange) ```json { "grant_type": "authorization_code", "code": "YOUR_AUTHORIZATION_CODE", "redirect_uri": "YOUR_REDIRECT_URI", "client_id": "YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET" } ``` ### Request Example (Token Refresh) ```json { "grant_type": "refresh_token", "refresh_token": "YOUR_REFRESH_TOKEN", "client_id": "YOUR_CLIENT_ID", "client_secret": "YOUR_CLIENT_SECRET" } ``` ### Response #### Success Response (200) - **access_token** (string) - The access token for making API requests. - **token_type** (string) - The type of token (e.g., 'Bearer'). - **expires_in** (integer) - The number of seconds until the access token expires. - **refresh_token** (string) - The refresh token (only provided when grant_type is 'authorization_code'). - **scope** (string) - The scopes granted to this token. #### Response Example ```json { "access_token": "BQC_...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "NgA...", "scope": "user-library-read" } ``` ## GET /me/tracks ### Description Retrieves a list of tracks saved in the current Spotify user's "Your Music" library. ### Method GET ### Endpoint /me/tracks ### Parameters #### Query Parameters - **limit** (integer) - Optional - Maximum number of items to return. Default: 20. Maximum: 50. - **offset** (integer) - Optional - The index of the first item to return. Default: 0. - **market** (string) - Optional - An ISO 3166-1 alpha-2 country code or the keyword 'from_token'. ### Response #### Success Response (200) - **items** (array) - A list of saved track objects. - **next** (string) - URL to the next page of results, or null if there is no next page. - **offset** (integer) - The offset from the end of the playlist. - **previous** (string) - URL to the previous page of results, or null if there is no previous page. - **total** (integer) - The total number of saved tracks. #### Response Example ```json { "href": "https://api.spotify.com/v1/me/tracks?offset=0&limit=20", "items": [ { "added_at": "2023-01-01T10:00:00Z", "track": { "album": { "album_type": "album", "artists": [ { "external_urls": { "spotify": "https://open.spotify.com/artist/1XdpDAKM52vS7v4fSg2j9m" }, "href": "https://api.spotify.com/v1/artists/1XdpDAKM52vS7v4fSg2j9m", "id": "1XdpDAKM52vS7v4fSg2j9m", "name": "Artist Name", "type": "artist", "uri": "spotify:artist:1XdpDAKM52vS7v4fSg2j9m" } ], "external_urls": { "spotify": "https://open.spotify.com/album/5r36epY233f7aY7z7z7z7z" }, "href": "https://api.spotify.com/v1/albums/5r36epY233f7aY7z7z7z7z", "id": "5r36epY233f7aY7z7z7z7z", "images": [ { "height": 640, "url": "https://i.scdn.co/image/ab67616d0000b2733f7aY7z7z7z7z", "width": 640 } ], "name": "Album Name", "release_date": "2022-01-01", "release_date_precision": "day", "total_tracks": 10, "type": "album", "uri": "spotify:album:5r36epY233f7aY7z7z7z7z" }, "artists": [ { "external_urls": { "spotify": "https://open.spotify.com/artist/1XdpDAKM52vS7v4fSg2j9m" }, "href": "https://api.spotify.com/v1/artists/1XdpDAKM52vS7v4fSg2j9m", "id": "1XdpDAKM52vS7v4fSg2j9m", "name": "Artist Name", "type": "artist", "uri": "spotify:artist:1XdpDAKM52vS7v4fSg2j9m" } ], "disc_number": 1, "duration_ms": 180000, "explicit": false, "external_ids": { "isrc": "USABC1234567" }, "external_urls": { "spotify": "https://open.spotify.com/track/12345abcde" }, "href": "https://api.spotify.com/v1/tracks/12345abcde", "id": "12345abcde", "is_local": false, "is_playable": true, "name": "Track Name", "popularity": 80, "preview_url": "https://p.scdn.co/mp3-preview/abcdef1234567890", "track_number": 1, "type": "track", "uri": "spotify:track:12345abcde" } } ], "limit": 20, "next": null, "offset": 0, "previous": null, "total": 1 } ``` ``` -------------------------------- ### Create Virtual Environment and Install Spotipy Source: https://spotipy.readthedocs.io/en/latest/index.html Steps to set up a Python virtual environment, install Spotipy, and run tests. ```bash $ virtualenv –python=python3.12 env (env) $ pip install –user -e . (env) $ python -m unittest discover -v tests ``` -------------------------------- ### Example: Search for Artist and Get Image URL Source: https://spotipy.readthedocs.io/en/latest/_sources/index.rst.txt Demonstrates how to search for an artist by name and retrieve the URL of their primary image. ```APIDOC ## Example: Search for Artist and Get Image URL ### Description This example shows how to search for an artist using their name and then extract the URL of their main profile image. ### Method `spotify.search()` ### Endpoint N/A (Method call within the Spotipy library) ### Parameters - **q** (string) - Required - The search query. Format: `artist:Artist Name`. - **type** (string) - Required - The type of item to search for, e.g., `artist`. ### Request Example ```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') ``` ### Response #### Success Response (200) Returns a dictionary containing search results. For artist searches, it includes an `artists` object with an `items` list, where each artist item contains `name` and `images` (a list of image URLs). #### Response Example ```json { "artists": { "items": [ { "name": "Radiohead", "images": [ { "url": "https://i.scdn.co/image/abcdef123456..." // ... other image sizes } ] // ... other artist details } // ... more artists if multiple match ] } } ``` ### Code Example (Full) ```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']) ``` ``` -------------------------------- ### Install Spotipy Source: https://spotipy.readthedocs.io/en/latest/_sources/index.rst.txt Install or upgrade Spotipy using pip. ```bash pip install spotipy --upgrade ``` -------------------------------- ### Example: List Artist Albums Source: https://spotipy.readthedocs.io/en/latest/_sources/index.rst.txt A practical example demonstrating how to fetch and list all albums released by a specific artist. ```APIDOC ## Example: List Artist Albums ### Description This example shows how to retrieve all albums for a given artist using their Spotify URI. ### Method `spotify.artist_albums()` ### Endpoint N/A (Method call within the Spotipy library) ### Parameters - **artist_uri** (string) - Required - The Spotify URI of the artist. - **album_type** (string) - Optional - Specifies the type of albums to retrieve (e.g., 'album', 'single', 'compilation'). ### Request Example ```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') ``` ### Response #### Success Response (200) Returns a dictionary containing album information, including `items` (list of albums) and `next` (URL for the next page of results). #### Response Example ```json { "items": [ { "name": "Beautiful Birds", "uri": "spotify:album:3r245a9j0QJ70010j3056M" // ... other album details } // ... more albums ], "next": "https://api.spotify.com/v1/artists/2WX2uTcsvV5OnS0inACecP/albums?offset=20&limit=20" } ``` ### Code Example (Full) ```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']) ``` ``` -------------------------------- ### Quick Start with SpotifyOAuth Source: https://spotipy.readthedocs.io/en/latest/index.html Example of using SpotifyOAuth for the Authorization Code Flow. It authenticates a user and fetches their saved tracks. Ensure you have set the SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET, and SPOTIPY_REDIRECT_URI environment variables. ```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 Artist Top Tracks with Spotipy Source: https://spotipy.readthedocs.io/en/latest/index.html This example fetches the top 10 tracks for an artist, including their preview URLs and cover art. Requires Spotify client 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() ``` -------------------------------- ### PUT /me/player/play Source: https://spotipy.readthedocs.io/en/latest/index.html Start or resume user's playback. ```APIDOC ## PUT /me/player/play ### Description Start or resume user’s playback. ### Method PUT ### Parameters #### Query Parameters - **device_id** (string) - Optional - device target for playback - **context_uri** (string) - Optional - spotify context uri to play - **uris** (list) - Optional - spotify track uris - **offset** (object) - Optional - offset into context by index or track - **position_ms** (integer) - Optional - indicates from what position to start playback ``` -------------------------------- ### Get Recommendations Source: https://spotipy.readthedocs.io/en/latest/index.html Get a list of recommended tracks for one to five seeds. At least one of seed_artists, seed_tracks, and seed_genres is needed. This endpoint has been removed by Spotify and is no longer available. ```APIDOC ## GET /recommendations ### Description Get a list of recommended tracks for one to five seeds. (at least one of seed_artists, seed_tracks and seed_genres are needed) This endpoint has been removed by Spotify and is no longer available. ### Method GET ### Endpoint /recommendations ### Parameters #### Query Parameters - **seed_artists** (array of strings) - Optional - A list of artist IDs, URIs or URLs. - **seed_tracks** (array of strings) - Optional - A list of track IDs, URIs or URLs. - **seed_genres** (array of strings) - Optional - A list of genre names. Available genres for recommendation. - **limit** (integer) - Optional - The maximum number of tracks to return (default: 20). - **country** (string) - Optional - An ISO 3166-1 alpha-2 country code. - **kwargs** - Additional keyword arguments. ``` -------------------------------- ### GET /shows/{id} Source: https://spotipy.readthedocs.io/en/latest/index.html Retrieve information about a single show. ```APIDOC ## GET /shows/{id} ### Description Returns a single show given the show’s ID, URIs or URL. ### Method GET ### Parameters #### Path Parameters - **show_id** (string) - Required - the show ID, URI or URL #### Query Parameters - **market** (string) - Optional - an ISO 3166-1 alpha-2 country code ``` -------------------------------- ### GET /search Source: https://spotipy.readthedocs.io/en/latest/index.html Search for items such as tracks, albums, or artists. ```APIDOC ## GET /search ### Description Searches for an item. ### Method GET ### Parameters #### Query Parameters - **q** (string) - Required - the search query - **limit** (integer) - Optional - the number of items to return (min = 1, default = 10, max = 50) - **offset** (integer) - Optional - the index of the first item to return - **type** (string) - Optional - the types of items to return (e.g., 'track,album,episode') - **market** (string) - Optional - An ISO 3166-1 alpha-2 country code or the string from_token ``` -------------------------------- ### Verify Code Style with Flake8 Source: https://spotipy.readthedocs.io/en/latest/index.html Check your Python code for style guide violations. ```bash pip install flake8 flake8 . ``` -------------------------------- ### Get Artist Information Source: https://spotipy.readthedocs.io/en/latest/index.html Retrieves details for a single artist using their ID, URI, or URL. ```python sp.artist(_artist_id_) ``` -------------------------------- ### Initialize and Use Spotipy Client Source: https://spotipy.readthedocs.io/en/latest/index.html Demonstrates basic usage of the Spotipy client to fetch artist and user information. Ensure you have the spotipy library installed. ```python import spotipy urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu' sp = spotipy.Spotify() artist = sp.artist(urn) print(artist) user = sp.user('plamere') print(user) ``` -------------------------------- ### Get Album Tracks Source: https://spotipy.readthedocs.io/en/latest/index.html Fetches catalog information about an album's tracks. You can specify the number of tracks to return (limit) and the starting offset. The 'market' parameter filters by country. ```python sp.album_tracks(_album_id_ , _limit =50_, _offset =0_, _market =None_) ``` -------------------------------- ### SpotifyPKCE Class Initialization Source: https://spotipy.readthedocs.io/en/latest/index.html Initializes the SpotifyPKCE manager for PKCE Authorization Flow. ```APIDOC ## SpotifyPKCE Initialization ### Description Implements PKCE Authorization Flow for client apps, enabling user and non-user endpoints with only a client ID, redirect URI, and username. ### Parameters - **client_id** (string) - Optional - **redirect_uri** (string) - Optional - **state** (string) - Optional - **scope** (list/string) - Optional - **cache_path** (string) - Optional - **username** (string) - Optional - **proxies** (dict) - Optional - **requests_timeout** (int) - Optional - **requests_session** (boolean) - Optional - **open_browser** (boolean) - Optional - **cache_handler** (object) - Optional ``` -------------------------------- ### Package and Upload to PyPI Source: https://spotipy.readthedocs.io/en/latest/index.html Commands to build source distributions and wheels, and then upload them to PyPI using twine. Ensure you have the necessary credentials configured for twine. ```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/* ``` -------------------------------- ### User Playlists Source: https://spotipy.readthedocs.io/en/latest/index.html Get current user playlists without required getting his profile. ```APIDOC ## GET /me/playlists ### Description Get current user playlists without required getting his profile. ### Method GET ### Endpoint /me/playlists ### Parameters #### Query Parameters - **limit** (integer) - Optional - The number of items to return. Default: 50. - **offset** (integer) - Optional - The index of the first item to return. Default: 0. ``` -------------------------------- ### Spotify Client Initialization Source: https://spotipy.readthedocs.io/en/latest/index.html Initializes the Spotify API client with various configuration options. ```APIDOC ## Spotify Client Initialization ### Description Creates a Spotify API client instance. This client can be used to interact with the Spotify Web API. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **auth** (string) - Optional - An access token. - **requests_session** (bool or requests.Session) - Optional - A Requests session object or a truthy value to create one. A falsy value disables sessions. It should generally be a good idea to keep sessions enabled for performance reasons (connection pooling). - **client_credentials_manager** (SpotifyClientCredentials) - Optional - SpotifyClientCredentials object. - **oauth_manager** (SpotifyOAuth) - Optional - SpotifyOAuth object. - **auth_manager** (SpotifyOauth, SpotifyClientCredentials, or SpotifyImplicitGrant) - Optional - An authentication manager object. - **proxies** (dict) - Optional - Definition of proxies. See Requests doc https://2.python-requests.org/en/master/user/advanced/#proxies - **requests_timeout** (int) - Optional - Tell Requests to stop waiting for a response after a given number of seconds. - **status_forcelist** (list) - Optional - Tell requests what type of status codes retries should occur on. - **retries** (int) - Optional - Total number of retries to allow. - **status_retries** (int) - Optional - Number of times to retry on bad status codes. - **backoff_factor** (float) - Optional - A backoff factor to apply between attempts after the second try. See urllib3 https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html - **language** (str) - Optional - The language parameter advertises what language the user prefers to see. See ISO-639-1 language code: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes ### Request Example ```python import spotipy sp = spotipy.Spotify(auth_manager=spotipy.SpotifyClientCredentials()) ``` ### Response None (initializes the client object) ``` -------------------------------- ### Get Recommended Genres Source: https://spotipy.readthedocs.io/en/latest/index.html Get a list of genres available for the recommendations function. This endpoint has been removed by Spotify and is no longer available. ```APIDOC ## GET /recommendations/available-genre-seeds ### Description Get a list of genres available for the recommendations function. This endpoint has been removed by Spotify and is no longer available. ### Method GET ### Endpoint /recommendations/available-genre-seeds ``` -------------------------------- ### Categories Source: https://spotipy.readthedocs.io/en/latest/index.html Get a list of categories. ```APIDOC ## GET /browse/categories ### Description Get a list of categories. ### Method GET ### Endpoint /browse/categories ### Parameters #### Query Parameters - **country** (string) - Optional - An ISO 3166-1 alpha-2 country code. - **locale** (string) - Optional - The desired language, consisting of an ISO 639-1 alpha-2 language code and an ISO 3166-1 alpha-2 country code, joined by an underscore. - **limit** (integer) - Optional - The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50 - **offset** (integer) - Optional - The index of the first item to return. Default: 0 (the first object). Use with limit to get the next set of items. ``` -------------------------------- ### Package and Upload to PyPI Source: https://spotipy.readthedocs.io/en/latest/_sources/index.rst.txt Commands to build distribution packages and upload them to the PyPI repository. ```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 ``` -------------------------------- ### PKCE Auth Manager Initialization Source: https://spotipy.readthedocs.io/en/latest/index.html Initializes the Auth Manager using the PKCE flow for Spotify authentication. ```APIDOC ## PKCE Auth Manager Initialization ### Description Creates an Auth Manager instance configured for the PKCE authentication flow. ### Parameters - **client_id** (string) - Required - Client ID for the application. - **redirect_uri** (string) - Required - Redirect URI for the application. - **state** (string) - Optional - State for verification. - **scope** (list/string) - Optional - List or comma-separated string of scopes. - **cache_path** (string) - Optional - Path to cache file. - **username** (string) - Optional - Spotify username. - **proxies** (dict) - Optional - Proxy configuration. - **requests_timeout** (int) - Optional - Timeout in seconds. - **requests_session** (bool) - Optional - Use a requests session. - **open_browser** (bool) - Optional - Whether to open the browser for auth. - **cache_handler** (object) - Optional - Instance of CacheHandler. ``` -------------------------------- ### Category Source: https://spotipy.readthedocs.io/en/latest/index.html Get info about a specific category. ```APIDOC ## GET /browse/categories/{category_id} ### Description Get info about a category. ### Method GET ### Endpoint /browse/categories/{category_id} ### Parameters #### Path Parameters - **category_id** (string) - Required - The Spotify category ID for the category. #### Query Parameters - **country** (string) - Optional - An ISO 3166-1 alpha-2 country code. - **locale** (string) - Optional - The desired language, consisting of an ISO 639-1 alpha-2 language code and an ISO 3166-1 alpha-2 country code, joined by an underscore. ``` -------------------------------- ### GET /parse_response_code Source: https://spotipy.readthedocs.io/en/latest/index.html Parses the response code from a given URL. ```APIDOC ## GET /parse_response_code ### Description Extracts the authorization code from the provided response URL. ### Parameters - **url** (string) - Required - The response URL containing the code. ``` -------------------------------- ### Set Spotify Client Credentials Source: https://spotipy.readthedocs.io/en/latest/_sources/index.rst.txt Set the SPOTIPY_CLIENT_ID and SPOTIPY_CLIENT_SECRET environment variables before running your application. ```bash export SPOTIPY_CLIENT_ID='your-spotify-client-id' export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret' ``` -------------------------------- ### Set Environment Variables for Credentials Source: https://spotipy.readthedocs.io/en/latest/_sources/index.rst.txt Configure Spotify API credentials and redirect URI using environment variables. Use $env:"credentials" syntax on Windows. ```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' ``` -------------------------------- ### Initialize SpotifyClientCredentials Source: https://spotipy.readthedocs.io/en/latest/index.html Use this class for server-to-server authentication to access endpoints that do not require user information. Provide client ID and secret directly or via environment variables. ```python SpotifyClientCredentials(client_id=None, client_secret=None, proxies=None, requests_session=True, requests_timeout=None, cache_handler=None) ``` -------------------------------- ### Export Environment Variables Source: https://spotipy.readthedocs.io/en/latest/_sources/index.rst.txt Set the required Spotify API credentials and redirect URI as environment variables. ```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 ``` -------------------------------- ### Available Markets Source: https://spotipy.readthedocs.io/en/latest/index.html Get the list of markets where Spotify is available. ```APIDOC ## GET /markets ### Description Get the list of markets where Spotify is available. Returns a list of the countries in which Spotify is available, identified by their ISO 3166-1 alpha-2 country code with additional country codes for special territories. ### Method GET ### Endpoint /markets ``` -------------------------------- ### POST /prompt_for_user_token Source: https://spotipy.readthedocs.io/en/latest/index.html Prompts the user to log in and returns a token for the Spotify constructor. ```APIDOC ## POST /prompt_for_user_token ### Description Prompts the user to login if necessary and returns a user token. Note: This method is deprecated. ### Parameters - **username** (string) - Optional - Spotify username. - **scope** (string) - Optional - Desired scope. - **client_id** (string) - Required - App client ID. - **client_secret** (string) - Required - App client secret. - **redirect_uri** (string) - Required - App redirect URI. - **cache_path** (string) - Required - Path to save tokens. - **oauth_manager** (object) - Optional - OAuth manager object. - **show_dialog** (bool) - Optional - Whether to force a login prompt. ``` -------------------------------- ### GET /me/top/artists Source: https://spotipy.readthedocs.io/en/latest/index.html Retrieves the current user's top artists. ```APIDOC ## GET /me/top/artists ### Description Get the current user’s top artists. ### Method GET ### Parameters #### Query Parameters - **limit** (integer) - Optional - The number of entities to return (max 50) - **offset** (integer) - Optional - The index of the first entity to return - **time_range** (string) - Optional - Over what time frame are the affinities computed. Valid values: short_term, medium_term, long_term ``` -------------------------------- ### Current Playback Source: https://spotipy.readthedocs.io/en/latest/index.html Get information about the user's current playback. ```APIDOC ## GET /me/player ### Description Get information about user’s current playback. ### Method GET ### Endpoint /me/player ### Parameters #### Query Parameters - **market** (string) - Optional - An ISO 3166-1 alpha-2 country code. - **additional_types** (string) - Optional - episode to get podcast track information ``` -------------------------------- ### Get Top Tracks, Preview URLs, and Cover Art Source: https://spotipy.readthedocs.io/en/latest/_sources/index.rst.txt Fetch the top 10 tracks for an artist, including their names, 30-second preview URLs, and the URL of their album's cover art. ```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() ``` -------------------------------- ### Create Playlist Source: https://spotipy.readthedocs.io/en/latest/index.html Creates a playlist for the current user. ```APIDOC ## POST /users/{user_id}/playlists ### Description Creates a playlist for the current user. ### Method POST ### Endpoint /users/{user_id}/playlists ### Parameters #### Path Parameters - **user_id** (string) - Required - The user's ID. #### Request Body - **name** (string) - Required - The name of the playlist. - **public** (boolean) - Optional - Is the created playlist public. Default: true. - **collaborative** (boolean) - Optional - Is the created playlist collaborative. Default: false. - **description** (string) - Optional - The description of the playlist. Default: ''. ``` -------------------------------- ### Get Previous Result Source: https://spotipy.readthedocs.io/en/latest/index.html Returns the previous result given a paged result. ```APIDOC ## GET /previous ### Description Returns the previous result given a paged result. ### Method GET ### Endpoint /previous ### Parameters #### Query Parameters - **result** (object) - Required - A previously returned paged result. ``` -------------------------------- ### Get Playlist Cover Image Source: https://spotipy.readthedocs.io/en/latest/index.html Retrieves the cover image for a specific playlist. ```APIDOC ## GET /playlists/{playlist_id}/images ### Description Get cover image of a playlist. ### Method GET ### Endpoint /playlists/{playlist_id}/images ### Parameters #### Path Parameters - **playlist_id** (string) - Required - The playlist ID, URI or URL. ``` -------------------------------- ### Client Credentials Flow Authentication Source: https://spotipy.readthedocs.io/en/latest/_sources/index.rst.txt Demonstrates how to authenticate using the Client Credentials Flow with Spotipy, enabling access to public data. ```APIDOC ## Client Credentials Flow Authentication ### Description This section shows how to set up authentication using the Client Credentials Flow, which is suitable for accessing public data without user authorization. ### Method Client Credentials Flow ### Endpoint N/A (Client-side authentication) ### Parameters #### Environment Variables - **SPOTIPY_CLIENT_ID** (string) - Required - Your Spotify application's Client ID. - **SPOTIPY_CLIENT_SECRET** (string) - Required - Your Spotify application's Client Secret. ### Request Example ```bash export SPOTIPY_CLIENT_ID='your-spotify-client-id' export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret' ``` ### Code Example ```python import spotipy from spotipy.oauth2 import SpotifyClientCredentials auth_manager = SpotifyClientCredentials() sp = spotipy.Spotify(auth_manager=auth_manager) # Example usage: Get user playlists 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 ``` ### Response #### Success Response (200) N/A (This is a client-side authentication setup, responses are handled by the Spotify API for subsequent requests.) #### Response Example N/A ``` -------------------------------- ### Followed Artists Source: https://spotipy.readthedocs.io/en/latest/index.html Gets a list of the artists followed by the current authorized user. ```APIDOC ## GET /me/following ### Description Gets a list of the artists followed by the current authorized user. ### Method GET ### Endpoint /me/following ### Parameters #### Query Parameters - **limit** (integer) - Optional - The number of artists to return. Default: 20. - **after** (string) - Optional - The last artist ID retrieved from the previous request. ``` -------------------------------- ### Initialize SpotifyImplicitGrant Source: https://spotipy.readthedocs.io/en/latest/index.html Implements the Implicit Grant Flow for client applications. Note: This flow is not recommended for client-side code due to security concerns. Consider using SpotifyPKCE instead. ```python SpotifyImplicitGrant(client_id=None, redirect_uri=None, state=None, scope=None, cache_path=None, username=None, show_dialog=False, cache_handler=None) ``` -------------------------------- ### Current User Profile Source: https://spotipy.readthedocs.io/en/latest/index.html Get detailed profile information about the current user. ```APIDOC ## GET /me ### Description Get detailed profile information about the current user. An alias for the ‘me’ method. ### Method GET ### Endpoint /me ``` -------------------------------- ### SpotifyOAuth Class Initialization Source: https://spotipy.readthedocs.io/en/latest/index.html Initializes the SpotifyOAuth manager to handle the Authorization Code Flow. ```APIDOC ## SpotifyOAuth Initialization ### Description Creates a SpotifyOAuth object to manage the Authorization Code Flow for Spotify's OAuth implementation. ### Parameters - **client_id** (string) - Optional - Must be supplied or set as environment variable - **client_secret** (string) - Optional - Must be supplied or set as environment variable - **redirect_uri** (string) - Optional - Must be supplied or set as environment variable - **state** (string) - Optional - No verification is performed - **scope** (list/string) - Optional - List of scopes or comma separated string - **cache_path** (string) - Optional - Path for token caching - **username** (string) - Optional - Used to set cache_path - **proxies** (dict) - Optional - Proxy settings for requests - **show_dialog** (boolean) - Optional - Whether to show the authorization dialog - **requests_session** (boolean) - Optional - Use a Requests session - **requests_timeout** (int) - Optional - Timeout in seconds - **open_browser** (boolean) - Optional - Whether to open the browser for authorization - **cache_handler** (object) - Optional - Instance of CacheHandler ```