Building a Spotify-like currently playing feature: Part 1 - Building the web API
You will need Node (any LTS version) and NPM installed on your machine.
Introduction
When using music streaming services like Spotify, you can see realtime technology in action when you are using multiple devices. On the other devices, you can see how much playtime has elapsed.
In this series, we will take a look at how you can integrate this feature into your application with minimal fuss. We will be building a web API, a web app, and an iOS application. Both apps will consume the API we built.
Prerequisites
To follow along in this part of the series, you must have the following requirements:
- Node.js (any LTS version) and NPM installed locally on your machine. Install here.
- Basic knowledge of JavaScript.
- Basic knowledge of the command-line interface.
Setting up
The first thing you need to do is create a Pusher account. Next, create a Pusher Channels application using the dashboard.
Next, create a root directory for your Web API project. We will call it spot
. When this is done, launch your terminal application and cd
to the directory you just created. In this directory, run the following command:
$ npm init -y
At the end, you should have a package.json
file in the root of your application.
Let’s install some dependencies we will need for our API. In the terminal, run the following command:
$ npm install --save express body-parser pusher cors
This will install all the dependencies we need to build the API. When the installation is complete, we can move on to building the application.
Building the web API
Now that we have everything installed, let’s create the web API. Open the project in an IDE of your choice. Create a new index.js
file. This will be where we will have all our logic. Let’s start building our API.
Let’s start by importing and using all the dependencies that we installed using npm. In the file, paste the following code:
// File: index.js
const express = require('express');
const bodyParser = require('body-parser');
const Pusher = require('pusher');
const fs = require('fs');
const cors = require('cors');
const path = require('path');
const app = express();
Above, we imported and created instances of the dependencies we installed using npm. Next, let’s create our API endpoints.
We will be creating three endpoints:
tracks
- this endpoint will return all the available tracks for the music player. Since we are not building a full-fledged application, we will be mocking the data from a flat JSON file. We will create this file later on.current
- this endpoint will return the currently playing song. This will make it easy for other clients to know which song is currently playing when they are loaded.tick
- this endpoint will trigger a Pusher event. As the song plays, we will intermittently send the current position of the song playing using this endpoint. This is so that other web clients can know where the track is currently.
Let’s start implementing these endpoints.
In the index.js
file, paste the following code:
// File: index.js
// [...]
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
let tracks = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'data.json')));
app.get('/tracks', (req, res) => {
res.json(tracks);
});
As seen above, we are returning the contents of a nonexistent JSON file. This file is supposed to contain the data for our tracks. Let’s create this file.
Create a file named data.json
and paste the following JSON string into the file:
// File: data.json
[
{
"id": 1,
"duration": 195,
"artist": "JugHead",
"title": "Polly",
"cover": "https://via.placeholder.com/500x500"
}
]
Now that we have the data file, we can continue building the API. In the index.js
file, paste the following code to create the second endpoint:
// File: index.js
// [...]
let current = {};
app.get('/current', (req, res) => {
res.json(current);
});
Above, the endpoint simply returns the currently playing track if there is any or an empty JSON object if nothing is playing.
Let us add the last endpoint. In the index.js
file, add the following code:
// File: index.js
// [...]
app.options('/tick', cors());
app.post('/tick', cors(), (req, res) => {
const { id, position, device } = req.body;
for (let index = 0; index < tracks.length; index++) {
if (tracks\[index\]['id'] === parseInt(id)) {
current = tracks[index];
pusher.trigger('spotmusic', 'tick', { id, position, device });
return res.json({ status: true });
}
}
res.json({ status: false });
});
In the endpoint above, we will receive the ID of the track currently being played, the position of the track and then we will receive the device that is sending the request. When we find a matching existing track, we will trigger the event to Pusher and save the currently playing track on the server.
Finally, let’s make sure the Node.js server is listening on port 3000 when we start the server. In the index.js
file, add the following code:
// File: index.js
// [...]
app.listen(3000, () => console.log('Listening on port 3000!'));
Now that we have the endpoints set up, let’s add realtime triggers to Pusher. Before the app
variable, add the following code:
// File: index.js
// [...]
let pusher = new Pusher({
appId: 'PUSHER_APP_ID',
key: 'PUSHER_APP_KEY',
secret: 'PUSHER_APP_SECRET',
cluster: 'PUSHER_APP_CLUSTER',
useTLS: true
});
Replace the
PUSHER_APP_*
placeholders with the credentials from your Pusher dashboard.
Running the application server
Now that we have built the application, we need to run the application in a server. In your terminal, run the following command to start the Node server:
$ node index.js
Now your server is running, in the next parts, we will move on to creating the clients that will consume the API that the Node.js app provides.
Conclusion
In this part, we created a web API for our music application. This API will be responsible for returning the tracklist and also updating the now playing track. It will also be responsible for triggering events to Pusher.
In the next part, we will start building an iOS app that will consume the API we built in this part. The source code is available on GitHub.
28 August 2019
by Neo Ighodaro