Reputation: 1
I've been having trouble adding multiple songs to my playlist on spotify. Here is what part of my code looks like so far:
def add_selected_songs(songs, playlist_id):
ACCESS_TOKEN = input('Provide Access Token: ')
request_data = json.dumps(songs)
URL = f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks'
response = requests.post(
URL,
data=request_data,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {ACCESS_TOKEN}"
})
response_json = response.json()
return response_json
The 'songs' variable is an array of song uris I have added from another playlist. They print out in the following format:
['spotify:track:75s1b4uRCk6UPOPBLNdDIA', 'spotify:track:3hqJdqziOPbu422kXaOyII', 'spotify:track:6rdKHwxWa9aqWyoGf1r20v', 'spotify:track:6xQdHOX1Tq3IrKsQdLs0nc', 'spotify:track:66g4mn8jSks0Hu1zEcc81G']
I think something might be wrong with the uris or how i did the requests.post() jargon that I still don't understand fully. I don't really know a lot about json, and what little I understand of the spotify api is from youtube videos. I am able to do most things to my playlist like retrieve playlist information like songs and such, and I can add each song individually, but I just can't add multiple songs in one request. If someone could please help me figure out what I am doing wrong that would be much appreciated!
Edit: Here's what I changed to my code thanks to you guys and your helpful feedback!! Thanks everyone!
def add_selected_songs(songs, playlist_id):
ACCESS_TOKEN = input(Provide Access Token: ')
songList = '%2C'.join(songs)
while(songList.find(':') != -1):
songList = songList.replace(':','%3A')
URL = BASE_URL + f'/playlists/{playlist_id}/tracks?uris={songList}' #forgot to even add the uris earlier too lol
response = requests.post(
URL,
headers={
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {ACCESS_TOKEN}"
})
response_json = response.json()
return response_json
Upvotes: 0
Views: 2256
Reputation: 115
Spotify Developers page is helpful in a way that will show you how exactly should the request look like: https://developer.spotify.com/console/post-playlist-tracks/
If you try to fill in at least two song ID's, e.g.:
spotify:track:3hqJdqziOPbu422kXaOyII,spotify:track:3hqJdqziOPbu422kXaOyII
You will notice the POST request on right side:
"https://api.spotify.com/v1/playlists/playlist_id/tracks?uris=spotify%3Atrack%3A3hqJdqziOPbu422kXaOyII%2Cspotify%3Atrack%3A3hqJdqziOPbu422kXaOyII"
Request does not accept special characters, however ASCII keycodes, so you should join the song IDs by %2C
and replace the : with %3A
.
Upvotes: 1