简体   繁体   中英

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

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
    )

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM