RESTful API development with Node.js and Express: Getting started with coding ( Part — 2)

RESTful API development with Node.js and Express: Getting started with coding ( Part — 2)

This is the second part of RESTful API development with Node.js and Express. I hope you already have gone through the first part and created your project environment. If you have not read the first part, you can check it here. In this part, we are going to get started building our RESTful API. You will find all the codes from Github:

https://github.com/humayun-rashid/first-rest-api-medium.git
https://github.com/humayun-rashid/first-rest-api-medium.git

We will start by creating a new directory with a preferred name. In my case, I am naming it “first-rest-API”. Open the terminal and type the following command to create a new directory and navigate to the newly-created directory.

$ sudo mkdir rest-API-project
$ cd rest-API-project

After navigating to the directory, you can open visual studio code by writing the following command to your directory.

$ code .

Alternatively, you can create a repository in GitHub with your preferred project name such as “first-rest-api”. If you have already installed git by following the previous article, you should be able to clone the repository by the following command.

$ git clone "git repo url"

Then navigate to the directory and start visual studio code by running the following command.

$ cd rest-API-project
$ code .

Generate Package.json by NPM init

We will now start developing our RESTful API by generating the “package.json” file which is going to contain all the dependencies. This file will be updated when adding further dependencies during the development process. To generate “package.json”, run the following command in the terminal that will request some answers to questions to generate the file. To autofill, the question, “-y” can be added at the end of the command.

$ npm init
$ npm init -y

A “package.json” file will be created similar to the following in the project’s root directory.

{
  "name": "first-rest-api-medium",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/humayun-rashid/first-rest-api-medium.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/humayun-rashid/first-rest-api-medium/issues"
  },
  "homepage": "https://github.com/humayun-rashid/first-rest-api-medium#readme"
}

Install Express Framework and Nodemon

for the next step, we are required to install Express to our project directory as well as save it in the dependencies list of “package.json”. The dependency can also be saved as “development dependency” in case it is required to be used only for development. The purpose of installing dependency as a development dependency is that package users will not be required to install it in production.

$ npm install express — save

To install Express temporarily and not add it to the dependencies list:

$ npm install express — no-save

Now, we are going to install a very cool tool known as no demon that allows a node.js application restarts automatically every time there is a change. Write the following command with “-g” that will allow installing the package as global so that it can be used from anywhere. The problem associated with the local installation of nodemon is that no demon will not be available in your system path and the local installation of nodemon can be run by calling it from within an npm script.

$ npm install -g nodemon

Nodemon can also be installed as a development dependency with the following command in the terminal.

$ npm install — save-dev nodemon

Create a Basic Server

Let’s start coding! First, we are going to create a file and name it as “server.js” in the project root directory. Run the following command in the terminal or create it from visual studio code.

$ sudo touch server.js

Now, we will start writing our code in “server.js”. First, we are going to import the “express” module. For the importing module, we are going to use the “require” function.

require(“express”)

The imported module is required to be in a variable. Variable can be declared as var, let or const. You can find details about variable declaration here :

https://dev.to/sarah_chima/var-let-and-const--whats-the-difference-69e

Variables declared with the const maintain constant values but variables with var can be updated. We are going to import “express” to a const variable. Then an instance of the imported module will be created through the “app” variable. the “app” is an instance of express. you can set the environment variable “PORT” to tell your web server what port to listen on. So process.env.PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there’s nothing there. So you pass that app.listen, or to app.set(‘port’, …), and that makes your server able to accept a parameter from the environment what port to listen on. If you pass 3000 hard-coded to app.listen(), you’re always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you’re running your server.

const express = require(‘express’); // importing Express
const app = express(); // instance of express
const port = process.env.PORT || 3000; // Defining port by environmental parameter or 3000// Create a routing 
app.get(‘/’,function(req,res){
 res.send(‘Server is running.’)
})// App is listening to user-defined port or 300 and printing the information to the console.
app.listen(port, function(req,res){
 console.log(`Server is listening on port ${port}!`)
})

Run the server using the command :

$ node server.js

Now, go to the following URL to access the server.

http://localhost:3000

By going to this URL, we are sending a GET request through our web client. This is the concept of routing. We are going to discuss this later in this section. Now if we are going to make changes, we have to stop the server by pressing ctrl + c and then start the server again by using the above command. To avoid running the server again and again by running the same command, we are going to use the nodemon.

Go to the package.json and replace test in the script with the following:

"scripts": {
"devStart": "nodemon server.js"
}

Then you can start the server using nodemon by using the following command.

$ npm start devStart

Alternatively, you can directly start your server by running following command:

$ nodemon server.js

Now, whenever you make a code change, the server will automatically restart. Currently, our server is running in port 3000. We can also define our port through set or exporting the port parameter through env. If you want to run it just once, run the following command.

$ PORT=1234 node server.js

You don't have to restart the server as nodemon will do it automatically. To set the PORT More permanently, use the following command.

$ export PORT=3000
$ node server.js

For Windows, use the following command.

$ set PORT=3000

For Windows PowerShell:

$ env:PORT = 3000

Another method to set the env parameter is though dotenv package.

npm install dotenv

Add this line to the start of the server.

require(‘dotenv’).config()

Create a .env file in the root directory of your project. Add

PORT = 3000

create .gitignore because you don’t want to import .env to git.

So, our basic server is running. But currently, there is not routing that is configured. We are going to discuss the routing and configure some endpoints.

Routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). Each route can have one or more handler functions, which are executed when the route is matched. Route definition takes the following structure:

