Created
December 29, 2019 14:27
-
-
Save fmaylinch/8898eea4bfa18d9cc812a454b6254fa5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This is an example of a basic node.js script that performs | |
* the Client Credentials oAuth2 flow to authenticate against | |
* the Spotify Accounts. | |
* | |
* For more information, read | |
* https://developer.spotify.com/web-api/authorization-guide/#client_credentials_flow | |
*/ | |
var request = require('request'); // "Request" library | |
var client_id = 'xxx'; // Your client id | |
var client_secret = 'xxx'; // Your secret | |
// your application requests authorization | |
var authOptions = { | |
url: 'https://accounts.spotify.com/api/token', | |
headers: { | |
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) | |
}, | |
form: { | |
grant_type: 'client_credentials' | |
}, | |
json: true | |
}; | |
const playlistId = 'xxx'; | |
request.post(authOptions, function(error, response, body) { | |
if (!error && response.statusCode === 200) { | |
// use the access token to access the Spotify Web API | |
var token = body.access_token; | |
displayPlaylistTracks(playlistId, token, 0, 100, [], items => { | |
items.forEach(item => { | |
let artists = item.track.artists.map(a => a.name).join(", "); | |
let track = item.track.name; | |
console.log(artists + " - " + track); | |
}); | |
console.log("\ntoken: " + token); | |
}); | |
} | |
}); | |
function displayPlaylistTracks(playlistId, token, offset, limit, items, callback) { | |
//console.log("offset " + offset); | |
var options = { | |
url: 'https://api.spotify.com/v1/playlists/' + playlistId + '/tracks?offset=' + offset + '&limit=' + limit, | |
headers: { | |
'Authorization': 'Bearer ' + token | |
}, | |
json: true | |
}; | |
request.get(options, function(error, response, body) { | |
//console.log("found " + body.items.length); | |
body.items.forEach(item => { | |
items.push(item); | |
}); | |
if (body.items.length === limit) { | |
displayPlaylistTracks(playlistId, token, offset+limit, limit, items, callback); | |
} else { | |
callback(items); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment