Git Product home page Git Product logo

spotify-web-api-js's Introduction

Spotify Web API JS Build Status Coverage Status Greenkeeper badge

This is a lightweight wrapper for the Spotify Web API (2.6kB gzipped + compressed). It includes helper functions for all Spotify's endpoints, such as fetching metadata (search and look-up of albums, artists, tracks, playlists, new releases, podcasts) and user's information (follow users, artists and playlists, and saved tracks management).

It doesn't have any dependencies and supports callbacks and promises. It is intended to be run on a browser, but if you want to use Node.JS to make the requests, please check spotify-web-api-node.

A list of selected wrappers for different languages and environments is available on the Developer site's Libraries page.

The wrapper includes helper functions to do the following:

Music and Podcast metadata

  • Albums, artists, tracks and playlists
  • Audio features and audio analysis for tracks
  • Albums for a specific artist
  • Top tracks for a specific artist
  • Artists similar to a specific artist
  • Shows and episodes (podcasts)

Profiles

  • User's emails, product type, display name, birthdate, image

Search

  • Albums, artists, tracks, playlists, shows, and episodes

Playlist Management

  • 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
  • Upload custom playlist cover image

User's Library

  • Add, remove, and get tracks on a user's library
  • Check if a track is in the signed in user's library
  • Add, remove, and get shows (podcasts) on a user's library

Personalization

  • Get a user’s top artists and tracks based on calculated affinity
  • Get current user’s recently played tracks

Browse

  • 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

  • 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

Player

  • Get a user's available devices
  • Get information about the user's current playback
  • Get the user's currently playing track
  • Transfer a user's playback
  • Start/Resume a user's playback
  • Pause a user's playback
  • Skip user's playback to next track
  • Skip user's playback to previous track
  • Seek to position in currently playing track
  • Set repeat mode on user's playback
  • Set volume for user's playback
  • Toggle shuffle for user's playback
  • Queue a track or an episode

Installation

Install via node (since the requests are made using XMLHttpRequest, you will need a tool like Browserify to run this on a browser):

$ npm install -S spotify-web-api-js

Then, in your javascript file

var Spotify = require('spotify-web-api-js');
var s = new Spotify();
//s.searchTracks()...

or by making a copy of the src/spotify-web-api.js file

Usage

We recommend you have a look at the documentation to get an overview of the supported .

The wrapper supports callback functions, as well as Promises (you can also use a polyfill), and Promises/A+ libraries such as Q and when.

First, instantiate the wrapper.

var spotifyApi = new SpotifyWebApi();

If you have an access token, you can set it doing:

spotifyApi.setAccessToken('<here_your_access_token>');

When you set an access token, it will be used for signing your requests. An access token is required for all endpoints.

If you want to use a Promises/A+ library, you can set it:

spotifyApi.setPromiseImplementation(Q);

Here you see how to get basic information using a function like getArtistAlbums:

// get Elvis' albums, passing a callback. When a callback is passed, no Promise is returned
spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', function (err, data) {
  if (err) console.error(err);
  else console.log('Artist albums', data);
});

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

The promises also expose an abort method that aborts the XMLHttpRequest. This is useful to cancel requests that were made earlier and could be resolved out-of-sync:

var prev = null;

function onUserInput(queryTerm) {
  // abort previous request, if any
  if (prev !== null) {
    prev.abort();
  }

  // store the current promise in case we need to abort it
  prev = spotifyApi.searchTracks(queryTerm, { limit: 5 });
  prev.then(
    function (data) {
      // clean the promise so it doesn't call abort
      prev = null;

      // ...render list of search results...
    },
    function (err) {
      console.error(err);
    }
  );
}

The functions that fetch data from the API support also an optional JSON object with a set of options, such as the ones regarding pagination. These options will be sent as query parameters:

// passing a callback - get Elvis' albums in range [20...29]
spotifyApi.getArtistAlbums(
  '43ZHCT0cAZBISjO8DG9PnE',
  { limit: 10, offset: 20 },
  function (err, data) {
    if (err) console.error(err);
    else console.log('Artist albums', data);
  }
);

