MS Club of SLIIT
Published in

MS Club of SLIIT

Build a simple Rest API using ExpressJS and NodeJS

Beginners Guide

Hello there! In this article I’m going to talk about how to build a simple REST API using ExpressJS and NodeJS. Before getting started we have to set up the NodeJS environment in our machines. First, let’s head over to https://nodejs.org and download the latest stable NodeJS version. Once you download the file, install it into your machine. After that open your terminal and type “node -v” to check whether it’s installed successfully. If it’s installed successfully you will get the version of the NodeJS that you have installed. Alright, now we are going to implement our Rest API from the scratch!

Let’s create a new folder for our API. Here I’m using terminal commands but you can also use the normal way to create a new folder with any name.

In this tutorial, I’m going to create a new folder called “first-api”.

mkdir first-api

Then we have to change the terminal directory to the new folder.

cd first-api

Now we are inside our newly created folder and here we have to initialize our project. For that, we are using Node Package Manager (NPM). You might wonder what is NPM and why we need it here… Don’t worry, I will explain. NPM is a package manager for Javascript Programming. When we developing Node Projects we need various packages, so that we use NPM to install them. There are several package managers that you can use in your projects, in here let’s use NPM. You can learn more about NPM using this link.

Let’s initialize our Node Project by typing

npm init

Then it will run a little wizard and ask for details of our project. If you want you can skip this step by typing

npm init -y

With the “-y” flag it will initialize a new project without asking for the project information. You can add or change these things later. Now we have successfully initialized our Node Project. If we check our folder, we have a new file called package.json. It contains all the information about our project.

As I mentioned earlier we have to use some packages when we developing our node projects. Here we are going to use ExpressJS to build this API because Express makes it easier for us. Let’s install ExpressJS dependency by typing


npm install express

If it has successfully installed, you should see the ExpressJS listed in your package.json file under the dependencies category. Also, there should be an automatically generated folder called node_modules and a new file called package-lock.json. The node_modules folder is used to store all downloaded packages from NPM and package-lock.json describes the exact tree of node modules.

Let’s start the coding part… Open your favorite editor (VS code recommended) inside the folder that we have already created and create a new file called server.js. If you are using a different name you have to add the following start snippet to the “scripts” in your package.json file.

“scripts”: {“start”: “node your-file-name.js”}

Let’s define our server by adding the following code to your file.

const express = require(“express”);const app = express();const PORT = 8080;app.listen(PORT, () => {console.log(“Server running on port : “ + PORT);});

Now let’s go through the code… The first line requires ExpressJS and uses “express” variable to store it. The second line initialized the express server and save it to the “app” variable. So now whenever we need to do something with our server we can use the “app” variable. The third line defined the port number which the project should run. Thereafter we set the project to listen on the port that we have already defined and pass a callback function. “app.listen()” function takes the port as its first argument and a callback function for the second argument. So when it starts to listen on the port that we passed, it will execute whichever function we defined as the second argument. Here we use an arrow function as the callback function, you can use a normal function also. Now let’s open our terminal and type

npm start

If there are no errors you should see the “Server running on port : 8080” in your terminal. Our app will now be accessible through http://localhost:8080, but we won’t get anything since we haven’t configured our server to listen to any requests.

Now let’s create a simple request handler for our server. Whenever the server receives a request,request handlers are responsible for processing it and returning a response. There are several request types and you can learn more about requests types using this link. Here we are going to implement a request handler for a GET request. Let’s implement our handler by copying the below code snippets to your file.

app.get(“/home”, (req, res) => {res.json(“This is Home”);});

As I mentioned earlier we can access our server using “app” variable. After that, we have to mention the request type that we are creating for our request handler. Since we are implementing a GET request handler, we mention it as “app.get()”. So this function also has two arguments. The first one is for the URL that we are going to implement our handler and the second argument is a callback function. Whenever the requests coming for the specified URL in the first argument, the callback function will be triggered. This callback function accepts three arguments but here we are using only two. The first one is for the requests and the second one is for the response. In this example, we are only dealing with the response. Whenever a request comes with a “/home” URL it will return a response as “This is Home” in JSON format.

Now it’s time to check our REST API. Make sure to restart your server because we have made some changes. You can stop your server by pressing CTRL+C in your terminal and type “npm start” again to start it again. Now open up your browser (You can use API clients also) and type http://localhost:3000/home. You should expect to see something like this on your browser!

Response from the Server

Thank you for reading my article, hope it’s helped you.

--

--

--

A student-driven community based on SLIIT aiming to bridge the skill gap between an Undergraduate and an Industry Professional

Recommended from Medium

MSAL2.0 Errors and their Resolution

Custom JavaScript in Cognos — Expand and Collapse

React native facebook auth

Use Custom Elements for Reusable Components! (ES6)

React Native Libraries I Use in Every Project

Reviving a legacy codebase with React Native

How to setup TabPy on your linux computer

Basic Period selector using HTML and JavaScript

Period Selector

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
Himasha Weerasinghe

Himasha Weerasinghe

More from Medium

Article Worth Reading On What Is An API, What is A REST API And Deep Diving Into REST API.

NodeJS, Express, Axios and the basic set-up

Node.js Basic Concept

Authentication for Dummies