简体   繁体   中英

Soundcloud API - authentication works via curl, but not via Python script?

I can successfully authenticate and get an access + refresh token using curl, but my Python authentication script won't work and returns a 401 error.

authentication_endpoint = 'https://api.soundcloud.com/oauth2/token'

def refresh_access_token(self):
    headers = {
        "accept": 'application/json; charset=utf-8',
        "Content-Type": 'application/x-www-form-urlencoded',
        "grant_type": 'client_credentials',
        "client_id": self.client_id,
        "client_secret": self.client_secret,
    }
    req = requests.post(self.authentication_endpoint, headers=headers)

The client_id and client_secret are correct because I have a script that performs queries -- which runs just fine as long as I have an access token.

Since the query script runs without problems, I'm not sure what's wrong with the authentication script. Am I only able to get the access token via curl?

edit: This is the curl command that I use to get an access token

https://developers.soundcloud.com/docs/api/guide#client-creds

# obtain the access token

$ curl -X POST "https://api.soundcloud.com/oauth2/token" \
     -H  "accept: application/json; charset=utf-8" \
     -H  "Content-Type: application/x-www-form-urlencoded" \
     --data-urlencode "grant_type=client_credentials" \
     --data-urlencode "client_id=YOUR_CLIENT_ID" \
     --data-urlencode "client_secret=YOUR_CLIENT_SECRET"

It's a post request, so I needed to post a "data" object in the body, not a "header". Silly mistake

def refresh_access_token(self):
    data = {
        "accept": 'application/json; charset=utf-8',
        "Content-Type": 'application/x-www-form-urlencoded',
        "grant_type": 'client_credentials',
        "client_id": self.client_id,
        "client_secret": self.client_secret,
    }
    req = requests.post(self.authentication_endpoint, data=data)

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