i am trying to add some tracks to a spotify playlist of mine. But I always get the error Error: 401 Client Error: Unauthorized for url. Can someone help? Thank you 🙂
def get_auth_header(token😞
return {"Authorization": "Bearer " + token}
def get_token():
auth_string = CLIENT_ID + ":" + CLIENT_SECRET
auth_bytes = auth_string.encode("utf-8")
auth_base64 = str(base64.b64encode(auth_bytes), "utf-8")
headers = {
"Authorization": "Basic " + auth_base64,
"Content-Type": "application/x-www-form-urlencoded"
}
data = {"grant_type": "client_credentials"}
result = post(url, headers=headers, data= data)
json_result = json.loads(result.content)
token = json_result["access_token"]
return token
def add_tracks_to_playlist(access_token, playlist_id, uris, position=None😞
"""
Add tracks to a Spotify playlist.
Parameters:
access_token (str): The access token for Spotify API.
playlist_id (str): The Spotify ID of the playlist.
uris (list of str): A list of Spotify URIs to add.
position (int, optional): The position to insert the items. If omitted, the items will be appended to the playlist.
Returns:
response (dict): The response from Spotify API.
"""
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
data = {
"uris": uris
}
if position is not None:
data["position"] = position
response = requests.post(url, headers=headers, json=data)
if response.status_code == 201:
return response.json()
else:
response.raise_for_status()
if __name__ == "__main__":
# Replace these values with your own
ACCESS_TOKEN = get_token()
PLAYLIST_ID = "ID"
URIS = [
"spotify:track:4iV5W9uYEdYUVa79Axb7Rh",
"spotify:track:1301WleyT98MSxVHPZCA6M",
"spotify:episode:512ojhOuo1ktJprKbVcKyQ"
]
POSITION = 0 # Optional
try:
result = add_tracks_to_playlist(ACCESS_TOKEN, PLAYLIST_ID, URIS, POSITION)
print("Tracks added successfully!")
print("Snapshot ID:", result["snapshot_id"])
except requests.exceptions.HTTPError as err:
print(f"Error: {err}")