首页 > 解决方案 > 如何使用客户端 ID 和密码访问 spotify 的 Web api?

问题描述

我正在尝试编写一个脚本,从头开始在 python 中的我的 spotify 帐户上创建一个播放列表,而不是使用像spotipy这样的模块。

我的问题是如何使用请求模块对我的客户端 ID 和客户端密钥进行身份验证,或者如何使用这些凭据获取访问令牌?

标签: pythonauthorizationspotify

解决方案


试试这个完整的客户端凭据授权流程。

第一步 - 使用您的凭据获取授权令牌:

CLIENT_ID = " < your client id here... > "
CLIENT_SECRET = " < your client secret here... > "

grant_type = 'client_credentials'
body_params = {'grant_type' : grant_type}

url='https://accounts.spotify.com/api/token'
response = requests.post(url, data=body_params, auth = (CLIENT_ID, CLIENT_SECRET)) 

token_raw = json.loads(response.text)
token = token_raw["access_token"]

第二步——向任何播放列表端点发出请求。确保为 设置有效值<spotify_user>

headers = {"Authorization": "Bearer {}".format(token)}
r = requests.get(url="https://api.spotify.com/v1/users/<spotify_user>/playlists", headers=headers)
print(r.text)

推荐阅读