Loading...

Node API Tutorial – How to create REST API with Node.js?

Node API Tutorial – How to create REST API with Node.js?

To facilitate better communication between the client and the server, developers use APIs and microservices to enhance the quality of their code and the efficiency of the product they are building. NodeJS is a popular runtime that JavaScript developers are using. In this article, we first understand what NodeJS and API are. It will serve as a refresher for experienced developers and as an introduction to NodeJS API for developers. After getting an understanding of the two most essential components, we will then understand what different HTTP methods GET, PUT, POST, PATCH, and DELETE are, look at how we can create our REST API, understand what the REST architecture is and check the responses of the requests we make on a popular testing tool – Postman. The output of the Postman workspace has also been provided in this article which the readers can compare while sending requests to their API in their workspace.

Readers are requested to use the codedamn playground to execute the code snippets provided in this article and follow the instructions step-by-step as you read along to get a better insight into the building and the working of the REST API that we are going to create.

What is NodeJS?

NodeJS is an open-source run time that uses javascript for its functioning. The advantage NodeJS holds over others is that it carries out the process of performing tasks without being dependent on the result of the previous task. In other words, it does not wait for the results of the last task and completes the new task as soon as the resources are available. NodeJS also have specific libraries/packages which can be used in a project with the help of NPM, Node package manager.

What is REST?

REST stands for Representational State Transfer. For a client and a server to communicate with each other, rules must be followed for lossless communication. REST takes care of those rules and carries out the communication. Rest is stateless, has a uniform interface, and is cacheable. It has a layered system that allows each layer to focus on its functionality without knowing about other layers. It should also have a server-client architecture, where the server and client are dependent on their work, i.e., the server need not know about the front UI, and the client need not worry about the backend logic.

What are APIs?

APIs stand for an Application Programming interface. API is a mediator that allows two software or programs to talk with each other. To understand it better, API plays the same role as a waiter in a restaurant. It takes the request to the server from the client and brings the formulated result back to the client without the other two parties ever interacting with each other. That is, the role of the server and client is abstracted from each other by an interface, i.e., the API. APIs offer humongous functionality to the developers by performing complex computations on one end and not disturbing the actual logic of the code or making it prone to errors or even making it bulky. API first development is slowly and steadily coming up as the next big thing in software development.

Understanding REST API Architecture

A REST architecture consists of a few components:

  1. Methods: Every request caters to different methods implemented by REST to perform certain functions like create, read, update, or delete, usually shortened to CRUD operations. Some methods under REST are:
    1. GET: Fetch the resource from the server and provide it to the client. This method does not modify any data. 
    2. POST: Produce new data on the server as requested by the client. 
    3. PUT: Updates, replaces or creates a resource.
    4. PATCH: Updates the existing resource.
    5. DELETE: Deletes the existing record of resources from the database.
  2. Endpoint: This is the end of the medium of communication. In other words, this is where the server receives the request, and it is formulated. 
  3. Headers: Since REST is stateless, additional information is sent in the headers. Request and Response are two well-known headers.
  4. Data: This is the part that contains the information to be sent to the server.

Creating a Nodejs API

After knowing the basics, let’s hop onto an example to understand how REST API works and how you can write your Nodejs API that performs CRUD operations.

Tools needed:

  • NodeJS: Latest NodeJS version installed in your system, with node and npm available in your path.
  • Postman: Postman is a tool that allows developers to build and use APIs.

We will create a Nodejs API that implements a phone book.

  1. Create a new directory phone book.
  2. Initialize node project 
  3. As a package, we will use Express and import Express and FileSystem to read the JSON object we created locally. 
  4. To begin, create a file and name it server.js. We will import express. The express server is initialized and stored in variable named apps. We will also initialize body-parser and set our server on the port to listen on 5000.

Let’s create a JSON file that stores our phone book details:

Create a phone-book.json file and add the following:

This JSON object contains a person’s name, number, and unique ID to differentiate them.

We will carry out the following methods in our tutorial:

  1. Create a server, and get a response.
  2. Get phoneBook JSON on our REST client, i.e., POSTMAN
  3. Update our resource with another entry
  4. Delete an existing object in our resource.
{ "person-1" : { "name" : "Mahendra", "phone-number" : "9282671829", "id": 1 }, "person-2" : { "name" : "Satya", "phone-number" : "8816791737", "id": 2 }, "person-3" : { "name" : "Roshan", "phone-number" : "9273918281", "id": 3 } }
Code language: JSON / JSON with Comments (json)

