[Django]-Spotify API authentication with Python

5👍

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!

0👍

Are you sure you’re providing client_id & client_secret in the proper format?
Looking at the docs, it suppose to be separated with :.

Also try to run the same flow with curl first and then replicate with python.

Leave a comment