Skip to content
Related Articles
Open in App
Not now

Related Articles

Using Restify to create a simple API in Node.js

Improve Article
Save Article
  • Last Updated : 24 Jan, 2023
Improve Article
Save Article

Restify is an npm package that is used to create efficient and scalable RESTful APIs in Nodejs. The process of creating APIs using Restify is super simple.

But firstly, if you are not familiar with what APIs are and want to know more, you can refer to the article here.

This article is going to contain the following things:

  • Installing Restify and creating a server using Restify in our simple Nodejs App.
  • Creating a simple API and passing the required data to the client.
  • Testing the API created on our local system.

For simplicity purposes, we are going to make an API using Restify that will provide us with the following:

Based on the name of the state entered in the route, the API will give us the data about basic information about the state, i.e., its capital, languages, etc.

A Live example of what we are going to build is shown in the image below:

When we type “Rajasthan” in the route and press enter, we get information about the state “Rajasthan”

So the procedure for building the API using Restify is given below:

Step 1: Firstly, create a Server.js file in a new folder/directory, and then initialize npm by entering the command given below in the command line:

npm init -y

Step 2: Then, we have to install our required package called “Restify” by executing the command below in the command line:

npm install restify

Step 3: After installing restify, we have to require the restify package in our Server.js file. The code for requiring the package is very simple and is shown below:

var restify = require('restify');

Implementation: Now that we have installed the package, we can now create a server using Restify in our Server.js file. The code for that is given below:

var server = restify.createServer();
server.listen(8080, function () {
    console.log("server is listening on port 8080");
});

Till now, we have allowed our to use restify, and also created a server that listens on port 8080.

Now we can create different routes, which will allow the client to get data from our API.

In our Server.js file, we have to add the following code:

server.get('/:stateName', sendInformation);
function sendInformation(req, res, next) {
    // this is the function which will get 
    // triggered when the /:stateName route
    // will be called
    res.send("Got the request");
}

Explanation of the code written above:

  • The server.get() function has two parameters. First one specifies the route(“/:stateName” in this case) and the second parameter specifies the function that is to be triggered when user goes on this route(sendInformation in this case).
  • The semi-colon before the name in the route specifies that “name” is a parameter, and we can provide different data to the user based on this parameter.

Now, for sending data, we are going to make a constant variable(containing all the information related to states) which we will use in the sendInformation function as per the parameters given by the user.

const stateData = [
   {
       state: "Rajasthan",
       capital: "Jaipur",
       regionalLanguages: ["Marwari", "Rajasthani"],
       noOfDistricts: 33
   },
   {
       state: "Punjab",
       capital: "Chandigarh",
       regionalLanguages: ["Punjabi"],
       noOfDistricts: 23
   },
   {
       state: "Uttar Pradesh",
       capital: "Lucknow",
       regionalLanguages: ["Braj", "Awadhi", ", Bagheli"],
       noOfDistricts: 75
   },
   {
       state: "Gujarat",
       capital: "Gandhinagar",
       regionalLanguages: ["Gujrati"],
       noOfDistricts: 33
   },
   {
       state: "Kerala",
       capital: "Thiruvananthapuram",
       regionalLanguages: ["Malayalam"],
       noOfDistricts: 14
   }
]

For simplicity and the purpose of explaining, we have taken the data from 5 states only.

Till now we have created our data object, along with the simple route “/:stateName”(with name as the parameter), now we are going to code inside the sendInformation function, which will send the stateData to the user.

The code for this is given below:

function sendInformation(req, res, next) {
   // req.params represents the parameters 
   // in the request(which is "name")
   let stateName = req.params.stateName;

   // iterating in the whole array of stateData so as to 
   // find the state entered by the user.
   for (let i = 0; i < stateData.length; i++) {
       
       //if the name given by user matches the 
       // with any object's state.
       if (stateName == stateData[i].state) {
           //sending the data through res.send() function.
           res.send(stateData[i]);
       }
   }
}

Explanation of the code written above:

  • “req.params” allows us to fetch the values of parameters in our request. So, we used “req.params.stateName” to know which state’s data the user is asking for and stored it in a variable called “stateName”.
  • After this, we iterate in the whole array using a simple for loop, and inside the for loop, we seek the state which matches the name of the state entered by the user in the request.
  • And if any state in the stateData array matches the state entered by the user, we will send the entire state data using the res.send() function.

Till here, we created a simple route and used sendInformation function to send data to the user. Hence, we are now complete with our simple API using Restify, which basically allows the user to fetch the data of any state. We can deploy this API on some free hosting platforms. But for now, we are only going to test it on our local system. Also, we can create some more complex APIs using Restify which may include some more complex data and logic.

Complete Code: Below is the complete running code of all the above steps:

Javascript




var restify = require('restify');
const stateData = [
    {
        state: "Rajasthan",
        capital: "Jaipur",
        regionalLanguages: ["Marwari", "Rajasthani"],
        noOfDistricts: 33
    },
    {
        state: "Punjab",
        capital: "Chandigarh",
        regionalLanguages: ["Punjabi"],
        noOfDistricts: 23
    },
    {
        state: "Uttar Pradesh",
        capital: "Lucknow",
        regionalLanguages: ["Braj", "Awadhi", ", Bagheli"],
        noOfDistricts: 75
    },
    {
        state: "Gujarat",
        capital: "Gandhinagar",
        regionalLanguages: ["Gujrati"],
        noOfDistricts: 33
    },
    {
        state: "Kerala",
        capital: "Thiruvananthapuram",
        regionalLanguages: ["Malayalam"],
        noOfDistricts: 14
    }
]
  
var server = restify.createServer();
function sendInformation(req, res, next) {
  
    // req.params represents the parameters 
    // in the request(which is "name")
    let stateName = req.params.stateName;
  
    // iterating in the whole array of stateData 
    // so as to find the state entered by the user.
    for (let i = 0; i < stateData.length; i++) {
  
        // if the name given by user matches 
        // the with any object's state.
        if (stateName == stateData[i].state) {
  
            //sending the data through res.send() function.
            res.send(stateData[i]);
  
        }
    }
}
  
server.get('/:stateName', sendInformation);
  
server.listen(8080, function () {
    console.log("server is listening on port 8080");
});


Steps to run the application: Write the below code in the terminal to run the server:

node server.js

NOTE: We can type “localhost:8080/” followed by the state that we require the data about in the address bar of our browser.

Output:

When we search “localhost:8080/Rajasthan” in browser, we get the data related to “Rajasthan”, and same for the state “Kerala”

We can see that when we type “Rajasthan” in the route, we get data related to the state “Rajasthan”. Similarily, if user wants to fetch data regarding the state “Kerala”, he/she would type “Kerala” in the route, and the desired data will be given to the user.

This is how REST APIs are created in Nodejs using the help of the package called “Restify“.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!