PYTHON: requests.post() how to send request_body encoded as application/x-www-form-urlencoded
Asked Answered
W

1

11

I'm doign an app with the Spotify API. My problem is I'm trying to get an access_token but It's not working. In the docs it says i need to send the body encoded as application/x-www-form-urlencoded so I search a little bit and It should work just setting request_body as a dictionary.

This is the code of my function:

    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)

The response I'm getting is always <Response [400]> Here are the docs, step 4 https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow-with-proof-key-for-code-exchange-pkce NOTE: I tryed executing this as a curl and it works fine I'm not sure what I'm doing wrong in the python code here's the command:

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
Wittol answered 14/7, 2020 at 0:25 Comment(0)
F
22

You can specify the request type in the request header.

    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(endpoint, data=request_body, headers=headers)
    print(response)
Finkle answered 14/7, 2020 at 1:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.