RESTful APIs/ RESTful Services with Node JS and Express Dependency

Amir Mustafa
10 min readFeb 18, 2019

--

→ First let’s talk about the REST (Representational State Transfer)

All application these days follows this structure

App = App itself is Client / Front end part

Server = Under the hood app needs to talk to Server / Backend to get or save the data

This communication happens with the help of HTTP Protocol, the same protocol that powers the web

→ On the server there are the bunch of services that are accessible through HTTP Protocol. The client can directly call this services by sending HTTP request.

→ This is where REST comes into the picture. REST = Representational Transfer

→ We will be doing CRUD Operations using REST

→ Lets talk about the http://vidly.com/api/customers

https:// = protocol

vidly.com = domain

api = basic convention to use term api somewhere in the url

customers = resources (This is the end point)

→ Every http request has the verb/method that determines is type or intention

GET = For getting data

POST = For creating data

PUT = For updating data

DELETE = For deleting data

(a) GET

(b) POST:

(c) PUT (for update):

(d) DELETE:

→ So throughout the section we will learn how to use the express framework to build the RESTful service for managing the list of customers (Without database — we will be using array)

→ This is the basic server created in node js. This is good, but when there are lots of routes and if conditions within the server.

→ Here framework comes into picture. A framework gives the application proper structure, so we can add as many routes while keeping our code maintainable. Most popular framework is express. It is fast, light weight and perfectly documented

→Go to npm and search express:

(1) Installation

Open the terminal in new project folder and

Type: Run below commands

a. npm init –yes

Now we have package.json file created in project

b. npm i express

(2) CREATE THE EXPRESS WEB SERVER

a. Create the index.js file

First we load the express module and call the express function. Now this express method have the bunch of useful methods like

We discussed this earlier about requests.

(3) Lets start with GET Request:

app.get contains 2 parameter:

1st = route/path in url, 2nd = callback function with message

app.listen contains 2 parameters:

1st = port number, 2nd (optional)= message

Lets run in terminal:

In Browser:

Lets create another request

In /api/courses mainly deals with databases, we will deal will array to understand express

Stop and restart the server in terminal:

Browser:

So array comes here. We can move all the routes related with /api/courses to a separate js page like courses.js

(4) Nodemon

→So far we have seen every time we have to make change in the code we have to stop the server in the terminal and restart it which is a very tedious way.

→ For this we have to install the js package called nodemon shortened for Node Monitor which works to stop the package.

npm i -g nodemon //g is for global installation, i is for install

→ Instead of node index.js, we will write nodemon index.js in terminal

Suppose you make some changes in code eg. string in terminal nodejs will be automatically be written

Though you need refresh the browser, but no need to restart the terminal server.

(5) Environment Variable

→ In real time giving port 3000 does not work in production(server) which is dynamically assigned. For test we can use any port of our choice

→ For this environment variable is used.

Instead of static port, we have taken in a constant and of environment port is present take that other wise second constant

è We have also used back ticks in message to show port it is using. At present will show 3000 as nothing .

SET ENVIRONMENT VARIABLE: (Try running from command prompt/terminal and not from editor terminal)

In MAC/LINUX:

export PORT=1234

In Windows:

set PORT=1234

Now run nodemon index.js

(6) Route Parameters:

→ Through route params we get single set of record by passing id in the request

Multiple parameters:

We can pass as many no. of paramaters eg if we pass date and year

Browser: (request params object)

(7) Query String Parameters:

→ What ever we give after question marks is query parameters

Eg: In url: http://localhost:3000/api/posts/2018/1?sortBy=name

/2018/1= route params

Bold in url= query string params

Eg 2: http://localhost:3000/api/posts/2018/1?sortBy=name&code=5

Browser:

Query Parameters = Used for additional data for the backend services /optional values

Route Parameters = Used for essential or required values

(8) Handeling GET Requests

→ Here we will take list of courses and will find will try to find specific course.

→ If course is found return that course otherwise show message of course not found

Eg: index.js

Browser:

a. Unknown id

b. Id present in course array:

You can also check in the dev tools:

(9) Handeling POST Requests

→ Here we will see how POST Request is sent

Eg. here we are using array: therefore length+1, in real time data will come from db.

Here we are assuming in the request body there is object and and that object has the name property.

Eg. name: req.body.name

In order to use this we have to enable parsing of JSON objects in the body of the requests

→ This is the software/chrome extension through which we can check all types of requests like GET, POST, PUT, DELETE etc. With browser we usually check GET request.

→ Adding express.json() in top

express.json() is adding a piece of middleware. We use this middleware in the request processing pipeline. We will explore this more later in the section.

→ Finally we will push the new course in the courses array.

Postman:

→ Download chrome Postman extension and make a new collection related with the project.

→ Now run the above code in postman, POST request and in body(select raw and json/application from other dropdown instead of text)

Request:

Response:

→ So now when you hit get request you will get 4 data (including the new data inserted from POST

So this is how we test HTTP services in postman

→ For this we have assumed there in name parameter in body. If we forget to put name or misspelled that’s where input validation comes into the picture

(10) Input Validation

→ We should always validate whatever is sent through client(i.e. from Postman). If not found or required conditions does not match will throw 400 i.e. Bad Request.

return is for stopping remaining code

Eg.

Name validation:

Length validation:

Ok condition:

→In real time validation will be complex. For this there is a npm package manager called joi

(11) JOI

→ Joi is the input validation npm package manager

https://www.npmjs.com/package/joi

→ Install joi in project

npm i joi

For getting specific version: npm I joi@13.1.0

→ We will first include Joi in top with J capital in

→ With joi first we need to define a schema.

A schema defines the shape of our objects. What properties do we have in that object. What is the type of each property. Do we have an email? Do we have the string.? Do we have min or max no. of characters? Do we have the numbers? What range should that number be?

→ So this is the job of the schema

If we send wrong validation like name not mentioned: will throw error in terminal

If Ok

→ So we will write like this:

(12) Handeling PUT Request (Update the data)

→ Here we will see how to update a course. We will handle following course as commented step by step

→ We have to update specific id therefore params (i.e. /:id) is required

POSTMAN

→ We see the course with ID 1 is updated from course 1 to new course 2 after clearing all validations:

(13) Handeling Delete Requests

→ We need to delete specific id there params is requires (i.e. :id)

→ To delete an element from array special method splice is used

Eg1. delete element

Eg2. In the next example we remove 3 elements and replace them with the other two:

→ Lets see it in program:

Postman:

(a) Delete Request:

(b) Course with id 1 removed

--

--

Amir Mustafa

JavaScript Specialist | Consultant | YouTuber 🎬. | AWS ☁️ | Docker 🐳 | Digital Nomad | Human. Connect with me on https://www.linkedin.com/in/amirmustafa1/