Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Spotify API: Get A User's Top Tracks

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