Delivering Sweet Tunes with SparkPost and the Spotify API
Tags: api, spotify, sparkpost
Published: 2017-06-15 20:06:28

---
title: Delivering Sweet Tunes with SparkPost and the Spotify API
published: true
description: Want your friends to help build the party playlist? Aydrian walks you through how to create a collaborative playlist with SparkPost and the Spotify API.
tags: api, spotify, sparkpost
---

One of my favorite things about my job is getting to take existing APIs and figure out ways to mix and match them with SparkPost to create cool and interesting apps. Thanks to our friend [Todd Motto](https://twitter.com/toddmotto), there’s a [Github repo](https://github.com/toddmotto/public-apis) full of public APIs for me to choose from. Using APIs from this repo, I’ve created apps like [Giphy Responder](https://github.com/aydrian/giphy-responder/) and many others that didn’t quite make it to Github.

SparkPost recently sponsored [ManhattanJS](http://manhattanjs.com/), which happened to be hosted at Spotify Headquarters in New York. This inspired me to take a look at the [Spotify Web API](https://developer.spotify.com/web-api/) and come up with something I could demo at the meetup. Their web API allows you do many things, such as search for a song, get information about artists and albums, manage playlists, and so much more. Given that set of functionality, how could I combine it with sending or receiving email to create an engaging demo?

I love music. I was a Punk/Ska DJ in college. When I owned a car, I would sing in it (I still do when I rent one!). I’ve also been a Spotify Premium member since 2011. Now that I live in NYC and travel mostly underground, I rely heavily on my offline playlists. But here’s the problem: I’m not hip or cool, and since I no longer listen to the radio, I don’t know a lot of new music. This usually results in me sitting in a subway car listening to early 2000’s emo bands or sobbing silently to myself while listening to the cast recording of [A New Brain](https://play.spotify.com/album/6vsRhoxMNFQBUhRIZ3Ocr9).

So yeah... I need suggestions. Spotify has a great social experience but sadly, not everyone has Spotify. But wouldn’t it be cool if you could email songs to a public collaborative playlist? I’m pretty sure everyone has access to email. This would also be a great way to create a playlist for an event. So I set out to create [JukePost](https://github.com/aydrian/jukepost).

The idea was simple. First I’d create an inbound domain (listen.aydrian.me) that would allow me to send an email to {playlist}@listen.aydrian.me with a list of songs. (Note: {playlist} has to be an already-existing, public, collaborative playlist.) Then I’d create a Node.js app using Express.js to process the relay webhook, search for the song and add it to the specified playlist, and reply with a confirmation that included the songs added and a link to the playlist.

##Webhooks, You Gotta Catch’em All!
For this application, I decided to use [Firebase](https://firebase.google.com/), a real time noSQL database. I like to use it for a lot of my demo apps because it makes receiving webhooks extremely easy. It will even receive them when your app isn’t running. You just need to set the target of your webhook to your Firebase URL + store name + .json. 

So, let’s set up an inbound domain and create a relay webhook to point to a Firebase database. I’m going to use the [SparkPost Node CLI](https://github.com/SparkPost/node-sparkpost-cli), but you’re welcome to use your favorite way to access the SparkPost API.

* Setup the MX records for your inbound domain. I’ll be using listen.aydrian.me
* Create your inbound domain:
`sparkpost inbound-domain create listen.aydrian.me`
* Create a relay webhook for your inbound domain targeting your Firebase URL. I’ll be using
`https://jukepost.firebaseio.com/raw-inbound.json`

```
sparkpost relay-webhooks create --name JukePost --target https://jukepost.firebaseio.com/raw-inbound.json --match.protocol SMTP --match.domain listen.aydrian.me
```

At this point, you should be able to send an email to `{anything}@listen.aydrian.me` and see an entry under `raw-inbound`.

##Playing with the Playlist

Now that we’re catching the incoming emails, we need a broker app to parse out the data, handle the interactions with Spotify, and trigger a response email.

First, we need to handle authenticating to Spotify using Oauth 2.0. This was my first time doing that and luckily I found the `spotify-web-api-node` [npm package](https://github.com/thelinmichael/spotify-web-api-node) and a great [blogpost](http://jkaufman.io/spotify-auth-react-router/) that assisted me in creating the `login`, `callback`, `refresh_token` routes needed to get everything going. Once the application is authenticated, we can pull the user’s public playlists, filter out the collaborative ones, and save them for later.

Now we can use the `firebase` [npm package](https://www.npmjs.com/package/firebase) to listen for new inbound messages and process them accordingly. Because Firebase notifies us of new messages in real time, we can set up a listener.

```
const firebase = require('firebase')
const relayParser = require('./relay_parser')

firebase.initializeApp({
  apiKey: process.env.FIREBASE_API_KEY,
  authDomain: process.env.FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.FIREBASE_URL
})

const ref = firebase.database().ref('raw-inbound')
ref.on('child_added', snapshot => {
  snapshot.forEach(item => {
      const data = relayParser.processRelayMessage(item.val().msys.relay_message)
      // Search for Tracks, Add to Playlist, Send Email
})
```

You can take a look at [relayParser.js](https://github.com/aydrian/jukepost/blob/master/server/relay_parser.js) to see how I grab the relevant data from the relay message. Based on the information we parsed from the message body text, we now know who sent the message, which playlist to add songs to, and what songs to search for. We now have everything we need to find the songs and add them to the playlist. Be sure to add the song information to a substitution data object, as we’ll use that for the confirmation email.

![Sample Confirmation Email](https://thepracticaldev.s3.amazonaws.com/i/mavjkefssrr7ffmigyyj.png)

I chose to get a little fancy with my [confirmation email](https://github.com/aydrian/jukepost/blob/master/resources/JukePost_Email_Response.png). I decided to use a stored template that would return a link to the playlist and the songs that were added along with artists, cover art, and a 30 second sample. I put my [template html](https://github.com/aydrian/jukepost/blob/master/resources/add_template.html) and a [sample json object](https://github.com/aydrian/jukepost/blob/master/resources/substitution_data.json) in the resources folder of the github repo for your convenience.


This was a fun little project and the demo went over quite well. Want to try it for yourself? Send an email to [sparkpost@listen.aydrian.me](mailto:sparkpost@listen.aydrian.me) with the subject line `Add` and then add your favorite songs to the body in the format {title} by {artist}. Let’s build an awesome playlist together.

This is just the tip of the iceberg for what this app can do. Have a cool idea for an addition? Feel free to [create an issue](https://github.com/aydrian/jukepost/issues/new) or [submit a pull request](https://github.com/aydrian/jukepost/compare).

P.S. Want to do more with inbound email processing? Check out my post about inbound email and other cool things you can do with it. 

This post was originally published on the [SparkPost blog](https://www.sparkpost.com/blog/spotify-api-jukepost/).