Obtain the Client Credential Access Token

Get the client credential access token to access all the public endpoints of Spotify without any user authorization.

In case we don't need access to any user resources, we can request an access token using the client credentials workflow. This is a straightforward authorization method and requires only one API call. In this lesson, we'll generate a token using this workflow.

Client credentials authorization

The base URI https://accounts.spotify.com/api/token is used to get a token using the client credentials flow.

Get an access token

Let's generate an access token using our credentials. The code below shows how this can be done. Click the "Run" button to generate the access token. We'll extract the access token from the output response. Click the "Save" button of the dialog box, which will appear after the code execution, to save this access token for later use.

Note: This token is valid for one hour (3600 seconds). After one hour, we'll have to request a new token.

Press + to interact
URL = "https://accounts.spotify.com/api/token?grant_type=client_credentials"
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: It contains the URL for client credentials flow.
  • Line 2: We encode the CLIENT_ID and CLIENT_SECRET in the required format.
  • Lines 3–6: We define the header.
  • Line 8: We make the API call.
  • Line 10: We print the response.

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

The code below checks the validity of the token obtained above via an API call. The code is hidden because we don’t need to go into the details of its implementation. Click the "Run" button to execute the code.

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

Using this access token, we can call any public endpoint of Spotify API. However, we will need to generate a new token once it expires.