Using spotify-web-api.js

The Spotify documentation provides a list of wrapper libraries for a variety of languages. One of the JavaScript libraries listed is named spotify-web-api.js. This tutorial will show how to use spotify-web-api.js to download the meta data for all of Elvis’ albums and then display all of the album covers for those albums.

Prerequisites

In this tutorial, we assume that you have the spotify-web-api.js file loaded in the browser. For information on how to load the file using require.js see the tutorial named Using Require.js. We also assume that you’ve registered your web app with Spotify, have set the application’s redirect URI, and requested user permissions, and have received an access token. Please see the tutorial named Spotify for Developers for information on how to accomplish all of that.

Instantiating the spotify-web-api Wrapper

Before you can request information you need to instantiate the spotify-web-api wrapper. You do so by calling the SpotifyWebApi constructor.

let spotifyApi = new SpotifyWebApi();

Next, you need to register your access token.

spotifyApi.setAccessToken(params.access_token);

Getting Data From Spotify

The example below is taken directly from the spotify-web-api.js GitHub website. It retrieves all of the album information for Elvis using the JavaScript Promise pattern.

// get Elvis' albums, using Promises through Promise, Q or when 
spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE')   
.then(function(data) {
    // use the data as you see fit
    console.log('Artist albums', data);
}, function(err) {     
    console.error(err);   
});