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:
Using Restify to Create a Simple API in Node.js
Next article icon

How to create a REST API using json-server npm package ?

Last Updated : 06 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

This article describes how to use the json-server package as a fully working REST API.

What is json-server?

json-server is an npm(Node Package Manager) module/package, used for creating a REST API effortlessly. Data is communicated in JSON(JavaScript Object Notation) format between client and server.

Installation: Execute the below command in your project directory.

npm install json-server

Creating a database file: The data is stored in JSON format. Create a .json file that stores the data in JSON format. This JSON file works as a database. for example, we name the database file db.json. json-server recognizes the id attribute specially and treats it with unique constrain. This attribute is useful in getting data accessed individually by id.

Note: double quotes must be used for string value-pairs, and value pairsThe last key-value pair should not be followed by a comma.

Let data be:

{
"students": [
{
"id": 1,
"name": "alex",
"grade": 11,
"marks": {
"maths": 80,
"physics": 50,
"chemistry": 35
}
},
{
"id": 2,
"name": "gary",
"grade": 12,
"marks": {
"maths": 70,
"physics": 50,
"chemistry": 65
}
},
{
"id": 3,
"name": "stuart",
"grade": 11,
"marks": {
"maths": 80,
"physics": 20,
"chemistry": 90
}
}

]
}

Running the json-server: json-server uses port 3000 as default and the server can be run using the command 3000

json-server db.json

Note: db.json is the name of the JSON file.

Running server on an alternative port: The command to run the server on the alternative port number is

json-server db.json --port PORT_NUMBER

Running a live serve: To get the server updated/re-run on manual changes in the .json file use the command

json-server --watch db.json

On running, the json-server module generates a home route for the data server which can be accessed through the URL "http://localhost:3000" (if the port is 3000)

Reading data from the database:

We use the GET method to request data from the server. Higher order attribute in our json includes student object which contains records of the student. As json-server automatically generates routes for higher order attributes.

Example: 

1. Retrieving all students

The URL to request Student data from the database is http://localhost:3000/students (the server is running at port 3000).

Below GIF shows get to request which is done in thunder client (An extension in vs code). Tools like postman and web browsers can also be used.

2. Retrieving student by id

Note: id in json-server data is treated as a special attribute. The server allows data only with the unique id. 

The URL to retrieve students by their id is http://localhost:3000/students/1 This URL retrieves the student data whose id is "1". This URL pattern doesn't work for other attributes like name, grade, etc.(http://localhost:3000/students/name doesn't work). The below GIF shows the working of this request.

Adding data to the database:

We use the post method to send data requests to the server. HTTP post method sends a request to the server with data in the request body.

Example: URL to add data to the database is http://localhost:3000/students with post method. let's data to be added is 

{
"id": 4,
"name": "binny",
"grade": 12,
"marks": {
"maths": 90,
"physics": 100,
"chemistry": 20
}
}

The below GIF shows the execution of the post method and updated data in the database:

Updating data in the database:

We use the HTTP PATCH method to update data in the database. This method sends a request to the server to update the data where the data to be updated is in the request body.

Example: The URL to update data in the database is http://localhost:3000/students/4 with the patch method. This method updates the data of the student with id "4" with data in the request body. Let's data to be updated is 

{
"name": "bunny"
}

The name of the student will be changed to bunny on successful request. The below GIF shows the working of the patch method.

Deleting data in the database:

We use the HTTP DELETE method to delete data in the database. This method sends a request to the server to delete the data. The data to be deleted is specified in the request URL.

Example: The URL to delete the student with a particular id is  http://localhost:3000/students/4 with the delete method. This method deletes the data of the student with id "4".The below GIF shows the working of delete method.


Next Article
Using Restify to Create a Simple API in Node.js

P

pcssai
Improve
Article Tags :
  • Web Technologies
  • Node.js

Similar Reads

    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
    Using Restify to Create a Simple API in Node.js
    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 RE
    6 min read
    How to create mock servers using Postman
    Postman is a comprehensive API platform used by developers; this platform provides a set of tools that support API design, testing, documentation, mocking, and API Monitoring. It also simplifies each step of the API lifecycle and streamlines collaboration, enabling developers to create and use APIs
    7 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 Make A GET Request using Postman and Express JS
    Postman is an API(application programming interface) development tool that helps to build, test and modify APIs.  In this tutorial, we will see how To Make A GET Request using Postman and Express JS PrerequisitesNode JSExpress JSPostmanTable of Content What is GET Request?Steps to make a GET Request
    3 min read
    How to Post JSON Data to Server ?
    In modern web development, sending JSON data to a server is a common task, especially when working with RESTful APIs. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write for humans and easy to parse and generate for machines. This article will gu
    4 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