Starting our ExpressJS Server

The code below will import Express, FileSystem (fs), and initialize our ExpressJS server as an app on 5000 port.

const express = require("express"); const fs = require("fs"); const app = express(); app.get("/", (req, res)=>{ res.send("Hello World") }) app.listen(5000, () => { console.log(`Server is running on port 5000.`); });
Code language: JavaScript (javascript)

App.get accepts two parameters, a path, and a call back function. Further, the callback function contains two parameters: 

  1. Req: Also known as request. This parameter takes our data to the server.
  2. Res: Also known as a response. This parameter is the result of whatever is returned by the server.

On the terminal input node server.js

Verifying ExpressJS Server Works on Postman

Go to POSTMAN, create your credentials, and create a new workspace (NEW).

To process our request, put localhost:5000/ in the search box after choosing the GET method from the dropdown. You will see your response.

Creating a GET request with Nodejs API

We will write our first GET request for our Nodejs API by using the code below.

app.get('/phoneBook', (req, res) =>{ fs.readFile( __dirname + "/" + "phone-book.json", 'utf8', (err, data)=> { console.log( data ); res.end( data ); }); })
Code language: JavaScript (javascript)

The above code reads our phone-book.js and passes it to the server, which processes the GET method and represents our data as a response.

Viewing the results of GET request on Postman

To process our request, put localhost:5000/phoneBook in the search box after choosing the GET method from the dropdown.

You will see your response.

Creating a POST request with Nodejs API

To add a new person, we need to create a POST request for our Nodejs API. Please create a new variable, person4, and add it in the JSON format.

var person4 = { "person-4": { name: "Ashwin", "phone-number": "9289471829", id: 4, }, }; app.post("/AddUser", (req, res) => { fs.readFile(__dirname + "/" + "phone-book.json", "utf8", (err, data) => { data = JSON.parse(data); data["person-4"]= person4["person-4"] console.log(data); res.end(JSON.stringify(data)); }); });
Code language: JavaScript (javascript)

Read the existing list of phoneBook and push your new data in the extracted list.

Viewing the results of POST request on Postman

To process our request, put localhost:5000/AddPerson in the search box after choosing the POST method from the dropdown.

You will see your response.

Showing Details Using Unique ID with Nodejs REST API

Implement the code below to process the details of only one person as per the ID with our Nodejs API. We will read our existing resource, ask for the ID passed in input as a request, and display that particular ID.

app.get("/:id", (req, res) => { fs.readFile(__dirname + "/" + "phone-book.json", "utf8", (err, data) => { var people = JSON.parse(data); var person = people["person-"+req.params.id] console.log(data); res.end(JSON.stringify(data)); }); });
Code language: JavaScript (javascript)

Viewing the response of Unique ID on Postman

To process our request, put localhost:5000/2 in the search box after choosing the POST method from the dropdown. You will see your response.

Creating a DELETE request with Nodejs API

This section also implements taking an ID and deleting it from the resources using our Nodejs API. The data will be extracted from the existing resource, and the ID passed in the request will be deleted.

app.delete("/:id", (req, res) => { fs.readFile(__dirname + "/" + "phone-book.json", "utf8", (err, data) => { data = JSON.parse(data); delete data["person-"+req.params.id] console.log(data); res.end(JSON.stringify(data)); }); });
Code language: JavaScript (javascript)

Viewing the results of the DELETE request on Postman

To process our request, put localhost:5000/2 in the search box after choosing the DELETE method from the dropdown. You will see your response.

Summary

  • NodeJS is a runtime environment that implements Javascript. It rules out waiting for a response from the previous task.
  • REST is an architectural style used on web services and has certain constraints to communicate efficiently between the server and the client.
  • APIs work as mediators between two software and allows them to communicate as a waiter acts as a medium between the customer and the chef. 
  • REST involves different methods: GET, POST, DELETE, and PUT, allowing CRUD operations on the resources. 
  • We can implement REST API using ExpressJS by hosting our server and using REST methods to perform various operations.

Read more about learning paths at codedamn here.

Happy Learning!

Sharing is caring

Did you like what Pooja Gera wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far