Spotify preview API search track and album
I am currently trying to migrate a Spotify App to the new 1.0 version of the api.
I am having issues with search. I want to search the catalog with a search string and get all the track info, artist names and album names back from the search results. However, it seems like Search does not include album names (only URI:s) in the results.
Do I have to load all album names for all resulting tracks asynchronously afterwards? I want to avoid this if possible.
I am searching like this
var search = Search.search(searchString);
search.tracks.snapshot().done(function(snapshot) {
var results = snapshot.toArray();
// no album names in the results tracks
}).fail(function() {
console.error('Error retrieving snapshot');
});
In the API 1.0 some data is not retrieved automatically. This means that, ideally, you will only fetch the data you need, decreasing data traffic and improving performance. The downside is that you will need to compose that array of tracks plus the album name yourself, fetching the data in an async way.
For each track you want to fetch the name of its album. This is how you would do it:
var maxTracks = 15;
var search = Search.search(searchString);
search.tracks.snapshot(0, maxTracks).done(function(snapshot) {
snapshot.toArray().forEach(function(result) {
result.album.load('name').done(function(album) {
// here you have access to the album.name attribute
});
});
}).fail(function() {
console.error('Error retrieving snapshot');
});
The problem with that approach is that you will the data in a different order than the one in which the tracks appear. If you need to keep the order you can use the Promise
object:
var maxTracks = 15;
var search = Search.search(searchString);
search.tracks.snapshot(0, maxTracks).done(function(snapshot) {
var promises = [];
snapshot.toArray().forEach(function(result) {
promises.push(result.album.load('name'));
});
models.Promise.join(promises)
.done(function(albums) { console.log('Loaded all albums.', albums); })
.fail(function(albums) { console.log('Failed to load at least one album.', albums); });
}).fail(function() {
console.error('Error retrieving snapshot');
});
Using an array of Promise
s will keep the same order as the tracks.
上一篇: Spotify元数据api查找表单
下一篇: Spotify预览API搜索曲目和专辑