Andy Rob Robinson
Andy Rob Robinson

Reputation: 31

Printing information from the Spotify URI with Node JS

I've completed the spotify tutorial (on their developer site) that prints a users information on screen, via the web API which runs using Node.js.

I've now edited my app.js file to include all permissions for the site to look / edit into user's music and playlists.

I'm now (as a test) trying to print a users playlists on screen, however, don't know how as I need the Spotify user ID as part of the URL to call the JSON array.

It'll be spotifyurl.com/me/[useridgoeshere]/playlists.

The user ID is printed in the html, which takes it from the JSON array. How would I go about taking the ID from the html and adding it to my javascript so I can make the call for the correct playlist array?

$.ajax({
                url: 'https://api.spotify.com/v1/me', 
                headers: {
                  'Authorization': 'Bearer ' + access_token
                },
                success: function(response) {
                  userProfilePlaceholder.innerHTML = userProfileTemplate(response);
                  userNavPlaceholder.innerHTML = userNavTemplate(response);


                  $('.login').hide();
                  $('.loggedin').show();
                }

            });

This is the code for making the call for the user information and this is the URL I need to make the playlists request:

https://api.spotify.com/v1/users/{USERID}/playlists

Many thanks for your help, I'm very new to this and having googled concatenating strings and variables I wondered if anyone could help.

Upvotes: 0

Views: 305

Answers (1)

Michael Thelin
Michael Thelin

Reputation: 4830

I suppose you could nest your requests, although that's probably not the most beautiful way of doing it.

$.ajax({
  url: 'https://api.spotify.com/v1/me', 
  headers: {
    'Authorization': 'Bearer ' + access_token
  },
  success: function(userResponse) {
    $.ajax({
      url: 'https://api.spotify.com/v1/users/' + userResponse.id + '/playlists',
      headers: {
        'Authorization': 'Bearer ' + access_token
      },
      success: function(playlistsResponse) {
        console.log('This user has ' + playlistsResponse.total + ' playlists!');
      }
    }); 
  }
});

I'd recommend that you check out the JavaScript client made by JMPerez (More documentation), it might save you some time.

Upvotes: 0

Related Questions