Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Create a Simple Server Using ExpressJS?
Next article icon

Using Restify to Create a Simple API in Node.js

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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. Building a RESTful API is a common requirement for many web applications. Restify is a popular Node.js framework that makes it easy to create RESTful services. It’s lightweight, fast, and specifically designed for API development. In this guide, we will walk you through the process of setting up a simple API using Restify.

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

Installation Steps

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 rectify, we have to require the rectify package in our Server.js file. The code for requiring the package is very simple and is shown below:

const restify = require('restify');

Project Structure:

Screenshot-2024-06-21-163207

The updated dependencies in package.json file will look like:

"dependencies": {
"restify": "^11.1.0",
}

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:

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

Till now, we have allowed our to use rectify 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. The first one specifies the route("/:stateName" in this case) and the second parameter specifies the function that is to be triggered when the user goes on this route(send information 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 send information 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 send information function, which will send the state data 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 send information 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.

Example: Implementation to show the use of Restify to create a simple API in Node.js

JavaScript
// index.js

const 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
    }
]

let 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 index.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:

We can see that when we type "Rajasthan" in the route, we get data related to the state "Rajasthan". Similarly, if the 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".


Next Article
How to Create a Simple Server Using ExpressJS?

M

mananvirmani611
Improve
Article Tags :
  • Node.js
  • NodeJS-Questions

Similar Reads

    How to Create a Simple Server Using ExpressJS?
    The server plays an important role in the development of the web application. It helps in managing API requests and communication between the client and the backend. ExpressJS is the fast and famous framework of the Node.Js which is used for creating the server.In this article, we will create a simp
    3 min read
    How to Create A REST API With JSON Server ?
    Setting up a RESTful API using JSON Server, a lightweight and easy-to-use tool for quickly prototyping and mocking APIs. JSON Server allows you to create a fully functional REST API with CRUD operations (Create, Read, Update, Delete) using a simple JSON file as a data source. Table of Content GET Re
    4 min read
    How To Create a Simple HTTP Server in Node?
    NodeJS is a powerful runtime environment that allows developers to build scalable and high-performance applications, especially for I/O-bound operations. One of the most common uses of NodeJS is to create HTTP servers. What is HTTP?HTTP (Hypertext Transfer Protocol) is a protocol used for transferri
    3 min read
    Creating a REST API Backend using Node.js, Express and Postgres
    Creating a REST API backend with Node.js, Express, and PostgreSQL offers a powerful, scalable solution for server-side development. It enables efficient data management and seamless integration with modern web applications.This backend can do Query operations on the PostgreSQL database and provide t
    4 min read
    How to Generate or Send JSON Data at the Server Side using Node.js ?
    In modern web development, JSON (JavaScript Object Notation) is the most commonly used format for data exchange between a server and a client. Node.js, with its powerful runtime and extensive ecosystem, provides robust tools for generating and sending JSON data on the server side. This guide will wa
    3 min read
    How to Build a RESTful API Using Node, Express, and MongoDB ?
    This article guides developers through the process of creating a RESTful API using Node.js, Express.js, and MongoDB. It covers setting up the environment, defining routes, implementing CRUD operations, and integrating with MongoDB for data storage, providing a comprehensive introduction to building
    6 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences