Create a simple server-side application that accesses user related data through the Spotify Web API.

Note: By using the Spotify Tools, you accept our Developer Terms of Service.

Through the Spotify Web API, external applications retrieve Spotify content such as album data and playlists. To access user-related data through the Web API, an application must be authorized by the user to access that particular information.

In this tutorial we create a simple application using Node.js and JavaScript and demonstrate how to:

  • Register an application with Spotify
  • Authenticate a user and get authorization to access user data
  • Retrieve the data from a Web API endpoint

The authorization flow we use in this tutorial is the Authorization Code Flow. This flow first gets a code from the Spotify Accounts Service, then exchanges that code for an access token. The code-to-token exchange requires a secret key, and for security is done through direct server-to-server communication.

In this example we retrieve data from the Web API /me endpoint, that includes information about the current user.

The complete source code of the app that will create in this tutorial is available on GitHub.

Set Up Your Account

To use the Web API, start by creating a Spotify user account (Premium or Free). To do that, simply sign up at www.spotify.com.

When you have a user account, go to the Dashboard page at the Spotify Developer website and, if necessary, log in. Accept the latest Developer Terms of Service to complete your account set up.

Register Your Application

Any application can request data from Spotify Web API endpoints and many endpoints are open and will return data without requiring registration. However, if your application seeks access to a user’s personal data (profile, playlists, etc.) it must be registered. Registered applications also get other benefits, like higher rate limits at some endpoints.

You can register your application, even before you have created it.

Prepare Your Environment

Now that you have registered the application, set up your environment.

Note: If you are already confident of your setup, you might want to skip ahead and download the code of our Authentication Flow example app from GitHub.

  1. In this tutorial, since we are creating a server-side application, we will need the appropriate software platform. For this, we use Node.js. If you do not already have Node.js installed, download and install it with the default settings for your environment.

  2. Test that Node.js is installed and set up correctly: in your favorite text editor create a simple server.js file with the following code:

  /* Load the HTTP library */
  var http = require("http");

  /* Create an HTTP server to handle responses */

  http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
  }).listen(8888);

This code creates a simple HTTP server on your local machine.

  1. Save the file in a folder named njtest and then execute the file in the command prompt:
cd njtest
node server.js
  1. Open a browser and go to the URL localhost:8888; the words “Hello World” should appear in your browser window:

image alt text

  1. Kill the server with CTRL-C in the command prompt window; you have now completed and checked your set up of Node.js. If you cannot get the example above to work, troubleshoot and fix it before continuing.

Note: In the endpoint reference pages, see cURL syntax for the example requests. You do not need cURL to complete this tutorial, but you will probably find it a helpful tool when developing your application; it will help you formulate requests to Spotify web services and see the responses they return. Install the version with SSL support if you need it.

Create a Project Folder and Files

  1. Now that you have installed Node.js, create a project folder for your application and download or clone into it the OAuth examples from the GitHub repository.
  2. The code of the OAuth examples depends on the packages express,request and querystring. Install the dependencies running the following command within the folder you just created!
npm install
  1. When the installation is completed, check that your project folder now contains a subfolder called node_modules, and that that folder contains at least those packages.

Prompt the User to Login

Examine the code of the Authorization Code example.

  1. Open the authorization_code folder:
cd authorization_code

The public folder is the web root. This is where we have put the public web pages for the application.

Note: All the other files are located outside this folder and therefore are not accessible to the application user.

  1. Open the index.html file. This file provides a simple interface that prompts the user to login:
<html>
  <head>
  ...
  <style type="text/css">
  #login {
    display: none;
  }

  #loggedin {
    display: none;
  }
  ...
</style>
<body>
 <div>
    <div id="login">
     <h1>First, log in to spotify</h1>
     <a href="/login">Log in</a>
    </div>
    <div id="loggedin">
    </div>
 </div>

 <script id="loggedin-template" type="text/x-handlebars-template">
    <h1>Logged in as </h1>
    <img id="avatar" width="200" src="" />
    <dl>
     <dt>Display name</dt><dd></dd>
     <dt>Username</dt><dd></dd>
     <dt>Email</dt><dd></dd>
     <dt>Spotify URI</dt><dd><a href=""></a></dd>
     <dt>Link</dt><dd><a href=""></a></dd>
     <dt>Profile Image</dt><dd></dd>
    </dl>
    <p><a href="/">Log in again</a></p>
 </script>
</body>
</html>

This HTML file both provides a “Log in” link and makes the call to Web API (not shown in the listing above), and provides a template for data display of what is returned by the Web API /me endpoint).

Provide the Application Credentials

The app.js file contains the main code of the application. Open it in an editor and you will find that it contains code for:

  • Creating a server on your local machine
  • Handling the user login request
  • Specifying the scopes for which authorization is sought
  • Performing the exchange of the authorization code for an access token
  • Calling the Web API endpoint

This file contains the Client ID, Client Secret, and redirect URI:

var client_id = 'CLIENT_ID'; // Your client id
var client_secret = 'CLIENT_SECRET'; // Your secret
var redirect_uri = 'REDIRECT_URI'; // Your redirect uri

To try the app, replace these credentials with the values that you received when you registered your app. In this demonstration app we use http://localhost:8888/callback as the redirect URI.

You can also see in this file the data scopes that we intend to ask the user to authorize access to :

var scopes = \'user-read-private user-read-email\'

This means that the app requests access to the user full name, profile image, and email address.

Call the Spotify Accounts Service

See that the app.js file contains three calls to the Spotify Accounts Service:

  • The first call is the service ‘/authorize’ endpoint, passing to it the client ID, scopes, and redirect URI. This is the call that starts the process of authenticating to user and gets the user’s authorization to access data.

  • The second call is to the Spotify Accounts Service ‘/api/token’ endpoint, passing to it the authorization code returned by the first call and the client secret key. This call returns an access token and also a refresh token.

Note: As app.js is not in the /public directory, its machinations cannot be seen from a web browser. This is important because we never want to expose our application Client Secret to a user. Make sure that you safeguard your application Client Secret at all times. Be aware, for example, that if you commit your code to a public repository like GitHub you will need to remove the Client Secret from your code before doing so.

To better understand the Accounts Service endpoints and the parameters passed in each call, see the full description of the Authorization Code Flow.

After both calls are completed, and the user has authorized the app for access, the application will have the ‘access_token’ it needs to retrieve the user data from the Web API.

  • The third call, in the code managing requests to ‘/refresh_token’, a refresh token is sent to ‘/api/token’. This will generate a new access token that we can issue when the previous has expired.

Running the Application

  1. Start the server by running the following command at the command prompt:
    node app.js
    
  2. Open a browser and visit the project home page again. Now that the server is running, you can use the following URL: http://localhost:8888.
  3. See the file in a browser (http://localhost:8888); you should see the initial display: image alt text
  4. Click Log in link; the Spotify Accounts login appears. image alt text
  5. Log in with your Spotify credentials; you are now looking at the authorization screen where permission is requested to access your account data: image alt text The Spotify Accounts Service now uses the redirect_uri to return to the application, passing back the authorization_code which is subsequently exchanged in a second call for an access_token. The home page can call a Web API endpoint at /me, retrieve data, and render it: image alt text
  6. Click Obtain new token using the refresh token; see that a new access token is generated; you have just completed creating a simple server-side application that accesses user related data. As this example app demonstrates how to retrieve data using an authorization flow, it may serve as a useful template for your own applications. Good luck!