Connect Retool to the Spotify Web API using a REST API Resource with OAuth 2.0. Use client credentials for public catalog data or the authorization code flow for user library access. Build queries to search tracks, view audio features, and manage playlists. The setup takes about 20 minutes and enables music analytics and playlist management dashboards.
| Fact | Value |
|---|---|
| Tool | Spotify |
| Category | Social |
| Method | REST API Resource |
| Difficulty | Intermediate |
| Time required | 20 minutes |
| Last updated | April 2026 |
Why Connect Retool to Spotify?
Music labels, playlist curators, artist managers, and music marketing teams often need more analytical depth than Spotify for Artists provides. The Spotify Web API exposes detailed audio features (energy, danceability, tempo, valence, acousticness), track popularity scores, artist follower counts, and playlist composition data that power internal analytics tools far more powerful than the native Spotify dashboards. Connecting Retool to Spotify makes this data accessible to operations teams without building custom web applications.
The Spotify API uses a clean OAuth 2.0 flow. For public catalog data — searching tracks, browsing artist profiles, fetching album information, and analyzing audio features — the client credentials grant requires only a client_id and client_secret with no user authentication. This makes read-only analytics dashboards simple to set up. For managing playlists, viewing a user's listening history, or accessing saved tracks, the authorization code flow adds a user authentication step that issues a user-specific access token.
Typical Retool use cases include artist roster dashboards for labels tracking catalog metrics across multiple signed artists, playlist editorial tools for curators comparing audio feature profiles of candidate tracks, and music marketing dashboards combining Spotify popularity data with social media metrics. Since Retool's server-side proxy handles the OAuth token exchange, complex OAuth flows that would cause CORS issues in browser-based apps work seamlessly.
Integration method
Spotify does not have a native Retool connector. Integration is achieved by configuring Spotify's Web API as a REST API Resource in Retool. Authentication uses OAuth 2.0 client credentials for public catalog data (no user login required) or an authorization code flow for accessing user-specific data like playlists and listening history. Retool proxies all requests server-side, so credentials never reach the browser and CORS is not an issue.
Prerequisites
- A Spotify account (free or premium) with access to the Spotify Developer Dashboard
- A Spotify app registered at developer.spotify.com/dashboard to obtain client_id and client_secret
- A Retool account (Cloud or self-hosted) with permission to add Resources
- Basic familiarity with OAuth 2.0 concepts (client credentials vs. authorization code flows)
Step-by-step guide
Register a Spotify app and obtain client credentials
Navigate to the Spotify Developer Dashboard at developer.spotify.com/dashboard and log in with your Spotify account. Click the Create App button. Fill in the required fields: App Name (e.g., 'Retool Music Analytics'), App Description (briefly describe the internal tool use case), and Website (your company website or Retool instance URL). In the Redirect URIs field, add a placeholder URI — for client credentials flow you do not need a real redirect URI, but the form requires at least one. Use https://localhost for now or your Retool instance URL if you plan to implement user OAuth later. Check the 'Web API' checkbox in the API/SDKs section. Accept the Developer Terms of Service and click Save. After the app is created, you land on the app's settings page. Click the View Client Secret button to reveal the client secret. Copy both the Client ID (displayed on the page) and the Client Secret to a secure location immediately. The client secret is shown only once and will be masked afterwards — if you lose it, you must regenerate it. In Retool, go to Settings (gear icon in the left sidebar) → Configuration Variables. Create two new Secret variables: SPOTIFY_CLIENT_ID with the Client ID value, and SPOTIFY_CLIENT_SECRET with the Client Secret value. Toggle both to Secret so they are restricted to resource configurations and never exposed to the browser.
Pro tip: If your dashboard needs to access user-specific data (playlists, saved tracks, listening history), add your Retool app's OAuth callback URL to the Redirect URIs list in the Spotify Developer Dashboard. For client credentials flow (public catalog only), the redirect URI is not used.
Expected result: A Spotify app is registered with a client_id and client_secret. Both are stored as Secret Configuration Variables in Retool. The Spotify Developer Dashboard shows the app as Active.
Create a Spotify token acquisition query and REST API Resource
Spotify's API requires a Bearer access token in every request. These tokens expire after 3600 seconds (1 hour) and must be refreshed. Start by creating a REST API Resource for the Spotify Accounts Service: navigate to Resources tab → Add Resource → REST API. Name it 'Spotify Auth', set Base URL to https://accounts.spotify.com. Add a header: Content-Type = application/x-www-form-urlencoded. Click Save. Now create a second REST API Resource named 'Spotify API'. Base URL = https://api.spotify.com/v1. In the Headers section, add Authorization = Bearer {{ getSpotifyToken.data.access_token }} — this dynamically injects the token obtained by a query named getSpotifyToken (which you will create in your apps). Click Save. Open or create a Retool app. In the Code panel, create a query named getSpotifyToken. Resource = Spotify Auth, method = POST, path = /api/token. Set Body Type to x-www-form-urlencoded and add parameters: grant_type = client_credentials, client_id = {{ retoolContext.configVars.SPOTIFY_CLIENT_ID }}, client_secret = {{ retoolContext.configVars.SPOTIFY_CLIENT_SECRET }}. Set Trigger to run automatically on page load. Set a cache duration of 3500 seconds so the token is reused within apps without redundant requests. This query returns { access_token: '...', token_type: 'Bearer', expires_in: 3600 }. The access_token is referenced in the Spotify API resource's Authorization header, automatically included in all subsequent API queries.
1{2 "method": "POST",3 "path": "/api/token",4 "body": {5 "grant_type": "client_credentials",6 "client_id": "{{ retoolContext.configVars.SPOTIFY_CLIENT_ID }}",7 "client_secret": "{{ retoolContext.configVars.SPOTIFY_CLIENT_SECRET }}"8 },9 "bodyType": "x-www-form-urlencoded"10}Pro tip: Set the getSpotifyToken query as a dependency for all other Spotify queries by referencing {{ getSpotifyToken.data.access_token }} in the Authorization header. Retool automatically runs getSpotifyToken first when any dependent query is triggered.
Expected result: The getSpotifyToken query returns a valid access_token on page load. The Spotify API resource is configured to automatically include this token in Authorization headers for all subsequent queries.
Build queries to search tracks and retrieve audio features
With authentication working, create the data queries. In the Code panel, create a query named searchTracks. Resource = Spotify API, method = GET, path = /search. Add URL parameters: q = {{ searchInput.value }}, type = track, limit = 20, market = US. Set Trigger to run automatically when searchInput.value changes (and debounce by 400ms to avoid excessive API calls on each keystroke). This query powers a real-time track search feature. Create a second query named getAudioFeatures. Resource = Spotify API, method = GET, path = /audio-features. Add URL parameter: ids = {{ searchResultsTable.selectedRows.map(r => r.id).join(',') }}. This retrieves audio analysis data for all selected rows in the search results table simultaneously. The endpoint accepts up to 100 comma-separated track IDs. Set Trigger to run automatically when searchResultsTable.selectedRows changes. Create a third query named getArtistTopTracks. Resource = Spotify API, method = GET, path = /artists/{{ artistIdInput.value }}/top-tracks. Add parameter: market = US. This retrieves the top 10 tracks for any artist ID entered in a Text Input component. Create a fourth query named getPlaylist. Resource = Spotify API, method = GET, path = /playlists/{{ playlistIdInput.value }}. This retrieves full playlist metadata including all track listings with their audio features summary.
1// JavaScript transformer to extract and format track data from search results2// Attach to searchTracks query (Advanced → Transform data)3const results = data;4if (!results || !results.tracks || !results.tracks.items) return [];56return results.tracks.items.map(track => ({7 id: track.id,8 uri: track.uri,9 title: track.name,10 artist: track.artists.map(a => a.name).join(', '),11 album: track.album.name,12 releaseDate: track.album.release_date,13 popularity: track.popularity,14 durationMs: track.duration_ms,15 duration: Math.floor(track.duration_ms / 60000) + ':' +16 String(Math.floor((track.duration_ms % 60000) / 1000)).padStart(2, '0'),17 previewUrl: track.preview_url || '',18 spotifyUrl: track.external_urls.spotify19}));Pro tip: Spotify track IDs (22-character Base62 strings) are more stable than names for referencing specific tracks. Store track IDs in your database rather than titles to avoid matching issues when the same song appears under multiple titles.
Expected result: The searchTracks query returns formatted track results as users type in the search input. getAudioFeatures returns energy, danceability, valence, and other metrics for selected tracks.
Build the music analytics dashboard interface
Assemble the dashboard layout. At the top of the canvas, drag two Text Input components: one for track search labeled 'Search Tracks' and one for Artist ID labeled 'Artist Spotify ID'. Below these, add a Tab component to organize two views: Search Results and Artist Top Tracks. In the Search Results tab, drag a Table component. Set Data source to {{ searchTracks.data }} (with the formatSearchResults transformer applied). Show columns: title, artist, album, releaseDate, popularity (displayed as a progress bar using a column renderer), and duration. Enable multi-row selection so users can select multiple tracks for audio feature analysis. Add an 'Open in Spotify' link column using the spotifyUrl field. Drag a second Table below for Audio Features. Set Data source to {{ getAudioFeatures.data.audio_features }}. Show columns: energy, danceability, valence, tempo, acousticness, instrumentalness, speechiness. Format values as percentages (0.0-1.0 → 0%-100%) using a query transformer, except tempo which is already in BPM. Drag a Chart component alongside the Audio Features table. Set type to Radar (if available in your Retool version) or Bar. Map the chart to show energy, danceability, valence, acousticness, and instrumentalness for the selected tracks side-by-side, enabling visual comparison of multiple tracks' sonic profiles. In the Artist Top Tracks tab, add a similar Table bound to getArtistTopTracks.data. For music labels managing large rosters and needing cross-artist analytics, RapidDev's team can help architect comprehensive Retool dashboards.
1// Transformer to format audio features for display2// Attach to getAudioFeatures query3const features = data;4if (!features || !features.audio_features) return [];56return features.audio_features7 .filter(f => f !== null)8 .map(f => ({9 id: f.id,10 energy: `${(f.energy * 100).toFixed(0)}%`,11 danceability: `${(f.danceability * 100).toFixed(0)}%`,12 valence: `${(f.valence * 100).toFixed(0)}%`,13 acousticness: `${(f.acousticness * 100).toFixed(0)}%`,14 instrumentalness: `${(f.instrumentalness * 100).toFixed(0)}%`,15 speechiness: `${(f.speechiness * 100).toFixed(0)}%`,16 liveness: `${(f.liveness * 100).toFixed(0)}%`,17 tempo: `${f.tempo.toFixed(0)} BPM`,18 key: ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'][f.key] || 'Unknown',19 mode: f.mode === 1 ? 'Major' : 'Minor',20 loudness: `${f.loudness.toFixed(1)} dB`21 }));Pro tip: Spotify's valence feature (0.0-1.0) measures musical positiveness — high valence = happy/euphoric, low valence = sad/angry. Display it as 'Mood' in the table for non-technical music team members who may not know the Spotify terminology.
Expected result: The dashboard displays a track search with live results, a multi-select for audio feature comparison, a formatted audio features table with percentage displays, and a chart visualizing sonic profiles of selected tracks.
Add playlist management and track recommendation queries
Extend the dashboard with playlist management capabilities. Create a query named getUserPlaylists. Resource = Spotify API, method = GET, path = /me/playlists. Note: this endpoint requires a user access token (authorization code flow), not the client credentials token. For dashboards managing a specific service account, pre-authenticate that account and store its refresh token as a Configuration Variable, then use it to obtain user access tokens. Create a query named addTracksToPlaylist. Resource = Spotify API, method = POST, path = /playlists/{{ playlistIdInput.value }}/tracks. Set Body Type to JSON. Body: { 'uris': {{ searchResultsTable.selectedRows.map(r => r.uri) }}, 'position': 0 }. Set Trigger to Manual. This adds selected tracks to a target playlist. Wire this to a Button labeled 'Add to Playlist' with a confirmation dialog. Create a query named getRecommendations. Resource = Spotify API, method = GET, path = /recommendations. Add URL parameters using the audio feature values from selected tracks as seeds: seed_tracks = {{ searchResultsTable.selectedRow.id }}, target_energy = {{ audioFeaturesTable.selectedRow.energy }}, target_danceability = {{ audioFeaturesTable.selectedRow.danceability }}, limit = 20. This queries Spotify's recommendation engine for similar tracks, enabling playlist building from a starting track. Display getRecommendations.data.tracks in a third Table with the same format transformer as the search results. Add an 'Add Recommendations to Playlist' button that triggers addTracksToPlaylist with the recommended track URIs. This creates a full playlist curation workflow entirely within Retool.
1{2 "uris": {{ JSON.stringify(searchResultsTable.selectedRows.map(row => row.uri)) }},3 "position": 04}Pro tip: Spotify's /recommendations endpoint accepts seed_tracks (up to 5 track IDs), seed_artists, seed_genres, and target values for any audio feature. Experiment with min_*, max_*, and target_* parameters to fine-tune recommendations for specific playlist styles.
Expected result: Playlist management queries are configured. Selecting tracks and clicking 'Add to Playlist' adds them to the specified Spotify playlist. The recommendations Table shows tracks similar to the selected seed track.
Common use cases
Build an artist catalog analytics dashboard for a music label
Create a Retool dashboard that queries Spotify for all tracks by a set of managed artists, displays them in a Table with popularity scores, follower counts, and key audio features, and shows a radar chart comparing the audio feature profile (energy, danceability, valence) of the label's catalog versus the current Top 50 playlist.
Build an artist analytics panel that searches Spotify for an artist by name, lists all their top tracks with popularity scores and audio features (energy, danceability, tempo), and shows a bar chart comparing popularity of the last 5 releases.
Copy this prompt to try it in Retool
Playlist curation tool with audio feature analysis
Build a Retool app where playlist editors can paste Spotify track URIs or search by song name, view the audio features of each candidate track, and compare them against the target playlist's average feature profile. Add a 'compatibility score' calculated from the difference between each track's features and the playlist's mean values.
Build a playlist curation tool with a search input for finding tracks by name, a Table showing each result's audio features (energy, danceability, valence, acousticness, tempo), and a compatibility percentage column showing how well each track matches the average feature profile of a selected playlist.
Copy this prompt to try it in Retool
Monitor track performance and editorial playlist placements
Create a Retool monitoring dashboard that tracks daily popularity scores for a set of watched tracks stored in a database, displays a line chart showing popularity trends over time, and flags tracks that have appeared in or dropped out of key editorial playlists by comparing current playlist composition against the previous day's snapshot.
Build a track performance tracker that shows a line chart of popularity score over time for a list of artist tracks stored in a database, with a Table below highlighting tracks whose popularity increased or decreased by more than 5 points in the last 7 days.
Copy this prompt to try it in Retool
Troubleshooting
getSpotifyToken query returns 400 Bad Request with 'invalid_client' error
Cause: The client_id or client_secret values stored in Configuration Variables contain extra spaces or characters, or the values were copied incorrectly from the Spotify Developer Dashboard.
Solution: In Retool Settings → Configuration Variables, click edit on SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET and carefully copy and paste the values again from the Spotify Developer Dashboard. Ensure no leading or trailing whitespace is included. Also verify that your Spotify app is in Active status — a newly created app may take a moment to become active. If the app was deleted and re-created, the client_id changes.
API queries return 403 Forbidden with 'Insufficient client scope' error
Cause: The operation requires user-level OAuth scopes that the client credentials grant does not provide. Client credentials only grant access to public Spotify catalog data, not user-specific data.
Solution: Client credentials (grant_type: client_credentials) can only access public Spotify data: catalog, search, artists, albums, tracks, audio features, and public playlists. For endpoints that require user data (saved tracks, user playlists, listening history, playlist modification), you must implement the authorization code OAuth flow where an actual Spotify user authenticates. Store the resulting refresh token as a Configuration Variable and exchange it for access tokens in Retool.
searchTracks query fires too frequently while typing, hitting Spotify's rate limit
Cause: The query is set to run automatically on input change without a debounce delay, causing a new API request on every keystroke.
Solution: In the searchTracks query settings, find the Debounce field (in the query's Trigger section) and set it to 400-600 milliseconds. This waits until the user pauses typing before sending the request. Spotify's rate limits are not publicly documented precisely but are typically enforced at the application level — exceeding them results in 429 Too Many Requests responses with a Retry-After header.
Audio features query returns null values for some tracks
Cause: Not all Spotify tracks have audio analysis data — tracks may be missing audio features if they are very new, podcast episodes, locally uploaded files, or certain regional releases.
Solution: Filter null values in the transformer before displaying: .filter(f => f !== null). Spotify's API returns null in the audio_features array at the position of tracks that have no audio analysis. The filter ensures the Table only shows tracks with complete feature data, and the count of nulls can be displayed in a Stat component: 'X tracks missing audio features'.
1// In the formatAudioFeatures transformer, filter nulls first:2return features.audio_features3 .filter(f => f !== null)4 .map(f => ({ /* ... mapping code ... */ }));Best practices
- Store Spotify client_id and client_secret in Retool Configuration Variables marked as Secret — never hard-code them in query fields.
- Cache the access token for 3500 seconds using Retool's query caching to avoid redundant token requests — the token is valid for 3600 seconds, so 3500 provides a safe buffer.
- Separate the token acquisition resource (Spotify Auth at accounts.spotify.com) from the data resource (Spotify API at api.spotify.com/v1) for cleaner resource organization.
- Use the client credentials grant for all public catalog operations (search, audio features, artist data) — reserve user OAuth for user-specific features to minimize complexity.
- Build audio feature displays with percentage formatting (multiply 0.0-1.0 values by 100) and use human-readable labels like 'Mood' instead of 'valence' for non-technical team members.
- For large-scale catalog analysis, batch audio feature requests using the /audio-features endpoint with up to 100 comma-separated track IDs per request rather than making individual calls.
- Store popularity score snapshots in a database via Retool Workflows to build trend charts — the Spotify API only returns the current popularity score, not historical data.
Alternatives
Choose SoundCloud if your focus is independent artists and unsigned music — SoundCloud's API covers the independent music ecosystem that Spotify Analytics often underrepresents.
Choose YouTube API if your music strategy includes music video analytics and comment management, since YouTube provides detailed video performance data not available through Spotify.
Choose Vimeo if you need private professional video hosting for music videos with advanced privacy controls rather than public streaming analytics.
Frequently asked questions
Does the Spotify API require users to log in, or can I access public data without user authentication?
Public Spotify catalog data — track search, artist profiles, album information, audio features, featured playlists — is accessible with just the client credentials grant (client_id + client_secret → access_token), with no user login required. User-specific data such as saved tracks, personalized recommendations, user playlists, and listening history requires the authorization code flow where an actual Spotify user authenticates your app.
What are Spotify's API rate limits for Retool dashboards?
Spotify does not publish precise rate limits publicly. In practice, the Web API enforces limits at the application level and returns 429 Too Many Requests with a Retry-After header when exceeded. For internal Retool dashboards with moderate query volume, rate limits are rarely an issue. For high-volume dashboards querying hundreds of tracks, use batch endpoints like /audio-features (up to 100 IDs per call) and enable query caching in Retool to minimize redundant requests.
Can I use Retool to add tracks to Spotify playlists, not just read data?
Yes, but this requires a user access token with the playlist-modify-public or playlist-modify-private scope — client credentials tokens cannot modify playlists. You need to implement the authorization code OAuth flow to obtain a user token for the Spotify account that owns the playlist. Once you have a valid user access token stored as a Configuration Variable, POST requests to /playlists/{playlist_id}/tracks from Retool will add tracks to that playlist.
Can Retool access Spotify for Artists data (streams, saves, listener demographics)?
No. Spotify for Artists analytics data (monthly streams, saves, playlist adds, listener demographics) is not available through the public Spotify Web API. It is only accessible through the Spotify for Artists web interface or through Spotify's Distribution and Catalog APIs, which require a separate partnership agreement. The public Web API provides popularity scores (0-100 scale) and follower counts, which are the closest approximation to reach data available programmatically.
How do I find a Spotify artist's ID to use in API queries?
The simplest method is to search by artist name using the /search endpoint with type=artist, which returns artist objects including their Spotify ID. Alternatively, open the artist's page in the Spotify web player or desktop app, click the three-dot menu, select Share, and copy the Spotify URI (format: spotify:artist:XXXXXXXX). The alphanumeric string after 'artist:' is the artist ID. You can also extract it from the artist's Spotify URL in a browser.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation