Obtain the Authorization Code Access Token

Get the authorization code access token required to access the Spotify API endpoints.

As we discussed earlier, for all the endpoints where we access a user's resources, we need to use either the authorization code, the authorization code with PKCE, or the implicit grant flow to get the access token. In this lesson, we’ll learn how to get the access token using the authorization code flow.

Authorization code

The workflow needed to get the authorization code access token is as follows:

  • First, we need to redirect the user to the Spotify API server by making a call to the base URI https://accounts.spotify.com/authorize with some query parameters. The user is asked to log in to Spotify using a dialog box.
  • After the user has logged in, a dialog box will pop up asking the user to accept or deny our grant request.
  • Once the user accepts our request, we'll receive a code.
  • Then we’ll make an API call using the base URI https://accounts.spotify.com/api/token and some query parameters.
  • Finally, we’ll receive an access token that we can use to access the user-specific endpoints.
  • Get an access token

    It is time to get our access token using the authorization code flow. We'll use the Flask app in the widget below to get the token. Click "Run" to see the app in action.

    app = Flask(__name__)
    
    
    #  Client Keys
    CLIENT_ID = "{{CLIENT_ID}}"
    CLIENT_SECRET = "{{CLIENT_SECRET}}"
    # Encoding values for header
    ENCODED_CLIENT_SECRET = base64.b64encode(b'{{CLIENT_ID}}:{{CLIENT_SECRET}}')
    ENCODED_CLIENT_SECRET=ENCODED_CLIENT_SECRET.decode("utf-8")
    
    # Spotify URLS
    SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize"
    SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
    
    # Server-side Parameters
    REDIRECT_URI = "{{EDUCATIVE_LIVE_VM_URL}}/callback"
    SCOPE = "playlist-read-collaborative playlist-modify-public playlist-modify-private playlist-read-private user-library-read user-library-modify"
    RESPONSE_TYPE = "code"
    GRANT_TYPE = 'authorization_code'
    
    @app.route("/")
    def index():
        authorize_url = 'https://accounts.spotify.com/en/authorize?response_type={}&client_id={}&redirect_uri={}&scope={}&show_dialog=TRUE'.format(RESPONSE_TYPE,CLIENT_ID,REDIRECT_URI,SCOPE)
        response = redirect(authorize_url)
        return response
    
    
    @app.route("/callback")
    def callback():
        token_url = 'https://accounts.spotify.com/api/token'
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic '+'{}'.format(ENCODED_CLIENT_SECRET)
            }
        body = {'code': request.args.get('code'), 'redirect_uri': REDIRECT_URI, 
                'grant_type': GRANT_TYPE}
        post_response = requests.post(token_url,headers=headers,data=body)
        return render_template('home.html',token=post_response.json())
    
    
    if __name__ == '__main__':
        app.run(debug=True)
    Get authorization code access token

    Once the app is up and running, follow the steps below:

    • Go to the app URL mentioned under the "Run" button. The index() function defined in lines 21–24 makes the API call for the code and redirects to the Spotify API server.
    • Log in if required and accept the code request. A code will be sent to this app after the permission has been granted. Once this app receives the code, the callback() function defined in lines 28–39 will request the access token. In response to this request, we'll obtain our access token.
    • Copy the access_token and the refresh_token received in response and save them in the widget below.

    Once we’ve saved the tokens, click the "Run" button to check the validity of the access token.

    Press + to interact
    validation() # A function which checks the validity of the access token using hidden code

    Note: The query parameters for the Authorize and Token endpoints have been discussed in detail in this lesson of the "Appendix" chapter.

    Refresh token

    The access code provided by the app above is valid for one hour only. We wouldn't want to bother the user after one hour to grant us permission to get a new access token. This is where the refresh_token that we saved in the above widget plays its role. After the access token has expired, we can call the base URI https://accounts.spotify.com/api/token with grant_type set to refresh_token to get a new access token. The refresh_token is sent as a query parameter with this request.

    Refresh the access token

    The code below shows how we can get a new access code using the refresh token. Click the "Run" button to get a new access token.

    Press + to interact
    URL = "https://accounts.spotify.com/api/token?grant_type=refresh_token&refresh_token={{REFRESH_TOKEN}}"
    encoded = base64.b64encode('{{CLIENT_ID}}:{{CLIENT_SECRET}}')
    headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Basic '+encoded
    }
    response = requests.request("POST", URL, headers=headers).json()
    print(json.dumps(response, indent=4))
    • Line 1: We define the URL.
    • Line 2: We encode the CLIENT_ID and CLIENT_SECRET.
    • Lines 3–6: We define the header to be sent with the request.
    • Line 8: We request the access token and save it in result.
    • Line 10: We finally print the response of the API call.

    We receive the access token, its type, its validity duration, and its scope, in response.