使用Python的Spotify API授权代码流 [英] Spotify API Authorization Code Flow with Python

查看:20
本文介绍了使用Python的Spotify API授权代码流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Spotify的API完成授权代码流程,最终将歌曲添加到播放列表中。我是从头开始构建的,不是使用任何库(如Spotipy)

我能够成功访问授权终结点,但令牌终结点有一些问题。以下是我到目前为止拥有的代码:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
# URLS
AUTH_URL = 'https://accounts.spotify.com/authorize'
TOKEN_URL = 'https://accounts.spotify.com/api/token'
BASE_URL = 'https://api.spotify.com/v1/'


# Make a request to the /authorize endpoint to get an authorization code
auth_code = requests.get(AUTH_URL, {
    'client_id': CLIENT_ID,
    'response_type': 'code',
    'redirect_uri': 'https://open.spotify.com/collection/playlists',
    'scope': 'playlist-modify-private',
})
print(auth_code)

auth_header = base64.urlsafe_b64encode((CLIENT_ID + ':' + CLIENT_SECRET).encode('ascii'))
headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Basic %s' % auth_header.decode('ascii')
}

payload = {
    'grant_type': 'authorization_code',
    'code': auth_code,
    'redirect_uri': 'https://open.spotify.com/collection/playlists',
    #'client_id': CLIENT_ID,
    #'client_secret': CLIENT_SECRET,
}

# Make a request to the /token endpoint to get an access token
access_token_request = requests.post(url=TOKEN_URL, data=payload, headers=headers)

# convert the response to JSON
access_token_response_data = access_token_request.json()

print(access_token_response_data)

# save the access token
access_token = access_token_response_data['access_token']

当我运行我的脚本时,我在终端中得到以下输出:

{'error': 'invalid_grant', 'error_description': 'Invalid authorization code'}
Traceback (most recent call last):
  File "auth.py", line 48, in <module>
    access_token = access_token_response_data['access_token']
KeyError: 'access_token'```

Can anyone explain to me what I might be doing wrong here?

推荐答案

如果我没有记错的话,您缺少代码中的CLIENT_ID和CLIENT_SECRET集。

这意味着Spotify将返回无效的访问令牌,导致您无法继续。

您还可以使用Spotipy库for Python使事情变得更容易。 https://spotipy.readthedocs.io/en/2.16.1/

这篇关于使用Python的Spotify API授权代码流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