// using Promises through Promise, Q or when - get Elvis' albums in range [20...29]
spotifyApi
  .getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', { limit: 10, offset: 20 })
  .then(
    function (data) {
      console.log('Album information', data);
    },
    function (err) {
      console.error(err);
    }
  );

More examples

Note: The following examples use Promises/Q/when as the return object.

Here you can see more examples of the usage of this wrapper:

// get multiple albums
spotifyApi.getAlbums(['5U4W9E5WsYb2jUQWePT8Xm', '3KyVcddATClQKIdtaap4bV']).then(
  function (data) {
    console.log('Albums information', data);
  },
  function (err) {
    console.error(err);
  }
);

// get an artists
spotifyApi.getArtist('2hazSY4Ef3aB9ATXW7F5w3').then(
  function (data) {
    console.log('Artist information', data);
  },
  function (err) {
    console.error(err);
  }
);

// get multiple artists
spotifyApi
  .getArtists(['2hazSY4Ef3aB9ATXW7F5w3', '6J6yx1t3nwIDyPXk5xa7O8'])
  .then(
    function (data) {
      console.log('Artists information', data);
    },
    function (err) {
      console.error(err);
    }
  );

// get albums by a certain artist
spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE').then(
  function (data) {
    console.log('Artist albums', data);
  },
  function (err) {
    console.error(err);
  }
);

// search tracks whose name, album or artist contains 'Love'
spotifyApi.searchTracks('Love').then(
  function (data) {
    console.log('Search by "Love"', data);
  },
  function (err) {
    console.error(err);
  }
);

// search artists whose name contains 'Love'
spotifyApi.searchArtists('Love').then(
  function (data) {
    console.log('Search artists by "Love"', data);
  },
  function (err) {
    console.error(err);
  }
);

// search tracks whose artist's name contains 'Love'
spotifyApi.searchTracks('artist:Love').then(
  function (data) {
    console.log('Search tracks by "Love" in the artist name', data);
  },
  function (err) {
    console.error(err);
  }
);

Nesting calls

When you need to make multiple calls to get some dataset, you can take advantage of the Promises to get a cleaner code:

// track detail information for album tracks
spotifyApi
  .getAlbum('5U4W9E5WsYb2jUQWePT8Xm')
  .then(function (data) {
    return data.tracks.map(function (t) {
      return t.id;
    });
  })
  .then(function (trackIds) {
    return spotifyApi.getTracks(trackIds);
  })
  .then(function (tracksInfo) {
    console.log(tracksInfo);
  })
  .catch(function (error) {
    console.error(error);
  });

// album detail for the first 10 Elvis' albums
spotifyApi
  .getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', { limit: 10 })
  .then(function (data) {
    return data.albums.map(function (a) {
      return a.id;
    });
  })
  .then(function (albums) {
    return spotifyApi.getAlbums(albums);
  })
  .then(function (data) {
    console.log(data);
  });

Getting user's information

In order to get user's information you need to request a user-signed access token, from either the Implicit Grant or Authorization Code flow. Say for instance you want to get user's playlists. Once you get an access token, set it and fetch the data:

// get an access token
...

// set it in the wrapper
var spotifyApi = new SpotifyWebApi();
spotifyApi.setAccessToken('<here_your_access_token>');
spotifyApi.getUserPlaylists('jmperezperez')
  .then(function(data) {
    console.log('User playlists', data);
  }, function(err) {
    console.error(err);
  });

spotifyApi.getPlaylist('4vHIKV7j4QcZwgzGQcZg1x')
  .then(function(data) {
    console.log('User playlist', data);
  }, function(err) {
    console.error(err);
  });

Some functions don't need to receive the user's id as a parameter, and will use the user's information from the access token:

var spotifyApi = new SpotifyWebApi();
spotifyApi.setAccessToken('<here_your_access_token>');
spotifyApi
  .getUserPlaylists() // note that we don't pass a user id
  .then(
    function (data) {
      console.log('User playlists', data);
    },
    function (err) {
      console.error(err);
    }
  );

Integrated Typescript Typings

Get great code completion for this package using the integrated typescript typings. It includes the complete typings of the Spotify Web Api too, so you'll know both how to the navigate the API as well as the response you are getting.

Typings Example

