Python Spotipy:在创建私人播放列表时,尽管已经使用playlist-modify-private,仍然出现“Insufficient Scope”错误

前端开发 2026-07-12

我正在尝试使用Spotify Web API(通过Python的 spotipy 库)创建一个私人播放列表,但遇到了授权错误。

问题 当我运行我的脚本时,我收到一个 403 Forbidden 错误。有人建议检查作用域,特别是 playlist-modify-private

我的代码

Python

import spotipy
from spotipy.oauth2 import SpotifyOAuth

# My current scope setup
scope = "playlist-modify-private" 

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))

# The line causing the error
sp.user_playlist_create(user="USER_ID", name="New Private Playlist", public=False)

我尝试过的办法

  • 我核对了我的客户端ID和密钥,确认无误。
  • 我查看了 @C3roe提供的Spotify文档,文档中确认 playlist-modify-private 是正确的作用域。

错误信息

针对 https://api.spotify.com/v1/users/USER_ID/playlists 进行POST请求时返回的HTTP错误,Params: {},返回403 Forbidden

解决方案

99% 的概率是缓存令牌的问题。Spotipy会把你的访问令牌保存在一个 .cache 文件中,即使你在代码中更改了作用域,它也会重复使用该令牌。因此如果你之前曾在不同的作用域(或没有作用域)运行过脚本,它仍在使用那个旧令牌。

删除你在项目目录中的 .cache 文件(如果你设置了用户名则删除 .cache-{your_username}),然后再次运行你的脚本。此次它应该会在浏览器中打开Spotify授权页面,并请求正确的权限。

# also worth using all the playlist scopes to avoid running into this again
scope = "playlist-modify-private playlist-modify-public playlist-read-private"

另外再确认一下,你是不是不小心在某处使用了 SpotifyClientCredentials 而不是 SpotifyOAuth。客户端凭据流不支持诸如创建播放列表之类的用户特定操作,你需要使用授权码流来实现。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章