Building A RESTful API: Express.js & MongoDB -Part 1

Recently, I was invited to interview for a role. Part of the recruitment process involved a tech assessment that required using Node.js but particularly, Express.js, the framework for Node.js. I’d never used Node.js let alone Express.js so I embarked on an intense learning schedule to prepare for the assessment. Over the next series of articles, I’ll show what I learned by detailing how to build a basic RESTful API using Express.js and MongoDB.

After creating a project folder in the code editor (I use VScode), you’ll need to install Express and Nodemon. Nodemon is a tool that automatically updates and restarts the node application while it’s running. In your terminal, run

npm init

“npm init” creates the package.json file. After running that command, hit enter a few times till the file appears. Then run

npm install express nodemon

In the package.json file, under “scripts”, change

"scripts": {
"test": "echo \"Error: no test specified\""
},

to

"scripts": {
"start": "nodemon app.js"
},

This script will execute and run the server. Then create a file called, “index.js”. You’ll need to import Express so at the top of the page, type in

const express = require('express');

Then create a variable to execute Express and have it listen for the server. Below, Express has been assigned to app which in turn is listening for the server on port 3000.

const app = express();app.listen(3000)

With most of the setup now complete, routes can be added. A route that displays a message on the homepage can be written as follows

app.get('/', function (req, res, next) => {
res.send("Home Page")
};

Before breaking down what app.get()function does, you’ll need to have a basic understanding of middleware function and how it works. Below is the official definition on the expressjs site

“Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware”

app.get routes the HTTP GET Requests to the path (‘/’). “function” refers to the middleware function. “req” is HTTP request argument to the middleware function. “res” is HTTP response argument to the middleware function. “next” is the callback argument to the middleware function.

In terminal, you can run “npm start” and in the browser, go to “http://localhost:3000/” and you’ll see the “Homepage” text displayed.

Junior Front-end Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store