A Node.js wrapper for Spotify's Web API
This is a universal wrapper/client for the Spotify Web API that runs on Node.JS and the browser, using browserify/webpack/rollup. A list of selected wrappers for different languages and environments is available at the Developer site's Libraries page.
It includes helper functions to do the following:
Some methods require authentication, which can be done using these flows:
Even though authentication isn't always necessary, it always gives benefits such as an increased rate limit.
$ npm install spotify-web-api-node --save
First, instantiate the wrapper.
var SpotifyWebApi = ;// credentials are optionalvar spotifyApi =clientId : 'fcecfc72172e4cd267473117a17cbd4d'clientSecret : 'a6338157c9bb5ac9c71924cb2940e1a7'redirectUri : '';
If you've got an access token and want to use it for all calls, simply use the api object's set method. Handling credentials is described in detail in the Authorization section.
Lastly, use the wrapper's helper methods to make the request to Spotify's Web API. The wrapper uses promises, so you need to provide a success callback as well as an error callback.
// Get Elvis' albumsspotifyApi;
If you dont wan't to use promises, you can provide a callback method instead.
// Get Elvis' albumsspotifyApi;
The functions that fetch data from the API also accept a JSON object with a set of options. For example, limit and offset can be used in functions that returns paginated results, such as search and retrieving an artist's albums.
Note that the options parameter is currently required if you're using callback methods.
// Passing a callback - get Elvis' albums in range [20...29]spotifyApi;
To enable caching, this wrapper now exposes the response headers and not just the response body. Since version 2.0.0, the response object has the format
In previous versions, the response object was the same as the response body.
Retrieving a track's metadata in
spotify-web-api-node version 1.4.0 and later
The response object for the same request in earlier versions than to 2.0.0.
Below are examples for all helper functions. Longer examples of some requests can be found in the examples folder.
Please note that since version 1.3.2 all methods accept an optional callback method as their last parameter. These examples however only use promises.
var SpotifyWebApi = ;var spotifyApi = ;// Get multiple albumsspotifyApi;// Get an artistspotifyApi;// Get multiple artistsspotifyApi;// Get albums by a certain artistspotifyApi;// Search tracks whose name, album or artist contains 'Love'spotifyApi;// Search artists whose name contains 'Love'spotifyApi;// Search tracks whose artist's name contains 'Love'spotifyApi;// Search tracks whose artist's name contains 'Kendrick Lamar', and track name contains 'Alright'spotifyApi;// Search playlists whose name or description contains 'workout'spotifyApi;// Get tracks in an albumspotifyApi;// Get an artist's top tracksspotifyApi;// Get artists related to an artistspotifyApi;/* Get Audio Features for a Track */// TBD/* Get Audio Features for several tracks Track */// TBD/** User methods*/// Get a userspotifyApi;// Get the authenticated userspotifyApi;/** Playlist methods*/// Get a playlistspotifyApi;// Get a user's playlistsspotifyApi;// Create a private playlistspotifyApi;// Add tracks to a playlistspotifyApi;// Add tracks to a specific position in a playlistspotifyApi;// Remove tracks from a playlist at a specific positionspotifyApi;// Remove all occurrence of a trackvar tracks = tracks : uri : "spotify:track:4iV5W9uYEdYUVa79Axb7Rh" ;var options = snapshot_id : "0wD+DKCUxiSR/WY8lF3fiCTb7Z8X4ifTUtqn8rO82O4Mvi5wsX8BsLj7IbIpLVM9" ;spotifyApi;// Reorder the first two tracks in a playlist to the place before the track at the 10th positionvar options = "range_length" : 2 ;spotifyApi;// Change playlist detailsspotifyApi;// Follow a playlist (privately)spotifyApi;// Unfollow a playlistspotifyApi;// Check if Users are following a PlaylistspotifyApi;/** Following Users and Artists methods*//* Get followed artists */spotifyApi;/* Follow a user */// TBD./* Follow an artist */// TBD./* Unfollow a user */// TBD/* Unfollow an artist */// TBD/* Check if a user is following a user */// TBD/* Check if a user is following an artist */// TBD/** Your Music library methods*//* Tracks */// Get tracks in the signed in user's Your Music libraryspotifyApi;// Check if tracks are in the signed in user's Your Music libraryspotifyApi;// Remove tracks from the signed in user's Your Music libraryspotifyApi;});// Add tracks to the signed in user's Your Music libraryspotifyApi;});/* Albums */// Get albums in the signed in user's Your Music libraryspotifyApi;// Check if albums are in the signed in user's Your Music libraryspotifyApi;// Remove albums from the signed in user's Your Music libraryspotifyApi;});// Add albums to the signed in user's Your Music libraryspotifyApi;});/** Browse methods*/// Retrieve new releasesspotifyApi;});// Retrieve featured playlistsspotifyApi;// Get a List of CategoriesspotifyApi;// Get a Category (in Sweden)spotifyApi;// Get Playlists for a Category (Party in Brazil)spotifyApi;/* Get Recommendations Based on Seeds */// TBD/*** Personalization Endpoints*//* Get a User’s Top Artists and Tracks */// TBDGet a User’s Top Artists and Tracks
// track detail information for album tracksspotifyApi;// album detail for the first 10 Elvis' albumsspotifyApi;
Supplying an access token in a request is not always required by the API (see the Endpoint reference for details), but it will give your application benefits such as a higher rate limit. This wrapper supports two authorization flows; The Authorization Code flow (signed by a user), and the Client Credentials flow (application authentication - the user isn't involved). See Spotify's Authorization guide for detailed information on these flows.
With the application created and its redirect URI set, the only thing necessary for the application to retrieve an authorization code is the user's permission. Which permissions you're able to ask for is documented in Spotify's Using Scopes section.
In order to get permissions, you need to direct the user to our Accounts service. Generate the URL by using the wrapper's authorization URL method.
var scopes = 'user-read-private' 'user-read-email'redirectUri = ''clientId = '5fe01282e44241328a84e7c5cc169165'state = 'some-state-of-my-choice';// Setting credentials can be done in the wrapper's constructor, or using the API object's setters.var spotifyApi =redirectUri : redirectUriclientId : clientId;// Create the authorization URLvar authorizeURL = spotifyApi;//console;
The example below uses a hardcoded authorization code, retrieved from the Accounts service as described above.
var credentials =clientId : 'someClientId'clientSecret : 'someClientSecret'redirectUri : '';var spotifyApi = credentials;// The code that's returned as a query parameter to the redirect URIvar code = 'MQCbtKe23z7YzzS44KzZzZgjQa621hgSzHN';// Retrieve an access token and a refresh tokenspotifyApi;
Since the access token was set on the api object in the previous success callback, it's going to be used in future calls. As it was retrieved using the Authorization Code flow, it can also be refreshed unless it has expired.
// clientId, clientSecret and refreshToken has been set on the api object previous to this call.spotifyApi;
The Client Credential flow doesn't require the user to give permissions, so it's suitable for requests where the application just needs to authenticate itself. This is the case with for example retrieving a playlist. However, note that the access token cannot be refreshed, and that it isn't connected to a specific user.
var clientId = 'someClientId'clientSecret = 'someClientSecret';// Create the api object with the credentialsvar spotifyApi =clientId : clientIdclientSecret : clientSecret;// Retrieve an access token.spotifyApi;
Credentials are either set when constructing the API object or set after the object has been created using setters. They can be set all at once or one at a time.
Using setters, getters and resetters.
// Use setters to set all credentials one by onevar spotifyApi = ;spotifyApi;spotifyApi;spotifyApi;spotifyApi;spotifyApi;// Set all credentials at the same timespotifyApi;// Get the credentials one by oneconsole;console;console;console;console;// Get all credentialsconsole;// Reset the credentialsspotifyApi;spotifyApi;spotifyApi;spotifyApi;spotifyApi;spotifyApi;// Reset all credentials at the same timespotifyApi;
Using the constructor.
// Set necessary parts of the credentials on the constructorvar spotifyApi =clientId : 'myClientId'clientSecret : 'myClientSecret';// Get an access token and 'save' it using a setterspotifyApi;
// Set the credentials when making the requestvar spotifyApi =accessToken : 'njd9wng4d0ycwnn3g4d1jm30yig4d27iom5lg4d3';// Do search using the access tokenspotifyApi;
// Set the credentials when making the requestvar spotifyApi =accessToken : 'njd9wng4d0ycwnn3g4d1jm30yig4d27iom5lg4d3';// Get tracks in a playlistapi;
See something you think can be improved? Open an issue or clone the project and send a pull request with your changes.
You can run the unit tests executing
mocha and get a test coverage report running
mocha -r blanket -R html-cov > coverage.html.
encodeURIto encode the user's id. 'encodeURI' wasn't encoding characters like
#that were generating an invalid endpoint url. Thanks @jgranstrom for the PR.
superagentrequest library to support Node.JS and browsers. Thanks @SomeoneWeird for the PR to add it, and @erezny for reporting bugs.
getRecomendationsmethod causing client error response from the API when making the request. Thanks @kyv for reporting, and @Boberober and @JMPerez for providing fixes.