Ethan M
Ethan M

Reputation: 15

Why does this curl command work but not my post request via python?

I'm trying to make a POST request to https://accounts.spotify.com/api/token via python and the request, library but can't get it to work. I'm able to execute the request via curl command:

note - params enclosed in * * are correct and work in the curl request

 curl -H "Authorization: Basic *base 64 encoded client ID and secret*"
 -d grant_type=authorization_code -d code=*auth code* -d 
 redirect_uri=https%3A%2F%2Fopen.spotify.com%2F 
 https://accounts.spotify.com/api/token 

and the request works just fine, however when I try to make what I think is the exact same request in python, I always get the same bad request error

    headers = {
        "Authorization": "Basic *base64 encoded client ID and secret*"
    }
    params = {
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "https://open.spotify.com/"
    }

    response = requests.post(
        url,
        params=params,
        headers=headers
    )

If you can help me figure out how the two requests differ and why the python one never seems to work that would be amazing.

see section 2. of https://developer.spotify.com/documentation/general/guides/authorization-guide/ for the params

Upvotes: 1

Views: 1104

Answers (2)

kuter
kuter

Reputation: 204

seems like you put payload under wrong argument, try to change params into json or data (depends on what type of requests that API accept):

response = requests.post(
    url,
    json=params,
    headers=headers
)

Upvotes: 0

Gabio
Gabio

Reputation: 9504

You use -d flag in your curl request which stands for data.

So you should pass your params as data also in your Python POST request:

headers = {
        "Authorization": "Basic *base64 encoded client ID and secret*"
    }
    params = {
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "https://open.spotify.com/"
    }

    response = requests.post(
        url,
        data=params,
        headers=headers
    )

Upvotes: 1

Related Questions