Announcements

Help Wizard

Step 1

NEXT STEP

FAQs

Please see below the most popular frequently asked questions.

Loading article...

Loading faqs...

VIEW ALL

Ongoing Issues

Please see below the current ongoing issues which are under investigation.

Loading issue...

Loading ongoing issues...

VIEW ALL

403 Forbidden getting top tracks but token received

403 Forbidden getting top tracks but token received

Plan

Free

Country

Spain

Device

PC

Operating System

Ubuntu

My Question or Issue

Hello!
The code below returns 403 Forbbiden status and then getTopTracks() obviously returns undefined.
As you can see, it get a token but something happens when getTopTracks() do a request.

Console.log:
token: BQDpyXe_KDka_5BKlQ_y72BSLrhvKbbCGgC1_RkBFTzecSQosg8fomns6_HZXvAu5two19ULmbnzASFAwsoht7k7nmSfTdY0NXT-HwQnl6KcGu0qVJk
https://api.spotify.com/v1/me/top/tracks?time_range=long_term&limit=5
403 Forbidden
topTracks: undefined
undefined

Thank you in advance.

Code:

import fetch from "node-fetch";

const CLIENT_ID = "MY_CLIENT_ID";
const CLIENT_SECRET = "MY_CLIENT_SECRET";
const REDIRECT_URI = "MY_REDIRECT_URI";

async function getAccessToken() {
const authHeader = `Basic ${Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`;

const tokenParams = new URLSearchParams({
grant_type: "client_credentials",
});

const response = await fetch(TOKEN_URL, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: authHeader,
},
body: tokenParams,
});

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

async function fetchWebApi(endpoint, method, body) {
const token = await getAccessToken();
console.log(`token: ${token}`);

const res = await fetch(`https://api.spotify.com/${endpoint}`, {
headers: {
Authorization: `Bearer ${token}`,
},
method,
body: JSON.stringify(body),
});

console.log(`https://api.spotify.com/${endpoint}`)
console.log(res.status, res.statusText);
return await res.json();
}

async function getTopTracks() {
return (await fetchWebApi("v1/me/top/tracks?time_range=long_term&limit=5", "GET")).items;
}

async function main() {
const topTracks = await getTopTracks();
console.log(`topTracks: ${topTracks}`);

console.log(
topTracks?.map(
({ name, artists }) => `${name} by ${artists.map((artist) => artist.name).join(", ")}`
)
);
}

main();



Reply
1 Reply

Since the Client Credentials flow does not include authorization, only endpoints that do not access user information can be accessed. Therefore, in this case, you should use a different Authorization method that lets you log in.

XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.

Suggested posts

Let's introduce ourselves!

Hey there you,   Yeah, you! 😁   Welcome - we're glad you joined the Spotify Community!   While you here, let's have a fun game and get…

ModeratorStaff / Moderator/ 4 years ago  in Social & Random