Search code examples
pythonjupyter-notebookgoogle-colaboratoryspotifyspotipy

Google Colab - Spotipy not redirecting me to the specified redirect_uri


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?


Solution

  • 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