Thomas Christensen
Thomas Christensen

Reputation: 109

Make a GET request to Spotify

I'm trying to make a get request to a public Spotify playlist to get the follower count, and then inject it into the inner HTML of a div. Simple as that.

I'm a bit new to APIs and JS in general, so thought I'd ask if anyone is to see what I'm doing wrong here.

The JS code looks like so:

const updateSpotify = (function() {

const clientId = 'aa81a434672045ccb5c9b40029359183';
const clientSecret = '456aea5802484cc5b83e35e05a40c623';

const _getToken = async () => {

    const result = await fetch('https://accounts.spotify.com/api/token', {
        method: 'POST',
        headers: {
            'Content-Type' : 'application/x-www-form-urlencoded', 
            'Authorization' : 'Basic ' + btoa(clientId + ':' + clientSecret)
        },
        body: 'grant_type=client_credentials'
    });

    const data = await result.json();
    return data.access_token;
}

const _getPlaylist = async (token) => {

    const result = await fetch(`https://api.spotify.com/v1/playlists/1Vt3ahELCdZ6tEAYUy8mNy`, {
        method: 'GET',
        headers: { 'Authorization' : 'Bearer ' + token}
    });

    const data = await result.json();
    document.getElementById("followers").innerHTML = data.followers.total;
    document.getElementById("cover-image").src = data.images.total;
    return data;
}

_getPlaylist(_getToken()); });

On the HTML page, I'm trying to call the function on load like this:

<body class="overview" onload="updateSpotify();">

But the developer tools gives me a 400 error. From spotify:

400 Bad Request - The request could not be understood by the server due to malformed syntax. The message body will contain more information; see Response Schema.


Is anyone able to see what is going wrong here?

Upvotes: 0

Views: 645

Answers (1)

Mo_-
Mo_-

Reputation: 634

Try it with curl and see if it works:

curl -X GET "https://api.spotify.com/v1/playlists/1Vt3ahELCdZ6tEAYUy8mNy" -H "Authorization: Bearer {your access token}"

I think the problem in your code is that _getToken() is returning a Promise instead of the token value. Try calling the _getPlaylist like this:

_getToken().then(function(token) {
  _getPlaylist(token);
})

Upvotes: 1

Related Questions