When bundling the library

If you are bundling spotify-web-api-js using e.g. webpack you can include the library and the typings into a typescript file like this:

import SpotifyWebApi from 'spotify-web-api-js';

let spotify = new SpotifyWebApi();

When using the library globally

If you are using the library globally, for example including directly from index.html, include the typings in the top of your typescript file. Typescript will then assume the library is already present globally. Adjust the path to node_modules.

/// <reference path="../node_modules/spotify-web-api-js/src/typings/spotify-web-api.d.ts" />

let spotify = new SpotifyWebApi();

Running tests

In order to run the tests, run:

$ npm test

If you want to check out the coverage, run:

$ npm run test:coverage

spotify-web-api-js's People

Contributors

adamgrieger avatar amelialaundy avatar asmitter avatar caitlin-tibbetts avatar cassioscabral avatar cloughney avatar csantiago132 avatar danmactough avatar davejm avatar dependabot[bot] avatar gravitypersists avatar greenkeeper[bot] avatar hughrawlinson avatar ikantspelgud avatar jdnvn avatar jmfortunatojr avatar jmperez avatar junebugfix avatar longears avatar lrholmes avatar manan2501 avatar pduchesne avatar peter-lavigne avatar skovmand avatar thelinmichael avatar ulyssem avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

spotify-web-api-js's Issues

Is there a way to send URI through the body instead of URI ?

Hi there, I'm using this wrapper and it's being great. I'm having a problem when trying to use the addTracksToPlaylist with 100 URI, the limit set by Spotify. I got a 414 error, request URI too long. I can see that replaceTracksInPlaylist uses postData: {uris: uris} instead of params: {uris: uris } like addTracksToPlaylist. So I was wondering if addTracksToPlaylist couldn't use the body as welll instead of params.

replaceTracksInPlaylist it's working fine.

My case is that I'm reordering my playlist using replaceTracksInPlaylist to replace the first 100 and iterate over chunks of 100 more tracks to add into the playlist. But eventually got this error.

Maybe I can help making a PR for that, just asking before doing anything.

Thanks

Can't add track to playlist, "This request requires user authentication.", but access token is set.

UPDATE: I realize now that I need to set the scope to 'playlist-modify-public'. I am temporarily using DHC to generate my Access Tokens based on my own Client id and secret. Is this the correct way to add in the scopes:
https://i.gyazo.com/0cef9796623315f670eb2f2ba63d557c.png
?

Sending this POST request successfully generates an Access Token but I still cannot add tracks to the playlist.

/UPDATE


https://i.gyazo.com/0984a525034373e9783ac52cf8ffbe9b.png

Here's my function:

function addTrack(){
	var spotifyApi = new SpotifyWebApi();
	spotifyApi.setAccessToken(accesstoken);
	spotifyApi.addTracksToPlaylist('12127460245','1qO3XzZcwh74JaZ2aQfBNc',songid)
	  .then(function(data) {
		console.log('insert track',data);
	  }, function(err) {
		console.error(err);
	  });
}

I know the Access Token works because I used the getPlaylist example and it successfully shows me info about it:

function getInfo(){
	var spotifyApi = new SpotifyWebApi();
	spotifyApi.setAccessToken(accesstoken);
	spotifyApi.getPlaylist('12127460245','1qO3XzZcwh74JaZ2aQfBNc')
	  .then(function(data) {
		console.log('User playlists', data);
	  }, function(err) {
		console.error(err);
	  });
}

The Spotify application where I get my client id and secret was created by the account that owns that playlist, so I wouldn't think that should be a problem. Do I need to open up the playlist to add tracks from anyone or something?

Release on npm not up to date

Thanks for a great library. However, running "npm install" installs version 0.15.0, but not the most recent release. Are there any issues that prevent uploading newer releases to npmjs?

remove userId from Create playlist method

