In this guided practice, we'll use Express to create a simple API that serves information about a playlist of songs.
- Create a new repository using this one as a template.
- Clone down your repository and run
npm installto install the dependencies. - Start the development server with
npm run dev.
-
In
server.js, import the"express"package and call it to create the Express app.See solution
const express = require("express"); const app = express();
-
Initialize a
PORTvariable to 3000, which is a common default port that local servers listen on.See solution
const PORT = 3000;
-
Write middleware to handle the
GET /endpoint. It should respond with the message"You've reached the Playlist API!".See solution
app.get("/", (req, res) => { res.send("You've reached the Playlist API!"); });
-
Tell the app to listen on
PORT. A corresponding status message should be logged to the console, which you should see if your development server is running.See solution
app.listen(PORT, () => { console.log(`Listening on port ${PORT}.`); });
-
Use the REST Client Extension to test the
GET /endpoint inplaylist.http. If you've done everything correctly, the server should respond with the correct message!
-
An array of songs has already been initialized in
playlist.js. At the bottom of that file, add a line to export that array.See solution
module.exports = playlist;
-
Back in
server.js, import that array usingrequire. Now that our server has access to this data, we can use it in our responses.See solution
const playlist = require("./playlist");
-
Write middleware to handle the
GET /playlistendpoint. It should respond with theplaylistarray as JSON. Useplaylist.httpto test this endpoint.See solution
app.get("/playlist", (req, res) => { res.json(playlist); });
-
Write middleware to handle the
GET /playlist/:indexendpoint. It should respond with the song at the givenindexof theplaylistarray. If the index is invalid, it should send the message"That song does not exist in the playlist."with status code 404. Useplaylist.httpto test this endpoint.See solution
app.get("/playlist/:index", (req, res) => { const { index } = req.params; if (index < 0 || index >= playlist.length) { res.status(404).send("That song does not exist in the playlist."); } else { res.json(playlist[index]); } });
To view the full solution, switch over to the solution branch of this starter repository.