Skip to content

Instantly share code, notes, and snippets.

@AmolMavuduru
Created January 21, 2021 18:02
Show Gist options
  • Save AmolMavuduru/5507896df1d3befa3596cc92a6850a85 to your computer and use it in GitHub Desktop.
Save AmolMavuduru/5507896df1d3befa3596cc92a6850a85 to your computer and use it in GitHub Desktop.
Function for finding Spotify songs. Sample code for my Medium article: "How to build an amazing music recommendation algorithm."
from spotipy.oauth2 import SpotifyClientCredentials
from collections import defaultdict
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=os.environ["SPOTIFY_CLIENT_ID"],
client_secret=os.environ["SPOTIFY_CLIENT_SECRET"]))
def find_song(name, year):
"""
This function returns a dataframe with data for a song given the name and release year.
The function uses Spotipy to fetch audio features and metadata for the specified song.
"""
song_data = defaultdict()
results = sp.search(q= 'track: {} year: {}'.format(name,
year), limit=1)
if results['tracks']['items'] == []:
return None
results = results['tracks']['items'][0]
track_id = results['id']
audio_features = sp.audio_features(track_id)[0]
song_data['name'] = [name]
song_data['year'] = [year]
song_data['explicit'] = [int(results['explicit'])]
song_data['duration_ms'] = [results['duration_ms']]
song_data['popularity'] = [results['popularity']]
for key, value in audio_features.items():
song_data[key] = value
return pd.DataFrame(song_data)
@balorboeshreyansh
Copy link

its saying error in SPOTIFY_CLIENT_ID

@balorboeshreyansh
Copy link

even after i gave my client id and secret its showing error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment