【问题标题】:Spotify API Authorization Code Flow with Python使用 Python 的 Spotify API 授权代码流
【发布时间】:2021-04-02 18:21:01
【问题描述】:

我正在尝试使用 Spotify 的 API 执行授权代码流,以最终将歌曲添加到播放列表。我正在从头开始构建它,并且使用任何库,例如 Spotipy。

我能够成功访问授权端点,但我遇到了令牌端点的一些问题。这是我到目前为止的代码:

# 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?

【问题讨论】:

    标签: api authorization spotify api-authorization


    【解决方案1】:

    如果我没记错的话,您可能错过了代码中设置的 CLIENT_ID 和 CLIENT_SECRET。

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

    您还可以使用 Python 的 Spotipy 库来简化操作。 https://spotipy.readthedocs.io/en/2.16.1/

    【讨论】:

      猜你喜欢
      • 2019-05-03
      • 2018-09-22
      • 2018-05-21
      • 2017-10-19
      • 2019-09-12
      • 2021-03-08
      • 2019-01-25
      • 2020-10-06
      • 1970-01-01
      相关资源
      最近更新 更多