Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Spotify API : Create A Playlist

- First checks to see if a playlist with the requested name already exists

- > get playlsts docs > https : //developer.spotify.com/documentation/web - api/reference/get - a - list - of - current - users - playlists >

- > create playlist docs > https : //developer.spotify.com/documentation/web - api/reference/create - playlist >

JavaScript

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

const checkIfPlaylistExists = async (name) => {
  let exists = false
  let maxLoopCount = 20
  for (let i=0; i<maxLoopCount; i++) {
    const url = new URL(`https://api.spotify.com/v1/me/playlists`)
    const params = {
      offset: 50 * i,
      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()
    if (!response.next) {
      i = maxLoopCount
    }
    response.items.forEach((item) => {
      if (item.name === name) {
        exists = true
        i = maxLoopCount
      }
    })
  }
  return exists 
}


const createPlaylist = async (name) => {
  if (!await checkIfPlaylistExists(name)) {
    const url = new URL(`https://api.spotify.com/v1/users/${user_id}/playlists`)
    const payload = {
      method: 'POST',
      headers: {
        Authorization: `Bearer  ${access_token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name,
        public: false,
        description: "This playlist is from the API",
      }),
    }
    const data = await fetch(url, payload)
    const response = await data.json()
    console.log(response)
  } else {
    console.log("Playlist already exists")
  }
}

const runIt = async () => {
}

document.addEventListener("DOMContentLoaded", async () => {
  const response = await createPlaylist("API Test 1")
  console.log(response)
})