Published
Edited
Aug 12, 2020
Importers
1 star
Insert cell
Insert cell
Insert cell
Insert cell
spotifyLogin(CLIENT_ID, { scope: 'user-read-recently-played user-top-read' })
Insert cell
Insert cell
Insert cell
viewof spotifyToken = spotifyLogin(CLIENT_ID, { scope: 'user-read-recently-played user-top-read' })
Insert cell
Insert cell
{
if (spotifyToken === null) return md`**⚠️ You must log in to Spotify above to see this information!**`
const topTracks = await (await fetch(
'https://api.spotify.com/v1/me/top/tracks?time_range=short_term&limit=5',
{ headers: { Authorization: `Bearer ${spotifyToken}`} }
)).json()
return html`<h3>Your Recent Top Tracks</h3>
<ol>
${topTracks.items.map(d => html`<li><a href=${d.uri}>${d.name}</a></li>`)}
</ol>
`
}
Insert cell
Insert cell
Insert cell
spotifyLogin = async (clientId, params = {}) => {
let output
const spotifyToken = new URLSearchParams(window.location.hash.replace('#', '?')).get('access_token')
if (!spotifyToken) {
output = loginButton(clientId, params)
} else {
const spotifyProfileResponse = await fetch(
'https://api.spotify.com/v1/me',
{ headers: { Authorization: `Bearer ${spotifyToken}` } }
)
const spotifyProfile = await spotifyProfileResponse.json()
output = profileDetails(spotifyProfile)
}
return Object.assign(output, { value: spotifyToken })
}
Insert cell
loginButton = (clientId, params = {}) => {
const notebookUrl = html`<a href>`.href
const queryStringWriter = new URLSearchParams()

queryStringWriter.append('response_type', 'token')
queryStringWriter.append('client_id', clientId)
queryStringWriter.append('redirect_uri', notebookUrl)
Object.entries(params).forEach(([k, v]) => queryStringWriter.append(k, v))
return html`
<a
href="https://accounts.spotify.com/authorize?${queryStringWriter.toString()}"
>
Log in with Spotify
</a>
`
}
Insert cell
profileDetails = (profile) => html`
Logged in to Spotify as
${'images' in profile && profile.images.length > 0 ? html`
<img
src=${profile.images[0].url}
style="height: 1.25em; margin-right: 0.25em; border-radius: 50%; vertical-align: top"
/>
` : ''}
<strong>${profile.display_name}</strong>
`
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more