home ~ projects ~ socials

Spotify API: Get A User's Top Tracks

Notes

  • The page assumes you have >logged in here>/pages/2zzlhz3m/>
  • There's a "next" featured defined for getting more items, but I'm only seeing 50 so I'm setting the limit to that and not messing with it.
  • This is set to "long_term" - calculated from several years of data and including all new data as it becomes available
  • There's also: medium_term which is roughly the last 6 months, and short_term which is roughly the past 4 weeks
  • The default is: medium_term

Output

Loading

HTML

<pre id="spotifyData">Loading</pre>

JavaScript

const user_id = localStorage.getItem("spotify_example_user_id")
const access_token = localStorage.getItem("spotify_example_access_token")

const getData = async () => {
  const url = new URL(`https://api.spotify.com/v1/me/top/tracks`)
  const params = {
    time_range: `long_term`,
    limit: 50
  }
  url.search = new URLSearchParams(params).toString()
  const payload = {
    method: 'GET',
    headers: {
      'Authorization': `Bearer  ${access_token}`
    },
  }
  const body = await fetch(url, payload)
  const response = await body.json()
  return response
}

const pullTracks = async () => {
  let output = "";
  const data = await getData()
  data.items.forEach((item) => {
    const artist_name = item.artists[0].name
    const track_name = item.name
    output += `${artist_name} - ${track_name}\n`
  })
  spotifyData.innerText = output
}

document.addEventListener("DOMContentLoaded", () => {
  if (user_id) {
    pullTracks()
  } else {
    spotifyData.innerHTML = "Not logged in"
  }
})
-- end of line --