Master LLMs with our FREE course in collaboration with Activeloop & Intel Disruptor Initiative. Join now!


Unlock Your Unique Playlist: Personalized Song Recommendations Using Spotify API
Data Science   Latest   Machine Learning

Unlock Your Unique Playlist: Personalized Song Recommendations Using Spotify API

Last Updated on February 13, 2024 by Editorial Team

Author(s): Sarvesh Talele

Originally published on Towards AI.

Image Created by AI

Have you ever been frustrated by the recommendations because you were so focused on choosing the perfect playlist? In that case, you are not alone. Looking through the vast array of songs and playlists on the many music streaming services available today to find what resonates with you could be frightening. But fear not — thanks to machine learning, we can now discover the key to creating a personalized playlist that appeals to your unique musical taste. To be more precise, we’re going to develop a customized hybrid and content-based recommendation system. By scraping the whole Spotify database and selecting the songs that best suit our taste in music, this machine-learning model will make song recommendations based on our playlist using Spotify API.

Access the Complete Code below given link-

GitHub – Wyverical/Music-Recommendation-System-using-Spotify-API

Contribute to Wyverical/Music-Recommendation-System-using-Spotify-API development by creating an account on GitHub.

Setting the stage

It would be more interesting to explore the recommendation system’s outcomes rather than provide a step-by-step explanation of the code. Though the blog would simply go over some basic algorithmic theory and code snippets, let’s analyze our model using the data. We’ll explore the realm of music recommendation systems, where computers create personalized playlists based on your listening tastes, habits, and even the qualities of specific songs. We’ll look at how to use machine learning methods and the Spotify API to make customized music recommendations based on your favorite songs.

Demo Video:

Video Created by Author

Getting Started

We'll need to start our voyage by browsing the enormous selection of music on Spotify. We can access comprehensive data on millions of songs, such as their audio characteristics, popularity rankings, release dates, and more, with the use of the Spotify API. With the use of sophisticated algorithms and this abundance of data, we can find hidden links and patterns in the song content to provide insightful recommendations. The Python libraries listed below are the ones that we would need to install in order to create our ideal playlist.

import requests
import base64
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from datetime import datetime
from sklearn.metrics.pairwise import cosine_similarity
import ipywidgets as widgets
from IPython.display import display, clear_output
import spotipy
from spotipy.oauth2 import SpotifyOAuth

Exploring Your Playlist

Let’s continue exploring a curated playlist on Spotify and collecting crucial insights about the songs it contains. Using the Spotify API, we can obtain information about each song in the playlist, such as the title of the track, the artist, the album, the popularity rating, the release date, and more audio characteristics. With this knowledge in hand, we may go deeper into the musical landscape and uncover hidden gems. The code that follows includes your unique playlist ID. For example, if your playlist URL is, then your playlist ID is 0zQTiQxLOgnsLg7drurLig.

playlist_id = '0zQTiQxLOgnsLg7drurLig'
song_df = playlist_data(playlist_id, access_token)

Analyzing the Data

It’s time to get in and truly get our hands cluttered with some analysis now that we’ve gathered all the data from our playlist! Assume that we are delving deeply into the world of music while donning our detective caps. Let’s start by looking at the fascinating correlation between a song’s duration and popularity. To display this, we’ll use Line plot, which are similar to putting Line on a map to identify potentially intriguing pathways. Next, we’ll go further into the tracks, analyzing their danceability, intensity, and acoustic quality. It’s similar to cutting through the layers of a musical orange to reveal the distinct tastes and sensations that are concealed in every track. So fasten your seatbelts and get ready for a musical journey like no other.

import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.scatter(data['Popularity'], data['Duration (ms)'], s=50, alpha=0.8, color='skyblue', edgecolors='k')
plt.title('Popularity vs Duration', fontsize=16)
plt.xlabel('Popularity', fontsize=14)
plt.ylabel('Duration (ms)', fontsize=14)
plt.grid(True, linestyle='--', alpha=0.6)
Image created by Author

Personalized Recommendations

Now comes the exciting part—generating personalized song recommendations based on your favorite tracks. We can find songs that not only suit musical preferences but also have resonance with the current trends and popularity scores by combining popularity-based weighting and content-based filtering, resulting in a hybrid recommendation system.

import ipywidgets as widgets
from IPython.display import display, clear_output
track_names = song_df['Track Name'].unique().tolist()
track_names.insert(0, "Select song from dropdown")
def update_recommendations(change):
input_song =
recommendations = hybrid_recommendations(input_song, num_of_recom=5)
print(f"Hybrid recommended songs for '{input_song}':")
dropdown = widgets.Dropdown(
description='Track Name:',
dropdown.observe(update_recommendations, names='value')


In conclusion, the process of making your own playlist is fascinating and exciting. Through the use of data analytics and machine learning, we may access a vast music library customized to suit our unique interests and inclinations. Thus, instead of settling for pre-made playlists, why not create your own musical journey? The soundtrack to your life may be found with only a click, thanks to our unique suggestion system. Enjoy your audio!

Reference Links

  1. Cosine Similarity :
  2. Spotify API Documentation:

Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.

Published via Towards AI

Feedback ↓