Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spotify API authentication with Python

I'm trying to authenticate a user in the Spotify API, but it keeps returning me the error code "invalid_client". I'm implementing that on a Python Django solution, that's my code:

headers = {'Authorization': 'Basic '+standard_b64encode(client_id)+standard_b64encode(client_secret)}
r = requests.post('https://accounts.spotify.com/api/token', {'code': code, 'redirect_uri': redirect_uri, 'grant_type': grant_type, 'headers': headers}).json()

Any idea why it's not working?


1 Answers

In spotify api docs it is: Authorization Required. Base 64 encoded string that contains the client ID and client secret key. The field must have the format: Authorization: Basic base64 encoded( client_id:client_secret)

So i guess you should do:

import base64
'Authorization' : 'Basic ' + base64.standard_b64encode(client_id + ':' + client_secret)

It's working for me so try it. If it doesn't work my code is:

@staticmethod
def loginCallback(request_handler, code):
    url = 'https://accounts.spotify.com/api/token'
    authorization = base64.standard_b64encode(Spotify.client_id + ':' + Spotify.client_secret)

    headers = {
        'Authorization' : 'Basic ' + authorization
        } 
    data  = {
        'grant_type' : 'authorization_code',
        'code' : code,
        'redirect_uri' : Spotify.redirect_uri
        } 

    data_encoded = urllib.urlencode(data)
    req = urllib2.Request(url, data_encoded, headers)

    try:
        response = urllib2.urlopen(req, timeout=30).read()
        response_dict = json.loads(response)
        Spotify.saveLoginCallback(request_handler, response_dict)
        return
    except urllib2.HTTPError as e:
        return e

Hope it helps!

like image 75
NBajanca Avatar answered Dec 07 '25 22:12

NBajanca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!