Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spotify API 400 Error Only Valid Bearer Authentication Supported

I'm trying to use the spotify api to get data for my top artists and songs. I followed the authorization code examples here https://github.com/spotify/web-api-auth-examples. The authorization works and I can log in and see my basic info and now I'm trying to get my top artists however I get a 400 error: "Only valid bearer authentication supported".

Here's my code for this

    app.get('/get_top_artists', function(req, res) {
  var authString = 'Basic' + new Buffer(client_id + ':' + client_secret).toString('base64')
  var authOptions = {
    url: 'https://api.spotify.com/v1/me/top/artists',
    headers: {
      'Authorization': authString
    }, function(res) {
      console.log(res)
    }
  };

  request.post(authOptions, function(error, response, body) {
    if (!error && response.statusCode === 200) {
      var get_top_artists = body.get_top_artists;
      res.send({
        'get_top_artists': get_top_artists
      });
    }
  });
})

EDIT

    app.get('/get_top_artists', function(req, res) {
  console.log('top artists');

  var authOptions = {
      url: 'https://accounts.spotify.com/api/token',
      form: {
        redirect_uri: redirect_uri,
        grant_type: 'authorization_code'
      },
      headers: {
        'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
      },
      json: true
    };

  request.post(authOptions, function(error, response, body) {
    console.log('request')
    if (!error && response.statusCode === 200) {

        var access_token = body.access_token,
            refresh_token = body.refresh_token;
        var options = {
          url: 'https://api.spotify.com/v1/me/top/artists',
          headers: { 'Authorization': 'Bearer ' + access_token },
          json: true
        };

        // use the access token to access the Spotify Web API
        request.get(options, function(error, response, body) {
          console.log('request 2')
          console.log(body);
        });
     }
  });
})
like image 378
captnvitman Avatar asked Oct 04 '17 02:10

captnvitman


1 Answers

As you can see in the example, you need to first make the call with the basic header, and then take the response you get and THEN make the call to the API. Looks like you're trying to make the call to the API with the Basic credentials, which won't work.

https://github.com/spotify/web-api-auth-examples/blob/master/authorization_code/app.js#L73-L102

like image 129
Dan Crews Avatar answered Oct 23 '22 04:10

Dan Crews