Hey guys, I’m stuck trying to add songs to my Spotify playlist using their API. I’m pretty new to this, so I’d really appreciate some help!
Here’s the Python code I’m using:
import requests
import json
user_info = 'my_user_id'
playlist_info = 'my_playlist_id'
endpoint = f'https://api.spotify.com/v1/playlists/{playlist_info}/tracks'
auth_headers = {
'Authorization': 'Bearer my_secret_token',
'Content-Type': 'application/json',
}
track_data = {
'uris': ['spotify:track:1234567890abcdef'],
}
result = requests.post(endpoint, headers=auth_headers, data=json.dumps(track_data))
print(result.text)
When I run this, I get an error:
requests.exceptions.InvalidSchema: No connection adapters were found for 'https://api.spotify.com/v1/playlists/my_playlist_id/tracks'
I’ve checked my auth token and it seems to work fine for other things like creating playlists. Any ideas what I’m doing wrong here? Thanks in advance for any help!
yo sarahj, had similar troubles before. make sure ur playlist_info is the actual id, not ‘my_playlist_id’. Also, try using requests.post(endpoint, headers=auth_headers, json=track_data) instead of json.dumps(). that fixed it for me. good luck!
I’ve run into this problem before, and it can be frustrating. One thing that helped me was using the ‘requests_oauthlib’ library instead of just ‘requests’. It handles a lot of the OAuth stuff automatically, which can be a real headache otherwise.
Here’s a snippet that worked for me:
from requests_oauthlib import OAuth2Session
spotify = OAuth2Session(client_id, token=token)
response = spotify.post(f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks', json={'uris': track_uris})
Make sure you’ve got the right scopes too - you need ‘playlist-modify-public’ or ‘playlist-modify-private’ depending on your playlist settings. And double-check that your playlist ID is correct - I once spent hours debugging only to realize I’d copied the wrong ID!
hey sarahj, seems your url might be off. check that ‘my_playlist_id’ is replaced with the actual id and that your auth token and scopes are correct. also consider using requests’ json param instead of json.dumps(). hope it helps!
I encountered a similar issue when I first started working with the Spotify API. The error you’re getting suggests there might be a problem with the URL or how it’s being interpreted. Have you tried using the requests library’s built-in URL encoding? Something like this might work better:
from urllib.parse import urljoin
base_url = ‘https://api.spotify.com/v1/’
endpoint = urljoin(base_url, f’playlists/{playlist_info}/tracks’)
This approach can help ensure your URL is properly formatted. Also, double-check that your playlist_info variable contains a valid playlist ID. If the issue persists, you might want to verify your API permissions and token scopes.