简体   繁体   中英

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>");
    }
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM