requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://accounts.spotify.com/api/token

requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://accounts.spotify.com/api/token

我对 Python 3 和 Flask 很陌生,我目前正在构建一个简单的 Web 应用程序来使用来自 Spotify API 的数据。

OAuth 2.0 身份验证流程几乎可以正常工作,因为我可以调用 https://accounts.spotify.com/authorize

在对 API 的 POST 请求期间,我收到 HTTP 400:

authentication_token = request.args['code']
code_payload = {
    "grant_type": "authorization_code",
    "code": str(authentication_token),
    "redirect_uri": REDIRECT_URI
}
encoded_oauth2_tokens = base64.b64encode('{}:{}'.format(CLIENT_ID, CLIENT_SECRET).encode())
headers = {"Authorization": "Basic {}".format(encoded_oauth2_tokens)}
post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)
post_request.raise_for_status()

编辑:响应正文:

"GET / HTTP/1.1" 302 - b'{"error":"invalid_client"}'

不确定请求中有什么问题。

我能够根据此 question 的提示更正问题。

向 header 添加 encoded_oauth2_tokens.decode() 是向 Spotify API 发出有效请求所缺少的部分。代码如下:

encoded_oauth2_tokens = base64.b64encode('{}:{}'.format(CLIENT_ID, CLIENT_SECRET).encode())
headers = {"Authorization": "Basic {}".format(encoded_oauth2_tokens.decode())}