Note: client_id, client_secret, username, and playlist_id declarations have been removed from the code below.
# Number of songs to delete from the playlistnum_songs_to_delete = 5 # Change this to the desired number# Encode client_id and client_secret for authenticationclient_creds = f"{client_id}:{client_secret}"#client_creds_b64 = base64.b64encode(client_creds.encode()).decode()client_creds_b64 = base64.b64encode('{}:{}'.format(client_id, client_secret).encode())# Get access token using client credentials flowtoken_url = "https://accounts.spotify.com/api/token"token_data = {"grant_type": "client_credentials"}#token_headers = {# "Authorization": f"Basic {client_creds_b64}"#}token_headers = {"Authorization": "Basic {}".format(client_creds_b64.decode())}token_response = requests.post(token_url, data=token_data, headers=token_headers)token_response_data = token_response.json()access_token = token_response_data['access_token']# Get playlist tracks using the access tokenplaylist_url = f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks"playlist_headers = {"Authorization": f"Bearer {access_token}"}playlist_response = requests.get(playlist_url, headers=playlist_headers)playlist_data = playlist_response.json()# Sort tracks by their added_at timestamp in descending ordertracks = playlist_data['items']sorted_tracks = sorted(tracks, key=lambda x: x['added_at'], reverse=True)# Extract track URIstracks_uris = [track['track']['uri'] for track in sorted_tracks]# Delete the specified number of tracks from the playlisttracks_to_delete = tracks_uris[:min(num_songs_to_delete, len(tracks_uris))]# Delete tracksdelete_url = f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks"delete_data = {"tracks": [{"uri": uri} for uri in tracks_to_delete]}delete_response = requests.delete(delete_url, headers=playlist_headers, data=json.dumps(delete_data))print(delete_response)if delete_response.status_code == 200: print(f"{num_songs_to_delete} songs deleted from the playlist.")else: print("Failed to delete songs from the playlist.")
I've tried using both requests and spotipy libraries to connect to the Spotify Web API to create a program to remove songs from a specified playlist, however, I'm getting 403s when running the code. The client_id and client_secret match whats in the developer portal app. I've done research and can't determine the root cause. The app is created properly in the Spotify Developer Portal as well.
Any help is much appreciated!