Exemple API en TD : team spotify

master
Juan 3 years ago
parent 5305c87cd5
commit f5a4bf843b

@ -0,0 +1,3 @@
SPOTIFY_API_ID=6491f80f28b044beb48e5d9139d98d43
SPOTIFY_CLIENT_SECRET=3c4b5fdc44314f538a30efa1d74d8771

@ -0,0 +1,96 @@
const axios = require('axios');
const qs = require('qs');
require('dotenv').config();
const client_id = process.env.SPOTIFY_API_ID; // Your client id
const client_secret = process.env.SPOTIFY_CLIENT_SECRET; // Your secret
const auth_token = Buffer.from(`${client_id}:${client_secret}`, 'utf-8').toString('base64');
const getAuth = async () => {
try {
//make post request to SPOTIFY API for access token, sending relavent info
const token_url = 'https://accounts.spotify.com/api/token';
const data = qs.stringify({ 'grant_type': 'client_credentials' });
const response = await axios.post(token_url, data, {
headers: {
'Authorization': `Basic ${auth_token}`,
'Content-Type': 'application/x-www-form-urlencoded'
}
})
//return access token
return response.data.access_token;
//console.log(response.data.access_token);
} catch (error) {
//on fail, log the error in console
console.log(error);
}
}
const getFirstTrackAlbum = async (album_id) => {
//request token using getAuth() function
const access_token = await getAuth();
//console.log(access_token);
const api_url = `https://api.spotify.com/v1/albums/${album_id}/tracks`;
//console.log(api_url);
try {
const response = await axios.get(api_url, {
headers: {
'Authorization': `Bearer ${access_token}`
}
})
.then(function (response) {
// handle success
// console.log(response.data);
let firstTrack = response.data.items[0].name;
console.log("First Track: " + firstTrack);
return response.data;
});;
//console.log(response.data);
// return response.data;
} catch (error) {
console.log(error);
}
};
const getFirstArtistAlbums = async (artist_id) => {
//request token using getAuth() function
const access_token = await getAuth();
//console.log(access_token);
const api_url = `https://api.spotify.com/v1/artists/${artist_id}/albums`;
//console.log(api_url);
try {
const response = await axios.get(api_url, {
headers: {
'Authorization': `Bearer ${access_token}`
}
})
.then(function (response) {
// handle success
// console.log(response.data);
let firstAlbum = response.data.items[0].name;
let firstAlbumId = response.data.items[0].id;
console.log("First Album: " + firstAlbum);
console.log("First Album id: " + firstAlbumId);
getFirstTrackAlbum(firstAlbumId);
return response.data;
});
// console.log(response.data);
} catch (error) {
console.log(error);
}
};
// console.log(getFirstArtistAlbums('0TnOYISbd1XYRBk9myaseg'));
getFirstArtistAlbums('0TnOYISbd1XYRBk9myaseg');

@ -0,0 +1,17 @@
{
"name": "spotify-node",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.25.0",
"dotenv": "^14.2.0",
"qs": "^6.10.3"
}
}
Loading…
Cancel
Save