Route definition takes the following structure:

app.METHOD(PATH, HANDLER)

METHOD is an HTTP request method, in lowercase. PATH is a path on the server. HANDLER is the function executed when the route is matched. Write down the following code to create routing using GET, POST, PUT and DELETE methods.

require('dotenv').config()
const express = require('express'); 
const app = express(); // instance of express
const port = process.env.PORT || 3000; // GET requestapp.get('/', function (req, res) {
res.status(200).send('Server is up and running.')
})// POST requestapp.post('/', function (req, res) {
res.status(200).send('This is a POST request')
})// PUT Requestapp.put('/', function (req, res) {
res.status(200).send('This is a PUT request')
})// PATCH Requestapp.patch('/', function (req, res) {
res.status(200).send('This is a PATCH request')
})// DELETE Requestapp.delete('/', function (req, res) {
res.status(200).send('This is a DELETE request')
})// App is listening to user-defined port or 300 and printing the information to the console.app.listen(port, function (req, res) {
console.log(`Server is listening on port ${port}!`)
})

To test your routing, you need to have POSTMAN or any other API endpoint testing tool. But for simplicity, I am going to use REST Client, an extension in visual studio code to test endpoints. You can install it in your VS editor by Quick doing open (Ctrl+P) and paste the following command:

ext install humao.rest-client

Let's create a new file with extension rest. I am creating a test.rest to test endpoints. Now write down the following to start testing.

### GET Request
GET http://localhost:3000### POST Request
POST http://localhost:3000### DELETE Request
DELETE http://localhost:3000### PUT Request
PUT http://localhost:3000### PATCH Request
PATCH http://localhost:3000

There should be a 'Send Request' just above the request. You need to press it to test your endpoints.

If the request is successful, you should see output similar to following:

HTTP/1.1 200 OK 
X-Powered-By: Express 
Content-Type: text/html; 
charset=utf-8 
Content-Length: 25 
ETag: W/"19-mtGkfbkTqxz/NZr8uVnRPTJZzm8" 
Date: Fri, 03 Apr 2020 21:18:53 GMT 
Connection: close  Server is up and running.

In case endpoints are not working, it should return a 404 error similar like the following:

HTTP/1.1 404 
Not Found X-Powered-By: Express 
Content-Security-Policy: default-src 'none' 
X-Content-Type-Options: nosniff Content-Type: text/html; charset=utf-8 Content-Length: 140 
Date: Fri, 03 Apr 2020 21:20:29 GMT 
Connection: close  
<!DOCTYPE html> 
<html lang="en"> 
<head> <meta charset="utf-8"> 
<title>Error</title>
 </head> 
<body> <pre>Cannot GET /r</pre> </body> 
</html>

Folder Structure

The code we have just written is working just fine but to make it standard, we should not put all our code into a single script, with the time being, it will a large file with lots of coding and you will find it difficult to write more features. To solve this problem, we are going to split our code into several scripts. In our server.js, we are going to keep server handling code and we are going to create a different script that will contain all the routes. This script can be exported as a module and be called in server.js and all the endpoints should work like just before. Let’s create a new directory named ‘routes’ and create a file named ‘routes.js’.

mkdir routes
touch routes/routes.js

Let’s start writing code in routes.js. First, we will import express like before and then create an instance of express, but not in ‘app’ variable with ‘express()’, instead we are going to use as following:

const express = require(‘express’);
const router = express.Router();

Let’s take out the routing code from the server and place them in routes.js. We are going to replace our app.METHOD with router.METHOD. At the end, we need to export it as a module.

// GET requestrouter.get(‘/’, function (req, res) {
res.status(200).send(‘Server is up and running.’)
})// POST requestrouter.post(‘/’, function (req, res) {
res.status(200).send(‘This is a POST request’)
})// PUT Requestrouter.put(‘/’, function (req, res) {
res.status(200).send(‘This is a PUT request’)
})// PATCH Requestrouter.patch(‘/’, function (req, res) {
res.status(200).send(‘This is a PATCH request’)
})// DELETE Requestrouter.delete(‘/’, function (req, res) {
res.status(200).send(‘This is a DELETE request’)
})module.exports = router;

Now, we can use routes.js as modules and can call this module from our server.js. To do so, let’s add these following two lines to server.js:

const router = require(‘./routes/routes’)
app.use(‘/’,router)

There will be no routes in the server now. The final code of server.js will be as follows:

require(‘dotenv’).config()const express = require(‘express’); // importing Express
const app = express(); // instance of express
const port = process.env.PORT || 3000; // Defining port by environmental parameter or 3000const router = require(‘./routes/routes’)
app.use(‘/’,router)// App is listening to user-defined port or 300 and printing the information to the console.app.listen(port, function (req, res) {
console.log(`Server is listening on port ${port}!`)
})

Test the endpoints with the test.rest. It should return 200 http codes and all endpoints should just work fine.

Push your code to GitHub

Now you are done with coding and testing. Let’s push your code to your GitHub. I assume you have already installed git, else you can do so b following the command:

$ sudo apt install git$ git config — global user.name “username”$ git config — global user.email “email”

Run the following command to push your code to GitHub (It may ask for your git username and password) :

$ git add .$ git ommit -m “Your commit message”$ git push

Congratulations on your first rest api development! I enjoyed a lot writing these first two parts and I hope you have also enjoyed reading and creating your first API. In the next part, I am going to cover some more important topics. Ask me any questions if you face any kind of difficulties during following this article.