meepz
meepz

Reputation: 363

Spotify Web API Ajax

I am making a small side-project to get better with using website APIs and jQuery. Unfortunately I am not doing that well. What I am trying to do is use the Spotify Web API to get 3 of my playlists and just put them on a web page.

I currently have:

var accessToken = "{my-token}";
$.ajax({
    url: 'https://api.spotify.com/v1/users/{my-username}/playlists?limit=3&offset=0',
    type: 'GET',
    headers {
        'Authorization' : 'Bearer ' + accessToken;
    },
    success: function(data) {
        console.log(data);
    }
});

I get the following error:

Failed to load resource: the server responded with a status of 401 (Unauthorized)

Does anyone have any idea how to do this. After I figure it out I am going to create a quick how-to for any future people that are not-so-familiar with using jQuery to access Web APIs

Upvotes: 0

Views: 5019

Answers (1)

Michael Thelin
Michael Thelin

Reputation: 4830

Spotify's Web API return HTTP status code 401 Unauthorized (Error code documentation) when the access token has expired or when the access token is invalid. Printing out the error response's body would give you further clues about why the API returned the 401.

Access token expire in an hour, but can be refreshed depending on the way you retrieved it. You can read more about the different ways of retrieving access tokens in the Authorization Guide, or check out the web-api-auth-examples project on Github.

Upvotes: 2

Related Questions