Search code examples
pythonspotifyspotipy

Create a Spotify playlist using spotipy


I am trying to create a playlist using the spotipy library. I followed the instructions on their website alongside this solved question Spotipy invalid username? . When running the code provided in this question (fitted to my Spotify developer account) everything works fine. However when trying another scope corresponding to my object of creating a playlist I get the same username error as mentioned in the linked question:

Traceback (most recent call last):

  File "C:\Users\d92167\Spotify\Create_Favorites.py", line 23, in <module>
    sp.user_playlist_create(cred.user_name, name=playlist_name)

  File "C:\Users\d92167\Anaconda3\lib\site-packages\spotipy\client.py", line 784, in user_playlist_create
    return self._post("users/%s/playlists" % (user,), payload=data)

  File "C:\Users\d92167\Anaconda3\lib\site-packages\spotipy\client.py", line 302, in _post
    return self._internal_call("POST", url, payload, kwargs)

  File "C:\Users\d92167\Anaconda3\lib\site-packages\spotipy\client.py", line 267, in _internal_call
    raise SpotifyException(

SpotifyException: https://api.spotify.com/v1/users/*My Username*/playlists:
 Invalid username

My code:

import spotipy
import cred 

scope = 'playlist-modify-public'
token = spotipy.util.prompt_for_user_token(cred.user_name,scope,client_id=cred.client_id,client_secret=cred.client_secret,redirect_uri=cred.redirect_url) 
sp = spotipy.Spotify(auth=token)


playlist_name = 'Test'  
sp.user_playlist_create(cred.user_name, name=playlist_name)

I am using Python 3.8 and Spotipy version 2.20.0


Solution

  • I have 2 possible solutions:
    1: You forgot to type user=

    sp.user_playlist_create(user=cred.user_name, name=playlist_name)
    

    2: Maybe the user_name in the cred file is wrong. You can get the username with this code:

    sp_user = sp.current_user()
    user_name = sp_user['uri'].split(":")[2]