Day 4 of the Anvil Advent Calendar

Build a web app every day until Christmas, with nothing but Python!

Driving the Spotify API with Anvil

We all eventually reach the point where we can’t decide which terrible Christmas song we’re going to listen to next. Thankfully the Spotify API can help us!

Today’s app is extremely simple. Visit the page, login with Spotify, get a song recommendation! It even plays the song for you, right there in the page.

To see how it works, clone it here and check out the source code:

Embedding the Spotify Player

Spotify provides a convenient way of embedding a player right there in your page - just add an iframe with a carefully crafted URL:

    <iframe src="https://open.spotify.com/embed/track/4cOdK2wGLETKBW3PvgPWqT" 
            width="300" height="380" frameborder="0" allowtransparency="true" 
            allow="encrypted-media"></iframe>

And it looks something like this:

We do this in Anvil using a Custom Component, to hide away the iframe implementation. We simply pass it a track_id and it takes care of the rest.

Random Song Choices

The Spotify API has all sorts of useful endpoints. You need to log in to use them, but I’m not going to go into the details here - you can see the (surprisingly simple!) implementation of the standard OAuth flow in the source code of my Spotify OAuth Helper app.

To save using the REST endpoints directly, we use the excellent Spotipy library, which takes care of that for us. We’re going to choose random songs from the terrible brilliant ‘100 Greatest Christmas Songs Ever’ playlist. So, on the server, this is all we need:

@anvil.server.callable
def get_random_track():
  tracks = spotify.playlist_tracks("5OP7itTh52BMfZS1DJrdlv")['items']
  track = random.choice(tracks)['track']
  print(f"Chosen track: {track['name']}")
  return track

We return this track to the client, add a Spotify player, and we’re done!

    track = anvil.server.call('get_random_track')
    self.add_component(SpotifyPlayer(track_id=track['id']))

Give it a try yourself!


Give the Gift of Python

Share this post: