H. Pauwelyn
H. Pauwelyn

Reputation: 14280

Get public playlist from Spotify by username

I'll try to get the public playlists of an Spotify-user, but I get always a 401-error.

{
    "error": {
        "status": 401,
        "message": "This request requires authentication."
    }
}

I use this url https://api.spotify.com/v1/users/id/playlists where id must be an username from Spotify. I have an oAuth key. I request the API with this JavaScript, JQuery code:

$.ajax({
    url: "https://api.spotify.com/v1/users/" + $("#username").val() + "/playlists",
    Authorization: "Bearer my_OAuth_Token",
    Host: "api.spotify.com",
    Accept: "application/json",
    type: "GET",
    success: function (data){

        var count = data.items.length;

        for (var i = 0; i < aantal; i++) {
            $("#playlists").append('<option>' + data.items[i].name + '</option>');
        }
    },
    error: function (data) {
        $("#playlists").append("<option>error</option>");
    }
});

Upvotes: 1

Views: 914

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to send the Authorization and Host values as headers, not as properties of the options object. Also note that accepts should be lower case. Try this:

$.ajax({
    url: "https://api.spotify.com/v1/users/" + $("#username").val() + "/playlists",
    headers: {
        Authorization: "Bearer my_OAuth_Token",
        Host: "api.spotify.com"
    },
    accepts: "application/json",
    type: "GET",
    success: function (data) {    
        var count = data.items.length;    
        for (var i = 0; i < aantal; i++) {
            $("#playlists").append('<option>' + data.items[i].name + '</option>');
        }
    },
    error: function (data) {
        $("#playlists").append("<option>error</option>");
    }
});

You could probably also leave out the Host header, as I don't believe it's required.

Upvotes: 1

Related Questions