2

I want to experiment with the Spotify API using the Spotipy python package.

So to start, in my Spotify Developer app, I have set the redirect_uri to https://example.com/callback/

This is the code I am trying to run on a Google Colab notebook

import pandas as pd
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

spotify_details = {
    'client_id' : '<hidden>',
    'client_secret':'<hidden>',
    'redirect_uri':'https://example.com/callback/'}

scope = "user-library-read user-follow-read user-top-read playlist-read-private" 

sp = spotipy.Spotify(
        auth_manager=spotipy.SpotifyOAuth(
          client_id=spotify_details['client_id'],
          client_secret=spotify_details['client_secret'],
          redirect_uri=spotify_details['redirect_uri'],    
          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'])

This is what I see as the output:

enter image description here

But my browser does not redirect me to any URL for me to receive an auth token

What am I doing wrong?

2 Answers2

5

Colab is a browserless environment, so as suggested in the FAQ you should add the parameter

open_browser=False

when you instantiate your spotipy.SpotifyOAuth object:

sp = spotipy.Spotify(
        auth_manager=spotipy.SpotifyOAuth(
          client_id=spotify_details['client_id'],
          client_secret=spotify_details['client_secret'],
          redirect_uri=spotify_details['redirect_uri'],    
          scope=scope, open_browser=False))

In this way, the notebook will print out the URL that you can open manually: enter image description here

rob_med
  • 496
  • 3
  • 7
0

In case any one is wondering what is the URL we need to follow is

https://accounts.spotify.com/authorize?client_id=<client_id>&redirect_uri=<encoded_redirect_uri>&response_type=code

once the request is complete it will be redirected to (if your redirect_uri is https://example.com/callback/)

https://example.com/callback/?code=<code_will_be_present_here>

Use the above url in the collab input box

Puneeth Rai
  • 1,163
  • 10
  • 11