Spotify Web API Node
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.
Table of contents
The library includes helper functions to do the following:
- Albums, artists, and tracks
- Audio features and analysis for tracks
- Albums for a specific artist
- Top tracks for a specific artist
- Artists similar to a specific artist
- User's emails, product type, display name, birthdate, image
- Albums, artists, tracks, and playlists
- Get a user's playlists
- Create playlists
- Change playlist details
- Add tracks to a playlist
- Remove tracks from a playlist
- Replace tracks in a playlist
- Reorder tracks in a playlist
Your Music library
- Add, remove, and get tracks and albums that are in the signed in user's Your Music library
- Check if a track or album is in the signed in user's Your Music library
- Get a user’s top artists and tracks based on calculated affinity
- Get New Releases
- Get Featured Playlists
- Get a List of Categories
- Get a Category
- Get a Category's Playlists
- Get recommendations based on seeds
- Get available genre seeds
- Follow and unfollow users
- Follow and unfollow artists
- Check if the logged in user follows a user or artist
- Follow a playlist
- Unfollow a playlist
- Get followed artists
- Check if users are following a Playlist
- Get a user's available devices
- Get information about the user's current playback
- Get current user’s recently played tracks
- Transfer a user's playback
- Resume a user's playback
- Skip a user's playback to next track
- Skip a user's playback to previous track
- Set a user's shuffle mode
- Set a user's repeat mode
- Set volume
- Seek playback to a given position
All methods require authentication, which can be done using these flows:
$ 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;
Response body, statuscode, and headers
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.
Example of a response
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 */spotifyApi;/* Get Audio Analysis for a Track */spotifyApi;/* Get Audio Features for several tracks */spotifyApi;/** 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 = 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;// Upload a custom playlist cover imagespotifyApi;// 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;/* Player */// Get information about current playing song for signed in userspotifyApi;/* 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 is required for all requests to the Spotify API. 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.
Important: If you are writing a universal/isomorphic web app using this library, you will not be able to use those methods that send a client secret to the Spotify authorization service. Client secrets should be kept server-side and not exposed. Never include your client secret in the public JS served to the browser.
Authorization code flow
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.
// clientId, clientSecret and refreshToken has been set on the api object previous to this call.spotifyApi;
Client Credential flow
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
npm test and get a test coverage report running
npm test -- --coverage.