PYTHON: requests.post () как отправить request_body в кодировке application / x- www-form-urlencoded - PullRequest
1 голос
/ 14 июля 2020

Я создаю приложение с 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

1 Ответ

1 голос
/ 14 июля 2020

Вы можете указать тип запроса в заголовке запроса.

    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(endpoint, data=request_body, headers=headers)
    print(response)
...