Me again, the changes just released to update the playlist endpoints as per the new Spotify URIs (https://developer.spotify.com/community/news/2018/06/12/changes-to-playlist-uris/)
https://github.com/JMPerez/spotify-web-api-js/pull/105https://github.com/JMPerez/spotify-web-api-js/releases/tag/v1.1.0 don't include an update for Creating a playlist without the userId:

POST /v1/me/playlists

I'll create a PR for this URI too, to remove the userId from the request.

Refresh token

Hey,
I've been working with this API a bit and I really like it. I have one question. As far as I know, normally you get an authorization code and a refresh code (at least it is like that in my Java application, where it generates the new codes automatically). Here I have to generate a new access code often by myself because else the "access token is invalid" (401).
Am I doing something wrong or is refreshing the codes not possible with JavaScript?
Thank you,
Adam

Maintainers wanted

We would like to get contributors who would like to maintain and evolve this library

As the main maintainer of this library, I have been busy lately with other projects and I will not able to keep this library up to date for the foreseeable future. I would love to get support from other contributors that have ideas on how to move forward the library so it's still relevant and useful for developers.

If you are interested in maintaining the library, please add a comment to this issue.

An example

At the moment I'm building a Sonos web-controller and I'm looking for a method to use the Spotify API via HTML/JS. After hours of searching I found your web-api, but I can't figure out how to use it via javascript. Is it possible you give me an example of an web-app running with this api (including the HTML, JS files)?

[Question] Getting full playlist object

Hi! Sorry if this is covered in the README, but I can't find it. I'm getting a playlist like so:

      const { tracks } = await spotify.getPlaylist(owner.id, id);

But tracks only has an href and a length. How can I get the track ids?

An in-range update of sinon is breaking the build 🚨

Version 2.2.0 of sinon just got published.

Branch Build failing 🚨
Dependency sinon
Current Version 2.1.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As sinon is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪

Status Details - ❌ **continuous-integration/travis-ci/push** The Travis CI build failed [Details](https://travis-ci.org/JMPerez/spotify-web-api-js/builds/227862815?utm_source=github_status&utm_medium=notification),- ✅ **coverage/coveralls** First build on greenkeeper/sinon-2.2.0 at 97.993% [Details](https://coveralls.io/builds/11328338)

Commits

The new version differs by 40 commits0.

  • f7ff840 Update docs/changelog.md and set new release id in docs/_config.yml
  • 59a7a34 Add release documentation for v2.2.0
  • 37676e8 2.2.0
  • b35d217 Update Changelog.txt and AUTHORS for new release
  • 0127365 Merge pull request #1363 from greena13/master
  • 4fe0a73 Flatten structure of getWindowLocation()
  • 38e3ec4 Fix matchers.md in v1.17.6 and v1.17.7 releases. (#1379)
  • 3d4bc16 Merge pull request #1364 from blacksun1/add-custom-promise
  • 7ac4f60 Fixes for pull request comments
  • 25bfde0 Added docs for usingPromise
  • 0a3518f Added usingPromise method to sandbox.
  • 17edad7 Added usingPromise method to stub.
  • c5bc9ab Merge pull request #1359 from kevincennis/kce/fix-1066
  • c633202 Merge pull request #1320 from ashirley/master
  • 17c2639 Merge pull request #1366 from GProst/master

There are 40 commits in total.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

iPhone 4 Error when calling getUserPlaylists

Hi,

I'm using the Spotify Web API to do the following function call.

spotifyApi.getUserPlaylists($scope.user.id)
.then(function(data) {
(err) {
console.error(err);
ga('send','event','error','spotifyLoadFailed');
});

And getting the following error.
Error: 'null' is not an object (evaluating 'spotifyApi.getUserPlaylists($scope.user.id)
.then')

It works on iPhone 5, 6 and all Android devices I've tested, yet, iPhone 4 says the data object returned is null.

getUserPlaylists doesn't return the correct number of playlists every time

The call getUserPlaylists, which I've modified a tiny bit, doesn't return the correct number of playlists everytime. I have 11 playlists and sometimes it returns all 11 and sometimes it returns just 6 of them.

Constr.prototype.getUserPlaylists = function(userId, options, callback) {
var requestData = {
url: _baseUri + '/users/' + userId + '/playlists' + '?offset=' + options.offset + '&limit=50'
};
return _checkParamsAndPerformRequest(requestData, options, callback);
};

screen shot 2016-01-24 at 9 57 23 am

I should note that I haven't updated this file with the Github repo is a very long time (about 1 year ago) and this error started occurring for me about 4-5 months ago and has been happening pretty consistently.

When it doesn't load them all

screen shot 2016-01-24 at 10 00 04 am

screen shot 2016-01-24 at 10 00 53 am

When it does load them all
screen shot 2016-01-24 at 10 06 13 am
screen shot 2016-01-24 at 10 06 29 am
screen shot 2016-01-24 at 10 06 37 am

Promise abort not working

Trying to implement the search functionalities with the promise implementation i run into some trouble.

My implementation is as written in the documentation. I've initialized the promises with the Q library spotifyApi.setPromiseImplementation(Q); . Following the example from the documentation:

var prev = null;

function onUserInput(queryTerm) {

  // abort previous request, if any
  if (prev !== null) {
    prev.abort();
  }

  // store the current promise in case we need to abort it
  prev = spotifyApi.search(queryTerm, ['album', 'artist', 'playlist', 'track'], {'limit': 20, 'offset': 0})
    .then(function(data) {

      // clean the promise so it doesn't call abort
      prev = null;

      // ...render list of search results...

    }, function(err) {
      console.error(err);
    });
}

Running this, i receive the error that the abort function doesn't exist. prev.abort is not a function.

As I see while debugging the script, the abort function is wrapped in the return value, but accessing the object which is stored in prev isn‘t possible besäuselt the abort function isn't represented anymore.

Is there anything I'm missing out?

Remove callback parameter

The functions in the library support two ways of getting the result of the request back. One of them is through a promise that is returned in the call, and the other one is a callback parameter that gets called with the data and eventual error.

The support for Promise is quite widespread at the moment and additions to the language like async/await, which allows a concise syntax around Promises, make this option the preferred one.

The idea is to get through some of the packages and projects that depend on the library and analyze how frequently they use the callback function before getting rid of it.

Expose a way to cancel a request

In a scenario such as searching for tracks using an input, it should be possible to cancel previous requests with every new key stroke.

Even though the Promise object doesn't support cancelation, we could pass a parameter similar to the timeout param that Angular uses for their $http service (see http://odetocode.com/blogs/scott/archive/2014/04/24/canceling-http-requests-in-angularjs.aspx), extending the returned Promise object (similar to jQuery's $.ajax() returned object) or returning both a Promise and a function that can be called to abort it (see https://github.com/sathify/angular-abortable-requests).

There are some approaches explained on https://github.com/then/promise#extending-promises

Help!

Hey

Sorry to bother you here, but i cant get an answer from the web-api at Spotify and ive got lots of labels getting aggravated with me!

Im getting 502 errors making this request

var options = {
    
                url: 'https://api.spotify.com/v1/users/' + splitUrl[4] + '/playlists/' + splitUrl[6] + '/tracks',
                headers: {
                    'Authorization': 'Bearer ' + globalToken
                },
                json: true
            }```
globalToken is a fresh Access Token returned form a refresh_token authorization call using the Authorization Code flow, this is all working fine. This had been working fine until yesterday evening.
Now im getting 502 errors in response to these calls.

I have tried refreshing the refresh token and even using a completely different Login to get client secret etc (and new refresh token for those credentials), but im still getting the same error

i cant see any complaints elsewhere online about the API so im assuming its an account issue, but its affecting the 100 labels that own the playlist i maintain and a fairly sizable community

Again, sorry to trouble you, last resort! x

Is there any support for OAuth?

Hey there, thanks for putting this together. I was wondering if there was any support provided for OAuth? I had a look through the source code and documentation, and it appears there isn't. Maybe I'm missing something?

Cheers,

Simon

Change /next from PUT to POST

Whenever I try to change execute the /next method, it gives me the 405 not allowed method. I found out it was because the method of the request was PUT and not POST. This little change was the solution locally for me :)

Latest type definition breaks typescript compilation

My typescript code uses the api as follows :

import * as SpotifyWebApi from 'spotify-web-api-js';

let spotifyApi: SpotifyWebApi.SpotifyWebApiJs;

This works fine with 1.1.0 .
Since 1.1.1 , this fails with Namespace '".../spotify-web-api"' has no exported member 'SpotifyWebApiJs' .

I could not find a way to work with the new type file.

Missing required parameter: client_id

Hi!

I'm facing an issue that I don't understand!
I am developing a react-native (js) app which try to access Spotify api using the Implicit Grant Flow.

Here is my method to get the access token:

async function getTokenFromAPI() {
    try {
        var params = {
            client_id: '<client_id>',
            response_type: 'token',
            redirect_uri: 'http://localhost:8888/callback'
        };

        var esc = encodeURIComponent;
        var query = Object.keys(params)
            .map(k => `${esc(k)}=${esc(params[k])}`)
            .join('&');

        fetch('https://accounts.spotify.com/authorize', query).then(function (response) {
            console.log('response, ' + JSON.stringify(response));
            return response;
        })
    } catch(error) {
        console.error(error);
    }
}

but It answers that:
Missing required parameter: client_id

I also used Postman to check if my request is good and I get the same response...

Is there something wrong? On there doc they tell that it is a GET method with only 3 parameters..

Thank you in advance for any workaround!

Add support for auto pagination when fetching results

Hi, I'm currently working on a project where this would be useful. For each method that fetches paginated results, it'd be nice if there existed a convenience method that fetched all the pages in parallel.

Take getMySavedTracks for example, which has a maxinum number of 50 results per page. We'd have a method called:

getAllMySavedTracks(maxPages, optionsEach, callbackEach, callback)

Which fetches the first page, checks the total items, and creates requests if needed for each page using a limit and offset. The parameters could work as follows:

  • maxPages: The maximum number of pages to get. By default it would request all of them (unless there's a rate limit for pages Spotify imposes that I don't know of).
  • optionsEach: The object for options to send in each call to getMySavedTracks. Passing limit and offset would have no effect since that's automatically determined per each page request in this method.
  • callbackEach: A callback function for each page request i.e. each call to getMySavedTracks. The callback function receives the error and value parameters of course.
  • callback: A callback function that fires after completion of all requests. Just going off of how Promise.all() works, you could pass it the array of values from all the resolved getMySavedTracks promises in the second parameter, and If any of the page requests fail, you only get the value of the promise that was rejected in the first parameter.

Currently, I do this on my own and it gets messy fast. Putting it in the API wrapper could save developers some headaches. If the paging could somehow be generalized, you'd end up with several clean convenience methods. The main usecase for this is for when dealing with a user who has a large music collection (personally I hoard and create too many playlists).

Let me know what you think. I'm totally willing to implement this, as I already have existing code I could refine to work within the wrapper.

latest release will have broken typescript integrations

Release 1.1.0 didnt update the typescript bindings so the code doesn't require userId anymore but the bindings don't reflect that meaning that anyone writing typescript will still be calling the functions with the userId and it won't create the URI correctly
screen shot 2018-08-24 at 8 30 55 am

I can do a PR too

spotifyApi.setVolume TypeError

Getting this error trying to use the setVolume command.

I've tried running it with:

spotifyApi.setVolume(1, "", function(){
	console.log("")
});

and
spotifyApi.setVolume(1);

but i get this error:

if ('device_id' in options) {
                    ^

TypeError: Cannot use 'in' operator to search for 'device_id' in undefined
    at Constr.setVolume (H:\My Documents\NodeJS\SpotifyVolumeTalkingDiscordJS\node_modules\spotify-web-api-js\src\spotify-web-api.js:1647:21)

Promises

Hey : )

are these compatible with promises?

[Question] Struggling getting play and pausing working

Hi
I'm having trouble getting .play() and .pause() working. I'm using an icon as a button to playwhatever track is current paused on the users current device. I am doing this using React. I have managed to get this api working fine so far until this. Here is the code for my button (it works fine for calling other functions)
<span onClick={() => spotifyApi.play()}> <i class="material-icons" style={{fontSize: 48}}>play_arrow</i> </span>

When I then click on the button I get the following error:

TypeError: right-hand side of 'in' should be an object, got undefined

After looking at the documentation of this library and the spotify api docs it seems that the device Id is optional and that if I call .play() it will just unpuase the music on whatever the active device is?
I tried passing the device object to .play() from getMyCurrentPlaybackState and this didn't give me an error but didn't actually unpause the music.

Any help would be appreciated.

Promise.defer is not part of the Promises/A+ spec

.defer is tested to determine if the promise implementation is valid within this utility, but .defer is an extension provided by some libraries, like Q. Therefore the error message is extremely misleading.

for example, using the native Promise provided by ES2015 would fail in Firefox and Safari:

spotifyApi.setPromiseImplementation(Promise);
// Throws saying not A+ compatible

.defer appears to be still in chrome, but is not defined in Safari or Firefox. It is deprecated and not on a standards track: https://bugzilla.mozilla.org/show_bug.cgi?id=1034599

Remove support for bower

It seems that bower is not used so much as when this library started. Although it doesn't introduce much complexity, it's another bit of code that needs to be maintained.

I suspect most people install the package through npm, but just in case I want to create the issue to get 👍 and 👎that can help me make an informed decision.

Post 10000 result 502 - Bad Gateway

Hey

Thanks for your promise-throttle btw its awesome : )

Im just using request-promise with promise throttle, so this isnt an issue with your library per se, but ive searched around and found a few unanswered queries on stack overflow about this issue, with people using spotify-web-api-js. Im hoping you can help?

Getting a 502-Bad Gatway with an offset larger than 10000, the API doc sais the limit should be 100000

Couldn't find an answer elsewhere, thanks in advance

Modify createPlaylist method to use the new api route.

It seems like Spotify updated their api route for creating a new playlist for the current user.
spotify-web-api.js route:
-> https://api.spotify.com/v1/me/playlists
current developer console route (https://developer.spotify.com/console/post-playlists/):
-> https://api.spotify.com/v1/playlists
beta web api reference route (https://developer.spotify.com/documentation/web-api/reference-beta/#endpoint-create-playlist):
-> https://api.spotify.com/v1/users/{user_id}/playlists

I got the latter one working by doing a manual request, which requires you to first grab the current user's id with the getMe() method.

Hi, how can I get album instead of tracks?

Hi Jose Manuel ,
this website is using Spotify-web-api-js , how can I make it do albums instead of tracks?
for example ,
Michael Jackson - Off the Wall
Off the Wall is an album and a track of the same album
this website is giving me the track uri
spotify:track:3zYpRGnnoegSpt3SguSo3W
but I would like to get the album uri instead
spotify:album:2ZytN2cY4Zjrr9ukb2rqTP
How can I achieve this task?

thanks

Browserify cannot find module 'spotify-web-api-js'

Is Browserify actually supported? I get the following error on bundle:

Error: Cannot find module 'spotify-web-api-js' from '/Users/Joakim/web/nattliv/resources/assets/js/app/music'

Seems like Browserify can't find the spotify-web-api-js module in node_modules. When I manually add the main attribute in package.json to tell it where the script resides, I get the this error:

Uncaught TypeError: object is not a function

when doing:

var Spotify = require('spotify-web-api-js');
var api = new Spotify();

console.log(api);

Instructions for Ionic 2/3 typescript app

Im a newbie to typescript and am trying to add this to my Ionic 2 app. Can someone give me step by step instructions on how to add this? I tried:

npm install -S spotify-web-api-js
then browserify spotify-web-api.js -o spotifybundle.js (on the file in the node_modules folder)
then add spotifybundle.js to my index.html
I also tried doing a typings install with all the *.d.ts files provided and still cant get it working (I get "SpotifyWebApi is not defined" when I try to make the call var spotify = new SpotifyWebApi() ).

thanks in advance.

P.S. I am using this instead of the angular-spotify version bc it seems more frequently updated.

Get a user's songs from Your Music

Is it possible to get a user's songs from Your Music? In the desktop app, that is normally on the left in the middle under Your Music.

Search suggestion

Hi, just a suggestion: wouldn't be enough to have a single search method and just pass the types in the options object? In my app I search for tracks, albums and artists and it just looks kinda strange in the code that I use searchTracks when the result back contains all three types.

regards, Emil

Link to documentation broken

The link in the usage section of the readme in the sentance:
"We recommend you have a look at the documentation to get an overview of the supported ."

Is broken.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.