spotify-web-api-node

repository·master·Indexed 25 days ago

https://github.com/thelinmichael/spotify-web-api-node

A universal Node.js and browser wrapper for the Spotify Web API (v5.0.2). It provides high-level helper functions for music metadata, playback control, user library management, search, and personalization. The library supports Promises and callbacks, and implements OAuth 2.0 flows including Client Credentials, Authorization Code Grant, and Implicit Grant.

Tokens
3.3K
Snippets
9
Records
14
Agent score
83%

What's inside spotify-web-api-node

  1. Overview of Spotify Web API Node features

    master

    The library is a universal wrapper/client for the Spotify Web API that works in Node.js and the browser (via browserify, webpack, or rollup). It provides helper functions for:

    • Music Metadata: Fetching albums, artists, tracks, audio features, and analysis.
    • Profiles: Accessing user emails, product types, display names, and images.
    • Search: Searching for albums, artists, tracks, and playlists.
    • Playlist Manipulation: Creating, modifying, and managing tracks within playlists.
    • Your Music Library: Managing tracks and albums in a user's library.
    • Personalization: Retrieving top artists and tracks.
    • Browse: Accessing new releases, featured playlists, categories, and recommendations.
    • Player Control: Managing playback state, devices, volume, shuffle, repeat, and queue.
    • Follow: Following/unfollowing users, artists, and playlists.
    • Shows: Accessing podcast show information.
  2. Instantiate the SpotifyWebApi wrapper

    master

    To use the library, import spotify-web-api-node and create a new instance of SpotifyWebApi. You can pass credentials like clientId, clientSecret, and redirectUri directly into the constructor. These credentials are optional if you already have an access token.

    var SpotifyWebApi = require('spotify-web-api-node');
    
    // credentials are optional
    var spotifyApi = new SpotifyWebApi({
      clientId: 'fcecfc72172e4cd267473117a17cbd4d',
      clientSecret: 'a6338157c9bb5ac9c71924cb2940e1a7',
      redirectUri: 'http://www.example.com/callback'
    });
  3. Implement Client Credentials Flow

    master

    The Client Credentials flow is for application-only authentication (no user involvement). It is suitable for retrieving public data like playlists. Note that access tokens obtained this way cannot be refreshed and are not connected to a specific user.

    var clientId = 'someClientId',
      clientSecret = 'someClientSecret';
    
    var spotifyApi = new SpotifyWebApi({
      clientId: clientId,
      clientSecret: clientSecret
    });
    
    // Retrieve an access token
    spotifyApi.clientCredentialsGrant().then(
      function(data) {
        spotifyApi.setAccessToken(data.body['access_token']);
      },
      function(err) {
        console.log('Something went wrong when retrieving an access token', err);
      }
    );
  4. Run tutorial examples using an existing access token

    master

    Once you have obtained an access_token, you can run the various tutorial examples by providing the token via the SPOTIFY_ACCESS_TOKEN environment variable.

    Set the environment variable and then run the desired example script. For example, to get information about the current user:

    export SPOTIFY_ACCESS_TOKEN="<Token content here>"
    node examples/tutorial/01-basics/01-get-info-about-current-user.js
  5. Obtain a Spotify access token via the tutorial script

    master

    To get an access_token for testing, you can use the provided tutorial script.

    1. Create a Spotify application at https://developer.spotify.com/my-applications to obtain a client_id and client_secret.
    2. Important: In your Spotify application settings, whitelist http://localhost:8888/callback as a valid redirectUri.
    3. Run the following commands to install dependencies and execute the token retrieval script:
    git clone <this repo url>
    cd spotify-web-api-node
    npm install
    npm install express
    node examples/tutorial/00-get-access-token.js "<Client ID>" "<Client Secret>"
    1. Visit http://localhost:8888/login in your browser to complete the authentication flow and receive your token.
    node examples/tutorial/00-get-access-token.js "<Client ID>" "<Client Secret>"
  6. Implement Implicit Grant Flow

    master

    The Implicit Grant flow is for completely client-side applications. It does not expose the clientSecret and does not return refresh tokens. You must re-authenticate the user every time the token expires.

    var scopes = ['user-read-private', 'user-read-email'],
      redirectUri = 'https://example.com/callback',
      clientId = '5fe01282e44241328a84e7c5cc169165',
      state = 'some-state-of-my-choice',
      showDialog = true,
      responseType = 'token';
    
    var spotifyApi = new SpotifyWebApi({
      redirectUri: redirectUri,
      clientId: clientId
    });
    
    // Create the authorization URL
    var authorizeURL = spotifyApi.createAuthorizeURL(
      scopes,
      state,
      showDialog,
      responseType
    );
    
    // When the client returns, pass the token directly
    var accessTokenFromHash = 'MQCbtKe23z7YzzS44KzZgjQa621hgSzHN';
    spotifyApi.setAccessToken(accessTokenFromHash);
  7. Make API requests using Promises or Callbacks

    master

    The wrapper supports both Promises and traditional callbacks.

    Using Promises: Provide a success callback and an error callback to the .then() method. The response object contains body, headers, and statusCode.

    Using Callbacks: If you use a callback, you must provide an options object as the second argument, even if it is empty ({}).

    Many methods accept an options object for pagination, such as limit and offset.

    // Using Promises
    spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE').then(
      function(data) {
        console.log('Artist albums', data.body);
      },
      function(err) {
        console.error(err);
      }
    );
    
    // Using Callbacks (options object is REQUIRED)
    spotifyApi.getArtistAlbums(
      '43ZHCT0cAZBISjO8DG9PnE',
      { limit: 10, offset: 20 },
      function(err, data) {
        if (err) {
          console.error('Something went wrong!');
        } else {
          console.log(data.body);
        }
      }
    );
  8. Implement Authorization Code Flow

    master

    The Authorization Code flow is used when you need user permissions.

    1. Generate Authorization URL: Use createAuthorizeURL(scopes, state) to direct the user to Spotify's Accounts service.
    2. Retrieve Access Token: After the user authorizes, they are redirected to your redirectUri with a code query parameter. Use authorizationCodeGrant(code) to exchange this code for an access token and a refresh token.
    3. Use Tokens: Set the tokens using setAccessToken(token) and setRefreshToken(token) so they are used in subsequent calls.
    var scopes = ['user-read-private', 'user-read-email'],
      redirectUri = 'https://example.com/callback',
      clientId = '5fe01282e44241328a84e7c5cc169165',
      state = 'some-state-of-my-choice';
    
    var spotifyApi = new SpotifyWebApi({
      redirectUri: redirectUri,
      clientId: clientId
    });
    
    // 1. Create the authorization URL
    var authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);
    
    // 2. Exchange the code (retrieved from redirect) for tokens
    var code = 'MQCbtKe23z7YzzS44KzZgjQa621hgSzHN';
    spotifyApi.authorizationCodeGrant(code).then(
      function(data) {
        // 3. Set the tokens for future use
        spotifyApi.setAccessToken(data.body['access_token']);
        spotifyApi.setRefreshToken(data.body['refresh_token']);
      },
      function(err) {
        console.log('Something went wrong!', err);
      }
    );
  9. Authenticate with the Spotify Web API

    master

    All methods in the library require authentication. You can use one of the following OAuth 2.0 flows depending on your use case:

    • Client credentials flow: For application-only authentication (no user context).
    • Authorization code grant: For user-signed authentication (accessing user-specific data).
    • Implicit Grant Flow: For client-side authentication.
  10. Manage credentials with setters and getters

    master

    You can manage credentials on an existing SpotifyWebApi instance using individual setters, a bulk setter, or by resetting them.

    Bulk Set: setCredentials({ accessToken, refreshToken, redirectUri, clientId, clientSecret }) Individual Setters: setAccessToken(), setRefreshToken(), setRedirectURI(), setClientId(), setClientSecret() Getters: getAccessToken(), getRefreshToken(), getRedirectURI(), getClientId(), getClientSecret(), getCredentials() Resetters: resetAccessToken(), resetRefreshToken(), resetRedirectURI(), resetClientId(), resetClientSecret(), resetCredentials()

    var spotifyApi = new SpotifyWebApi();
    
    // Set all credentials at the same time
    spotifyApi.setCredentials({
      accessToken: 'myAccessToken',
      refreshToken: 'myRefreshToken',
      redirectUri: 'http://www.example.com/test-callback',
      clientId: 'myClientId',
      clientSecret: 'myClientSecret'
    });
    
    // Get credentials
    console.log('The access token is ' + spotifyApi.getAccessToken());
    
    // Reset all credentials
    spotifyApi.resetCredentials();
  11. Understand the API response and error format

    master

    All successful requests return an object containing the response metadata and the actual data from Spotify:

    {
      "body" : { /* Spotify API response data */ },
      "headers" : { /* HTTP response headers */ },
      "statusCode" : 200
    }

    Errors follow the same structure but include a human-readable message field, which is useful because Spotify returns different error object types depending on the endpoint.