Spotify isn’t just a music platform—it’s a treasure chest of data. From tempo and key to genre and mood, Spotify’s API gives developers a way to dive deep into what makes your favorite songs tick. In this guide, we’re going to roll up our sleeves and build something practical: a Spotify Playlist Analyzer that pulls your playlists, crunches the data, and visualizes it in a friendly dashboard.
And yes—this is all legal because we’ll be using Spotify’s official API with your own account authorization. No scraping, no shady downloads, just pure coding fun.
Why Build a Spotify Playlist Analyzer?
There’s a certain magic in knowing why you gravitate toward certain songs. Is your “Focus” playlist mostly acoustic tracks in a minor key? Does your workout mix tend toward higher BPMs and major keys? With this project, you’ll:
- Learn OAuth 2.0 authentication in a real-world app.
- Get hands-on with REST APIs.
- Practice data visualization with chart libraries like Chart.js or Recharts.
- Have a working project to showcase in your portfolio.
Prerequisites
Before we get started, make sure you have:
- Node.js and npm installed.
- A Spotify Developer Account (free—just log in with your normal Spotify credentials).
- Basic knowledge of JavaScript and React.
- A text editor like VS Code.
Step 1: Setting Up Your Spotify Developer App
- Head to the Spotify Developer Dashboard.
- Click "Create an App", give it a name like Playlist Analyzer, and note your Client ID and Client Secret.
- Set your Redirect URI to something like http://localhost:3000/callback—we’ll need this for OAuth.
Step 2: Building the Backend with Node.js + Express
Our backend will handle:
- Redirecting users to Spotify’s login.
- Exchanging the authorization code for an access token.
- Fetching playlist data from Spotify.
const express = require('express');
const request = require('request');
const cors = require('cors');
require('dotenv').config();
const app = express();
app.use(cors());
const redirect_uri = 'http://localhost:3000/callback';
const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET;
// Step 1: Redirect to Spotify login
app.get('/login', (req, res) => {
const scope = 'playlist-read-private user-library-read';
res.redirect(
'https://accounts.spotify.com/authorize?' +
new URLSearchParams({
response_type: 'code',
client_id,
scope,
redirect_uri
}).toString()
);
});
// Step 2: Handle callback & exchange code for token
app.get('/callback', (req, res) => {
const code = req.query.code || null;
const authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri,
grant_type: 'authorization_code'
},
headers: {
Authorization:
'Basic ' + Buffer.from(client_id + ':' + client_secret).toString('base64')
},
json: true
};
request.post(authOptions, (error, response, body) => {
const access_token = body.access_token;
res.redirect(`http://localhost:3000?access_token=${access_token}`);
});
});
app.listen(3001, () => console.log('Server running on port 3001'));
Step 3: Frontend in React — Fetching & Displaying Data
Once the user logs in, we’ll use the access token to get their Spotify APK playlists and analyze track attributes.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Bar } from 'react-chartjs-2';
export default function App() {
const [playlists, setPlaylists] = useState([]);
const [chartData, setChartData] = useState({});
const token = new URLSearchParams(window.location.search).get('access_token');
useEffect(() => {
if (token) {
axios.get('https://api.spotify.com/v1/me/playlists', {
headers: { Authorization: `Bearer ${token}` }
}).then(res => setPlaylists(res.data.items));
}
}, [token]);
const analyzePlaylist = async (id) => {
const tracks = await axios.get(`https://api.spotify.com/v1/playlists/${id}/tracks`, {
headers: { Authorization: `Bearer ${token}` }
});
const trackIds = tracks.data.items.map(item => item.track.id).join(',');
const audioFeatures = await axios.get(`https://api.spotify.com/v1/audio-features?ids=${trackIds}`, {
headers: { Authorization: `Bearer ${token}` }
});
const bpmData = audioFeatures.data.audio_features.map(f => f.tempo);
setChartData({
labels: bpmData.map((_, i) => `Track ${i+1}`),
datasets: [{ label: 'BPM', data: bpmData, backgroundColor: 'rgba(30,215,96,0.5)' }]
});
};
return (
<div className="container">
<h1>Spotify Playlist Analyzer</h1>
{playlists.map(p => (
<div key={p.id}>
<button onClick={() => analyzePlaylist(p.id)}>{p.name}</button>
</div>
))}
{chartData.labels && <Bar data={chartData} />}
</div>
);
}
Step 4: Visualizing the Data
We’re using Chart.js here to plot BPMs, but you could expand the analysis to:
- Energy levels
- Danceability
- Key distribution
- Popularity scores
Step 5: Ideas for Expansion
Once you have the basics working, you can:
- Build a “Mood Breakdown” pie chart showing how many songs are upbeat vs. mellow.
- Compare playlists to see how your tastes change.
- Export your playlist stats as a PDF report.
- Add authentication persistence so users don’t have to log in each time.
Why This Project Works So Well for Learning
This isn’t a “toy” project. You’re touching multiple real-world skills:
- OAuth 2.0 authentication
- Handling API requests and responses
- State management in React
- Backend/frontend integration
- Data visualization
And the best part? You can show this off in a portfolio, because it’s useful, attractive, and personalized.
Wrapping It Up
By the end of this project, you’ll not only understand how Spotify’s API works—you’ll also have a solid grasp on connecting APIs to a frontend interface, processing JSON data, and turning that into something visually meaningful.
Whether you’re building this for your own curiosity, as a resume project, or just because you love music and code, this kind of app is a fantastic way to learn while creating something you’ll actually use.
Top comments (0)