Search code examples
pythondjangooauth-2.0spotifyspotipy

Spotify authentication using Spotipy not showing and my redirect uri is refusing to connect?


Using Spotipy(A spotify module to access data using the Spotify API) and Django, I am trying to use the Authorization Code Flow for authentication but I keep running into an error when I use the login route.

The URL http://localhost/?code=AQDaVeJPteLHVgQG7P41mX5XMmoriJtbpx7vjRYdTXBR64Fal2IMHXQfnSoEdrYrZnYwM-xjyyr_ME_t_gsbqR6-72A4sRBQZ1aaoJd7Xcr2rqT_9aF_kDND0XmZZMhRQzN4oAujH6Uawl9d-tEJmnE_Q-yISGAGTuIHlONwbPEretR9XdPXQg with an error localhost refused to connect comes up after I use the login route

urls.py

urlpatterns = [
path("login/" , views.login , name = "login" ),
path("home/", views.home, name= "home"),
path("callback/" , views.callback , name="callback")
]

views.py

#get_authorize_url()method returns a Spotify API endpoint https://accounts.spotify.com/authorize?client_id=83654ff787fc48c7a38cc7976238628a&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2F&scope=user-library-read

def login(request):
   authorize_url = oauth.get_authorize_url()
   return redirect(authorize_url)

get_access_token() returns the access token

def callback(request):
    code = request.GET.get("code")
    if code is not None:
        oauth.get_access_token(code)
        return redirect(reverse("home"))
    else:
        return redirect(reverse("login"))


def home(request):
     return HttpResponse("Welcome")

Solution

  • I realized http://localhost/ was the bug. Typed that into a browser and it threw the same error. Changed the redirect_uri to http://127.0.0.1:8000/spotify/callback/so I am redirected back to my server and my callback route.