How to fetch data from Spotify Search API and parse it to JSON? [In node.js

Viewed 602

This is my app.js:

const express = require("express");
//const https = require("https");
const app = express();

app.get("/", function(req, res) {
  
  const query = niall;

  // Follow procedure here to get access_token and refresh_token: https://benwiz.com/blog/create-spotify-refresh-token/

  const access_token = {access_token};
  const token = "Bearer " + access_token;
  var searchUrl = "https://api.spotify.com/v1/search?q=" + query + "&type=track&limit=4";





  ////////WRITE YOUR CODE HERE//////////




  
});
// Starting the server. Should this be placed at the top of all other commands?
app.listen(3000, function() {
  console.log("Server is running on port 3000.")
})

Expected Behaviour:

We are to get results from the api endpoint using https.get method.

The returned data is to be parsed to JSON.

We need to store the value of track ID, from this JSON output, into a variable and log it in the console.

Helpful Resources:

I'm really in need of help. Any help would be appreciated.

1 Answers

Replace ////////WRITE YOUR CODE HERE////////// with

axios.get(searchUrl, {
      headers: {
        'Authorization': token,
      }
    })
    .then((resAxios) => {
      console.log(resAxios.data)
      spotifyResult = resAxios.data;

      //Extracting required data from 'result'. The following "items[0].id.videoId" is the address of the data that we need from the JSON 'ytResult'.
      let spotifyTrackIdAppJs00 = spotifyResult.tracks.items[0].id;
      let spotifyAlbumIdAppJs00 = spotifyResult.tracks.items[0].album.id;
      let spotifyArtistIdAppJs00 = spotifyResult.tracks.items[0].artists[0].id;
      console.log("Fetched values: " + spotifyTrackIdAppJs00 + ", " + spotifyAlbumIdAppJs00 + ", " + spotifyArtistIdAppJs00);

      // The 'results' named EJS file is rendered and fed in response. The 'required' data is passed into it using the following letiable(s).
      // A folder named 'views' has to be in the same directory as "app.js". That folder contains 'results.ejs'.
      res.render("results", {
        spotifyTrackIdEjs00: spotifyTrackIdAppJs00,
        spotifyAlbumIdEjs00: spotifyAlbumIdAppJs00,
        spotifyArtistIdEjs00: spotifyArtistIdAppJs00
      });
      console.log("Values to be used in rendered file: " + spotifyTrackIdAppJs00 + ", " + spotifyAlbumIdAppJs00 + ", " + spotifyArtistIdAppJs00);
    })
    .catch((error) => {
      console.error(error)
    })

I needed ID value for Album and Artist as well. Please modify accordingly.

Related