0

It's my intention to authenticate with Spotify. After authorizing user, this should fetch user information with walking through an official document.

An example cURL request and response from the token endpoint will look something like this:

curl -H "Authorization: Basic ZjM...zE=" -d grant_type=authorization_code -d code=MQCbtKe...44KN -d redirect_uri=https%3A%2F%2Fwww.foo.com%2Fauth https://accounts.spotify.com/api/token

via Authorization Guide

But this error occurs to it:

TypeError: a bytes-like object is required, not 'str'

This is my code:

client_id = 'XXXXXXXXXXXXXXXXXX'
client_secret = 'XXXXXXXXXXXXXXXXXX'
oauth_scope = 'user-read-currently-playing'
redirect_uri = 'http://localhost:3000/spotify_profile/callback'

@bp.route('/redirect', methods=['GET'])
def authorize():
    authorize_url = f"https://accounts.spotify.com/authorize?response_type=code&client_id={ client_id }&scope={ oauth_scope }&redirect_uri={ redirect_uri }"

    return redirect(authorize_url)

@bp.route('/callback', methods=["GET", "POST"])
def callback():
    auth_code = request.args['code']
    auth_client = client_id + client_secret
    auth_encode = 'Basic ' + base64.b64encode(auth_client)
    ## error happens

    headers = {
        'Authorization': auth_encode,
    }
    data = {
    'grant_type': 'authorization_code',
    'code': auth_code,
    'redirect_uri': redirect_uri
    }
    response = requests.post('https://accounts.spotify.com/api/token', headers=headers, data=data)
remotir
  • 117
  • 7

1 Answers1

0

Encode auth_client to bytes, then decode the result:

auth_encode = 'Basic ' + base64.b64encode(auth_client.encode()).decode()
AKX
  • 152,115
  • 15
  • 115
  • 172