使用Spotify get_users_playlists API返回空播放列表的问题排查
问题描述
我创建了一个包含单首曲目的测试播放列表,尝试通过Spotify API获取自己的播放列表。返回的JSON包含头部信息,但播放列表数组为空且无报错。
已尝试的操作:
- 使用REST API(Python脚本、curl)及Spotipy,结果一致
- 采用
client_credentials授权流,测试过公开和私有播放列表 - 调用私有播放列表时在REST API头中设置了
scope,但Spotipy参数无scope - 怀疑该授权流不支持私有播放列表,但通过播放列表ID可正常获取播放列表
- Spotipy文档示例显示
client_credentials流应支持公开播放列表
测试代码:
import os from config import CLIENT_ID import spotipy from spotipy.oauth2 import SpotifyClientCredentials def main(): sp = get_spotipy_client() playlists = sp.user_playlists("<my user name>") for playlist in playlists['items']: print(playlist['name']) def get_spotipy_client(): client_secret = os.getenv("CLIENT_SECRET") if not isinstance(CLIENT_ID, str) or not CLIENT_ID: raise ValueError("CLIENT_ID must be a non-empty string.") if not isinstance(client_secret, str) or not client_secret: raise ValueError("CLIENT_SECRET must be a non-empty string.") ccm = SpotifyClientCredentials(CLIENT_ID, client_secret) sp = spotipy.Spotify(client_credentials_manager=ccm) return sp if __name__ == "__main__": main()
问题分析与解决方案
核心原因
client_credentials授权流的本质限制
该授权流属于应用级授权,没有用户上下文,只能访问Spotify公开的、与应用直接关联的资源,无法获取用户个人的播放列表(无论公开还是私有)。user_playlists接口需要用户上下文才能返回对应用户的播放列表,因此用该流调用会返回空数组。scope参数无效client_credentials流不需要用户授权,因此即使在请求中设置scope也不会生效。只有用户级授权流(如Authorization Code)才需要通过scope申请访问用户数据的权限。通过ID能获取播放列表的原因
playlist接口仅需要播放列表的访问权限,只要播放列表是公开的,或你拥有该列表的私有访问权限,就能通过ID直接获取,与授权流的用户上下文无关。
解决方案
要获取用户的个人播放列表(包括公开和私有),必须使用Authorization Code授权流,该流程需要用户登录授权,获取带用户上下文的access token。
修改后的测试代码
import os from config import CLIENT_ID import spotipy from spotipy.oauth2 import SpotifyOAuth def main(): sp = get_spotipy_client() # 获取当前授权用户的播放列表 playlists = sp.current_user_playlists() for playlist in playlists['items']: print(playlist['name']) def get_spotipy_client(): client_secret = os.getenv("CLIENT_SECRET") redirect_uri = "http://localhost:8888/callback" # 需在Spotify开发者后台配置 if not isinstance(CLIENT_ID, str) or not CLIENT_ID: raise ValueError("CLIENT_ID必须是非空字符串。") if not isinstance(client_secret, str) or not client_secret: raise ValueError("CLIENT_SECRET必须是非空字符串。") # 使用Authorization Code授权流,申请播放列表读取权限 sp_oauth = SpotifyOAuth( client_id=CLIENT_ID, client_secret=client_secret, redirect_uri=redirect_uri, scope="playlist-read-private playlist-read-collaborative" ) sp = spotipy.Spotify(auth_manager=sp_oauth) return sp if __name__ == "__main__": main()
注意事项
- 需在Spotify开发者后台的应用设置中,添加
http://localhost:8888/callback作为重定向URI scope参数按需选择:playlist-read-private读取私有列表,playlist-read-collaborative读取协作列表,playlist-read-public读取公开列表- 首次运行会打开浏览器引导用户登录授权,授权后会自动缓存token,后续运行无需重复授权
内容的提问来源于stack exchange,提问作者Greg Oliver
相关产品推荐
相关产品推荐

