Creating Basic Rest API using Node JS

Ivan
6 min readJul 13, 2021

REST API stands for REpresentational State Transfer , which defines a set of principles on how Web standards are supposed to be used. This is a very common standards that a huge majority of the web / mobile applications run on.

The goals of REST are :

  • Generality interfaces
  • Reduce latency and thus improve performance
  • Scalability of interactions between components
  • Reliable

This article provides a basic guide on how to create a API using Node JS. There are many ways of creating a Rest API, and you should refer to right tutorials for other languages.

To use Node JS, I assume you have some knowledge of Java or JavaScript. Node JS runs on JavaScript.

Part A

Installation of Node JS and Visual Studio Code (IDE)

  1. Download Node JS from this link. Install the package, with package at least 14.17 (current as of today)
  2. Create a folder name “testapi” in your command prompt

mkdir testapi

Go to your folder testapi in your command prompt or terminal

3. Create a package.json file . package.json contains information about your libraries that you need, the metadata of your projects etc.

npm init

4. Install a IDE. A IDE is a development software for building application. For this, I am using Visual Studio Code, which can be downloaded in here .

Installing Postman

Postman is useful for testing APIs. I recommend that you install it. Postman can be downloaded from here

Libraries

  1. We will need the following libraries for this project
  • ExpressJS. Express JS is a flexible and light framework for developing web and mobile APIs

npm i express --save-dev

Package.json file

Your package.json should look like this

Creating files

  1. Create the following files under testapi/
  • server.js

File directory structure

The file folder testapi should look like this

Part B

Type of HTTP Request Methods

There are 7 types of HTTP methods. Some of them are very common such as Get and Post. The 7 are

  • Get
  • Post
  • Put
  • Head
  • Delete
  • Patch
  • Options

Get Method

Get is used to request data from specified resources. Example

http://localhost:3000?name=value

Get requests are

a. Cached

b. Can be bookmarked

c. It is not encrypted and should not be used when dealing with sensitive data

d. There is a length restrictions of 2048 characters

e. It can be stored in browser history

f. Not secure

Post Method

Post is used to send data to a server which will create or update a resource. Note that Post Request are :

a. Never cached

b. Do not remain in browser history

c. Have no restriction on data length

d. Cannot be bookmarked

Post is the most common and recommended if you want a more secure request.

Put Method

Put is used to send data to server to update and create a resource. The difference between Post and Put is that in put method, you modify a single resource. Post is called when you have to add a child resource under a resources collection.

Delete Method

Delete method delete a specified resources

Head Method

Head method is useful if you want to make the same request as Get , but instead check what the Get request will return. This is crucial especially when you are downloading a large file or response body. Head method only ask for the information about the document, not the document itself. It is much faster than Get

Options Method

Options is one of the least less used. It is use to describes the communication options for the target resources.

Part C

Creating your first Rest API

  1. Open up the file server.js under testapi/ folder using Visual Studio Code

A. Create basic file structure

Import Express JS

Type this in server.js

const express = require('express')

B. Set the Port to port number 3000

We want to listen to the specific port number actively. In your machine or on a server hosted somewhere, there are several ports that other services used. 3000 (or 3001 or 3002) is a safe and common number that you can used. Port number is where the client can reference to a specific service.

Add this to server.js

const port = 3000

app.listen(port, () => {
console.log('Server is up on port ' + port)
})

C. Mount Express as a middleware and prepare it for API endpoints

Express JS help to create easily API endpoint. It act as middleware for your application. In this case, we need to use app.use() to let the service for. We will also need to specific “json” in the parameter as we are using JSON.

Add this after “const port=3000” but before the listening port statement

const app = express()

app.use(express.json())

D. Creating a Get Method

Let’s create our first Get Method. Input this

app.get ("/", (request,response)=>{
response.send ("This is my first GET method!")
})

You will see 2 parameters — “request” and “response”. The HTTP request and response are how data exchanged between the server and client. Request is sent by the client to trigger an action on the server. Response is the answer from the server.

In here, we only use response, and we will send our first message

E. Create a Post Method

We shall create our Post Method. Let’s say that we need the user to give the parameter “message” so that we can print it out. We call this variable as the key “message” .

Creating a Post end point is similar to a Get. There are some differences. Input this and you will see the similarities and differences.

app.post ('/testpost', (request,response)=>{
response.send ("Message by you : " + message)
})

server.js

These is the code for server.js

const express = require('express')

const port = 3000

const app = express()

app.use(express.json())

app.get ("/", (request,response)=>{

response.send ("This is my first GET method!")
})

app.post ('/testpost', (request,response)=>{

response.send ("Message by you : " + message)
})

app.listen(port, () => {
console.log('Server is up on port ' + port)
})

Part E

Testing our server

A. Launch the Server from Our Local Machine

Go to command prompt / terminal under testapi/ folder. Input this :

nodemon server

You should see something like this in your command prompt / terminal

B. Open up Postman

Create a collection (under Collections menu) and Add a Request. set the parameters as “localhost:3000” for the first request Get and the second Post request “localhost:3000/testpost” . For Post , you will need to add in the parameter key under Body (see below image) and set it as JSON.

Run it . You should see the result for the Get and Post

Get Request and result in Postman

Post Request and result in Postman

This is only a very brief tutorial on creating API and testing them, however it should be sufficient to move on your own to deeper topic if you are able to do it.

For Git repo, you can go here.

Date created : 6 June 2021

--

--

Ivan

I am a Software Engineer and Psychotherapist. Follow me on Linkedin at linkedin.ivantay.org