6
votes

This is one of my many attempts at making a POST request to https://accounts.spotify.com/api/token.

Scope was set to 'playlist-modify-public, playlist-modify-private'.

I'm using Python 3.7, Django 2.1.3.

No matter what I do, response_data returns {'error': 'invalid_client'}

I've tried many things, including passing the client_id/client_secret inside the body of the request as per the official Spotify documentation for this particular request... to no avail.

Please help!

def callback(request):

    auth_token = request.GET.get('code')     # from the URL after user has clicked accept
    code_payload = {
        'grant_type': 'authorization_code',
        'code': str(auth_token),
        'redirect_uri': REDIRECT_URI,
    }

    auth_str = '{}:{}'.format(CLIENT_ID, CLIENT_SECRET)
    b64_auth_str = base64.b64encode(auth_str.encode()).decode()

    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic {}'.format(b64_auth_str)
    }

    post_request = requests.post(SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)

    response_data = json.loads(post_request.text)
        # ==> {'error': 'invalid_client'}
2
Hello. Did you figure out how to solve? - Matteus Barbosa
Hey @MatteusBarbosa, I actually realized I had reset my Spotify client_secret on the Spotify Dashboard and completely forgot to modify my code accordingly... Felt real smart :| - Charlotte Prevost
thanks for your response - Matteus Barbosa

2 Answers

4
votes

I suspect the issue is with invalid characters in your Authorization header. Try using urlsafe_b64encode instead of b64encode to prepare that header value:

b64_auth_str = base64.urlsafe_b64encode(auth_str.encode()).decode()
0
votes

From the documentation

An alternative way to send the client id and secret is as request parameters (client_id and client_secret) in the POST body, instead of sending them base64-encoded in the header.

    SPOTIFY_TOKEN = "https://accounts.spotify.com/api/token"
    request_body = {
        "grant_type": GRANT_TYPE,
        "code": code,
        "redirect_uri": REDIRECT_URI,
        "client_id": SPOTIFY_CLIENT_ID,
        "client_secret": SPOTIFY_CLIENT_SECRET,
    }
    r = requests.post(url=SPOTIFY_TOKEN, data=request_body)
    resp = r.json()

This works as well.