有人知道为什么我使用下面的代码从 Spotify 播放列表中删除曲目时收到 403 错误吗?

问题描述 投票:0回答:1

注意:client_id、client_secret、username 和 playlist_id 声明已从下面的代码中删除。

# Number of songs to delete from the playlist
num_songs_to_delete = 5  # Change this to the desired number

# Encode client_id and client_secret for authentication
client_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 flow
token_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 token
playlist_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 order
tracks = playlist_data['items']
sorted_tracks = sorted(tracks, key=lambda x: x['added_at'], reverse=True)


# Extract track URIs
tracks_uris = [track['track']['uri'] for track in sorted_tracks]

# Delete the specified number of tracks from the playlist
tracks_to_delete = tracks_uris[:min(num_songs_to_delete, len(tracks_uris))]

# Delete tracks
delete_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.")

我尝试使用 requests 和 Spotipy 库连接到 Spotify Web API,以创建一个程序来从指定的播放列表中删除歌曲,但是,在运行代码时出现 403 错误。 client_id 和 client_secret 与开发人员门户应用程序中的内容匹配。我已经进行了研究,但无法确定根本原因。该应用程序也在 Spotify 开发者门户中正确创建。

非常感谢任何帮助!

python https spotify http-status-code-403
1个回答
0
投票

Two reasons

#1 客户端凭据流程无法删除播放列表

您已通过

"grant_type": "client_credentials"
获取访问令牌

您应该使用授权代码流程

如果您查看 Spotify API 文档 在删除播放列表项目中,

https://developer.spotify.com/documentation/web-api/reference/remove-tracks-playlist

你可以看到

Authorization scopes
。这意味着您的访问令牌已通过
Authorization Code Flow

这意味着您必须运行本地服务器来重定向(回调)URL。 spotipy 为您轻松提供。

#2 [范围]很重要

如果您查看 Spotify 范围文档

https://developer.spotify.com/documentation/web-api/concepts/scopes

删除播放列表曲目需要这两个范围

playlist-modify-public
playlist-modify-private

我修改了你的代码并添加了

spotipy
代码。

另存为

demo.py

import requests
import json
import spotipy
from spotipy.oauth2 import SpotifyOAuth

client_id = '<your client id>'
client_secret = '<your client secret>'
redirect_uri = '<your redirect uri>' # get from developer dash board
username = '<your user name>'        # get from user profile
SCOPEs = ['playlist-modify-private', 'playlist-modify-public']

playlist_id = '<your user name>'     # You want to delete from this playlist ID
# Number of songs to delete from the playlist
num_songs_to_delete = 5  # Change this to the desired number

auth_manager = SpotifyOAuth(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=SCOPEs, username=username)
sp = spotipy.Spotify(auth_manager=auth_manager)
token_info = sp.auth_manager.get_cached_token()
access_token = token_info['access_token']

# Get playlist tracks using the access token
playlist_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 order
tracks = playlist_data['items']
sorted_tracks = sorted(tracks, key=lambda x: x['added_at'], reverse=True)


# Extract track URIs
tracks_uris = [track['track']['uri'] for track in sorted_tracks]

# Delete the specified number of tracks from the playlist
tracks_to_delete = tracks_uris[:min(num_songs_to_delete, len(tracks_uris))]

# Delete tracks
delete_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.")

如何获得

client_id
client_secret
redirect_uri

通过浏览器打开网址

https://developer.spotify.com/dashboard

如何获取用户名

通过浏览器打开网址

https://open.spotify.com/

安装依赖项

pip install requests
pip install spotipy

运行之前

检查播放列表中的歌曲数量 跑步前9首歌

运行它

python demo.py

运行后

由于 5 首歌曲被删除,还剩 4 首歌曲

向上翘起

我只是演示如何从播放列表中删除歌曲,但我使用混合 API 调用 请求 API 和 Spotipy API,但如果您使用

Authorization Code Flow
,我建议仅使用 Spotipy API。

© www.soinside.com 2019 - 2024. All rights reserved.