Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

70
Views
Spotify Web API / Next.js: Only getting data from one end-point

I'm pretty new to working with API's, and I'm currently trying to fetch some data from the Spotify API in a Next.js website. The problem is that the only end-point that gives me any data is the 'top-tracks': (https://api.spotify.com/v1/me/top/tracks), all the other end-points I've tried gives this error:

Request failed FetchError: invalid json response body at https://api.spotify.com/v1/me/player/recently-played reason: Unexpected token U in JSON at position 0

This is the function I'm using to fetch data from the API:

const basic = Buffer.from(`${client_id}:${client_secret}`).toString("base64");
const TOKEN_ENDPOINT = `https://accounts.spotify.com/api/token`;

export default async function handler(req, res) {
  const response = await fetch(TOKEN_ENDPOINT, {
    method: "POST",
    headers: {
      Authorization: `Basic ${basic}`,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: querystring.stringify({
      grant_type: "refresh_token",
      refresh_token,
    }),
  })
    .then((response) => response.json())
    .then((data) => {
      const access_token = data.access_token;
      return fetch(`https://api.spotify.com/v1/me/player/recently-played`, {
        method: "GET",
        headers: {
          Authorization: `Bearer ${access_token}`,
        },
      });
    })
    .then((response) => response.json())
    .catch((err) => {
      console.error("Request failed", err);
    });

  return res.status(200).json(response);
}

(First getting the access token, using clientId and secret from env-variables, then fetching data from API using said token)

Any idea of what I'm doing wrong here? All help is greatly appreciated :)

Also: I've added the necessary scopes, so I should have permisssion to get the data!

7 months ago ยท Juan Pablo Isaza
Answer question
Find remote jobs