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 resource, 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
const endpointUrl = new URL('https://accounts.spotify.com/api/token');
const queryParameters = new URLSearchParams({
grant_type: 'client_credentials'
});
const required_ids = Buffer.from('{{CLIENT_ID}}:{{CLIENT_SECRET}}');
const encoded = required_ids.toString('base64');
headerParameters = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic '+encoded
}
const options = {
method: 'POST',
headers: headerParameters
};
async function fetchAccessToken() {
try {
endpointUrl.search = queryParameters;
const response = await fetch(endpointUrl, options);
printResponse(response);
} catch (error) {
printError(error);
}
}
fetchAccessToken();

Following is a brief explanation of the above code:

  • Line 1: We define the URL for the client credentials flow.

  • Lines 3–5: We define the required query parameters.

  • Lines 7–8: We encode the CLIENT_ID and CLIENT_SECRET in the required format and save the encoded ID in the encoded variable.

  • Lines 10–13: We define the header parameters.

  • Lines 20–28: We define an asynchronous function fetchAccessToken(). This function calls the endpoint on line 23 and prints the response on line 24. In case of an error, the printError() function executes and prints the error.

  • Line 30: We call fetchAccessToken().

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
validateToken() //A function that validate the client credentials access token

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.