Search code examples
pythonauthorizationspotify

Spotify API (Obtaining Authorization Code) using Python


My goal is to connect to the Spotify API using pure Python and I have been able to figure out how to obtain the authorization token given the authorization code but I am unable to get the authorization code itself.

Note: I have not provided the client_id and client_secret for obvious reasons and you can assume that all libraries have been imported.

Once the web browser opens, the authorization code ("code") is displayed as a query parameter in the URL but I am unsure how to go about saving it to a variable. I can't just copy and paste it to a variable as the authorization code constantly changes.

My question is how exactly I would go about retrieving the code query paramter and save it to a variable?

Here is what I have tried so far:

    # credentials
    client_id = "xxx..."
    client_secret = "xxx..."

    # urls
    redirect_uri = "http://localhost:7777/callback"
    auth_url = "https://accounts.spotify.com/authorize?"
    token_url = "https://accounts.spotify.com/api/token"

    # data scopes
    scopes = "user-read-private user-read-email"

    # obtains authorization code
    payload = {
        "client_id": client_id,
        "response_type": "code",
        "redirect_uri": redirect_uri,
        "scope": scopes
    }
    webbrowser.open(auth_url + urlencode(payload))

    code = # NOT SURE HOW TO RETRIEVE CODE

    # obtains authorization token
    encoded_creds = base64.b64encode(client_id.encode() + b":" + client_secret.encode()).decode('utf-8')
    token_headers = {
        "Authorization": "Basic " + encoded_creds,
        "Content-Type": "application/x-www-form-urlencoded"
    }
    token_data = {
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": redirect_uri
    }
    r = req.post(token_url, data=token_data, headers=token_headers)

Solution

  • You'll need to extract the code from your callback URL. If authentication is successful, Spotify will make a request to your redirect_uri with the code in the query (e.g http://localhost:7777/callback?code=...).

    The easiest way to do that is probably spin up a Flask server (or equivalent) with a GET callback endpoint and grab the code there. Then you can exchange it for the authorization token in the same endpoint if you'd like. This example may be helpful: https://github.com/spotify/web-api-auth-examples/blob/master/authorization_code/app.js#L60