3

我正在使用 Spotify API 开发一个应用程序。我的问题是我正在尝试获取access_token但它不起作用。在文档中它说我需要发送编码为 application/x-www-form-urlencoded 的正文,所以我搜索了一下,它应该只是设置request_body为字典。

这是我的函数的代码:

    def get_access_token(self):
        auth_code, code_verifier = self.get_auth_code()
        endpoint = "https://accounts.spotify.com/api/token"

        # as docs said data should be encoded as application/x-www-form-urlencoded
        # as internet says i just need to send it as a dictionary. However it's not working
        request_body = {
                "client_id": f"{self.client_ID}",
                "grant_type": "authorization_code",
                "code": f"{auth_code}",
                "redirect_uri": f"{self.redirect_uri}",
                "code_verifier": f"{code_verifier}"
        }

        response = requests.post(endpoint, data=request_body)
        print(response)

我得到的响应总是<Response [400]> 这里是文档,第 4 步https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow-with-proof-key-for- code-exchange-pkce 注意:我尝试将其作为 curl 执行,它工作正常我不确定我在 python 代码中做错了什么,这是命令:

curl -d client_id={self.client_ID} -d grant_type=authorization_code -d code={auth_code} -d redirect_uri={self.redirect_uri} -d code_verifier={code_verifier} https://accounts.spotify.com/api/token
4

1 回答 1

6

您可以在请求标头中指定请求类型。

    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(endpoint, data=request_body, headers=headers)
    print(response)
于 2020-07-14T01:07:18.893 回答