How to Build a REST API

Priyanka Patwal
Last Updated: May 13, 2022

What is an API?

When you use an application, it connects to the Internet and sends information to a server. The server retrieves the data, interprets it, takes the appropriate actions, and sends it back to your phone. The software then analyses the data and displays the information you requested legibly. All of this happens via API, which is what an API is.

 

Let us try to understand API with a real-life example. Suppose you are at a restaurant and you ordered a dish. Now the dish is being prepared in the kitchen, but you are waiting at the table for the dish. There has to be an agent to bring the food from the kitchen to the table. In this case, that agent is the waiter. Similarly, API plays the role of a waiter in programming, who serves information between the server and the client. 

.

What is REST API?

REST API stands for Representational State Transfer and is a web service architecture pattern. Roy Fielding created it in 2000, and it has spawned an increasing number of RESTful web services that adhere to the REST principles. Because of how easily it communicates with other machines over sophisticated activities like COBRA, RPC, or Simple Object Access Protocol, REST APIs are now widely used by application developers (SOAP).

 

REST is a collection of principles that describe how to share data between clients and servers in the most efficient way possible. It's essentially a design philosophy for designing HTTP or other APIs that requires you to use just CRUD methods, no matter how sophisticated they are. HTTP methods such as GET, POST, DELETE, and PUT are used in REST applications. 

 

An API has to follow the below rules to be a REST API:

  • Client-server: REST applications feature a server that manages the data and state of the application. The server connects with a client, which is responsible for handling user interactions. A clear separation of concerns separates the two components. As a result, you'll be able to update and upgrade them in separate tracks.
  • Stateless: Client state is not maintained by the server; instead, clients control their application state. The information required to process the client's requests is contained in the client's submissions to the server.
  • Cacheable: Servers must tell in advance whether or not their results are cacheable. In order to boost performance, systems and clients might cache results when necessary. They also delete non-cacheable data, so no client has to deal with stale data.
  • Uniform interface: The most prominent feature or guideline of REST is its uniform interface. The highlight of a uniform interface between components is the primary aspect that distinguishes the REST architectural style from other network-based approaches. REST services give data in the form of resources with a standardized namespace.
  • Layered system: Components in a layered system cannot look through the layer they are in. This restricted scope makes it simple to add load-balancers and proxies to increase authentication security and performance.

 

The core functions used in any REST-based architecture are:

  • GET − Provides read-only access to a resource.
  • PUT − Creates a new resource.
  • DELETE − Removes a resource.
  • POST − Updates an existing resource or creates a new resource.

 

Building a REST API using node.js

To build an API using Node.js, we need to install the following:

  1. Node.js
  2. Express.js
  3. Joi
  4. Nodemon

First, we need to create a project folder. Next, in the command prompt and navigate to your project folder. Once there, we have to call npm using the command below :

npm init

 

Now,  Node.js will ask you to enter some details to build the .json file

Next, we will be installing Express.js using the below command:

npm i express

 

Finally, we’ll set up Nodemon, a software for monitoring nodes. It maintains track of all files in this folder that have any type of extension. We also don't have to restart the Node.js server every time we make a change with Nodemon on the monitor. Nodemon will detect the modifications and automatically restart the server for us.

npm i -g nodemon

 

Now, we can start coding our APIin the js file.

We can use the CRUD methods such as GET, POST, PUT and DELETE of the REST API.

The first step is to include the packages we installed:

const express = require('express');
const app = express();
var port=3000;
app.use(express.json());

 

Now, the next step is to read data and send the data using a GET method:

app.get("/test_data", (req, res) => {
            //get the data in var data
            res.send(data);
    });
});

 

We can also use the POST method to save to our database:

app.post("/register", function(req, res){
 //get the data to be posted
});

 

Similarly, DELETE and PUT methods can also be used in creating a REST API.

Finally, we need to set a port for the REST API to listen from:

app.listen(port, () => {
    console.log(`app listening at http://localhost:${port}`)
  });

 

Finally, we have to expose our server to the internet using Ngrok. To do so, we need to run the ngrok executable after the Express server is up and running on port 3000( in our case).

In the directory where the ngrok executable is, we have to run the following command:

./ngrok http 3000

On successful execution we see the following screen:

ngrok by @inconshreveable
Session Expires               7 hours, 59 minutes
Version                       2.3.35
Region                        United States (us)
Web Interface                 http://127.0.0.1:4040
Forwarding                    http://367f23f4ca81.ngrok.io ->        http://localhost:3000
Forwarding                    https://367f23f4ca81.ngrok.io       ->    http://localhost:3000
Connections                   ttl     opn     rt1     rt5     

Here Session Expires indicates the time duration for which the urls will be valid if the ngrok does not stop.

We have to note down both forwarding URLs and the Web Interface URL.

Once we  start making requests to the server, a listing of every request will appear under the heading “HTTP Requests”.

Now our REST API is ready to be tested.

 

We can test our REST API using an application called Postman. Using this app, we create an artificial request( either GET or POST), and the app gives us results based on the parameters passed and processed by our API.

 

Frequently asked questions

  1. What is an API?

Ans:  An API is a communicator between the server and the client.

 

2. What is a REST API?

Ans: REST is a collection of principles that describe how to share data between clients and servers in the most efficient way possible.

 

3. What are REST principles?

Ans: An API has to follow the below rules to be called a REST API:

  • Client-server: REST applications feature a server that manages the data and state of the application. The server connects with a client, which is responsible for handling user interactions. A clear separation of concerns separates the two components. As a result, you'll be able to update and upgrade them in separate tracks.
  • Stateless: Client state is not maintained by the server; instead, clients control their application state. The information required to process the client's requests is contained in the client's submissions to the server.
  • Cacheable: Servers must tell in advance whether or not their results are cacheable. In order to boost performance, systems and clients might cache results when necessary. They also delete non-cacheable data, so no client has to deal with stale data.
  • Uniform interface: The most prominent feature or guideline of REST is its uniform interface. The highlight of a uniform interface between components is the primary aspect that distinguishes the REST architectural style from other network-based approaches. REST services give data in the form of resources with a standardized namespace.
  • Layered system: Components in a layered system cannot look through the layer they are in. This restricted scope makes it simple to add load-balancers and proxies to increase authentication security and performance.

 

4. What are the core functions of a REST API? 

Ans:  The main function of REST are:

  1. GET
  2. POST
  3. PUT
  4. DELETE

Key Takeaways

An API is a communicator between the server and the client.

REST is a collection of principles that describe how to share data between clients and servers in the most efficient way possible.

An API has to follow the below rules in order to be called a REST API:

  1. Client-server
  2. Stateless
  3. Cacheable
  4. Uniform Interface
  5. Layered system

We can build a REST API using the main functions like GET, POST, PUT and DELETE.

To know more about CRUD function visit Handling Requests in RESTful API 

 

Happy learning!

 

Was this article helpful ?
0 upvotes