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 MySQL REST API
Next article icon

How to Create A REST API With JSON Server ?

Last Updated : 15 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Request Returns a List of all Users
  • POST Request to create a New User
  • PUT Request to Update an Existing User
  • DELETE Request to Delete a User

Approach

  • First, Create a JSON file that represents your data model. This JSON file will serve as your database.
  • Run JSON Server and point it to your JSON file using the command npx json-server --watch users.json.
  • Create four different JavaScript files to perform the operations like Create, Read, Update, Delete.
  • To Send a GET Request use the command in the terminal node get_request.js that returns a list of all users stored on the server, Send a POST request to create a new user, this will create a new user with the provided data.
  • Similarly, Send a PUT request to update an existing user. This will update the user with the provided data and for DELETE Request, The endpoint deletes the user with the specified id from the server. After deletion, the user will no longer exist in the database.

Steps to create a REST API with JSON Server

Run the below command to Create a package.json file:

npm init -y

Run the below command to Install the JSON Server globally using npm:

npm i -g json-server

Run the below command to Install Axios:

npm install axios

Project Structure:

Screenshot-2024-05-04-145653

Example: The example below shows the JSON file that represents your data model.

JavaScript
{
    "users": [
        {
            "id": "1",
            "first_name": "Ashish",
            "last_name": "Regmi",
            "email": "ashish@gmail.com"
        },
        {
            "id": "2",
            "first_name": "Anshu",
            "last_name": "abc",
            "email": "anshu@gmail.com"
        },
        {
            "id": "3",
            "first_name": "Shreya",
            "last_name": "def",
            "email": "shreya@gmail.com"
        },
        {
            "id": "4",
            "first_name": "John",
            "last_name": "aaa",
            "email": "John@yahoo.com"
        },
        {
            "first_name": "Geeks For",
            "last_name": "Geeks",
            "email": "gfg@gmail.com",
            "id": "5"
        }
    ]
}

Run the below command to start JSON Server and point it to your JSON file:

npm json-server --watch users.json

GET Request Returns a List of all Users

Example: In this example the endpoint returns a list of all users stored on the server. Each user object contains properties such as id, name, and email.

JavaScript
//get_request.js

const axios = require('axios');

axios.get('http://localhost:3000/users')
    .then(resp => {
        data = resp.data;
        data.forEach(e => {
            console.log(`${e.first_name}, 
            ${e.last_name}, ${e.email}`);
        });
    })
    .catch(error => {
        console.log(error);
    });

Run the below command to test the GET request:

node get_request.js

Output:

Ashish, Regmi, ashish@gmail.com
Anshu, abc, anshu@gmail.com
Shreya, def, shreya@gmail.com
John, aaa, John@yahoo.com
Geeks For, Geeks, gfg@gmail.com

POST Request to create a New User

Example: In this example, Send a POST request to create a new user will create a new user with the provided data.

JavaScript
//post_request.js

const axios = require('axios');

axios.post('http://localhost:3000/users', {
    id: "6",
    first_name: 'Geeks for',
    last_name: 'Geeks',
    email: 'gfg@gmail.com'
}).then(resp => {
    console.log(resp.data);
}).catch(error => {
    console.log(error);
});

Run the below command to test the POST Request:

node post_request.js

Output:

{
      "first_name": "Geeks For",
      "last_name": "Geeks",
      "email": "gfg@yahoo.com",
      "id": "5"
    }

PUT Request to Update an Existing User

Example: In this example, send a PUT request to update an existing user this will update the user with the provided data.

JavaScript
//put_request.js

const axios = require('axios');

axios.put('http://localhost:3000/users/5/', {
    first_name: 'Geeks For',
    last_name: 'Geeks',
    email: 'gfgofficial@gmail.com'
}).then(resp => {

    console.log(resp.data);
}).catch(error => {

    console.log(error);
});

Run the below command to test the PUT Request:

node put_request.js

Output:

{
  first_name: 'Geeks For',
  last_name: 'Geeks',
  email: 'gfg@yahoo.com',
  id: '5'
}

Above data is modified as

{
  first_name: 'Geeks For',
  last_name: 'Geeks',
  email: 'gfgofficial@gmail.com',
  id: '5'
}

DELETE Request to Delete a User

Example: In this example the endpoint deletes the user with the specified id from the server. After deletion, the user will no longer exist in the database.

JavaScript
//delete_request.js

const axios = require('axios');

axios.delete('http://localhost:3000/users/3/')
    .then(resp => {
        console.log(resp.data)
    }).catch(error => {
        console.log(error);
    });

Run the below command to test the PUT Request:

node delete_request.js

Output:

{
  id: '3',
  first_name: 'Shreya',
  last_name: 'def',
  email: 'shreya@gmail.com'
}

Next Article
How to Create a MySQL REST API

A

ayushbhankr3p
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • JSON
  • RESTful

Similar Reads

    How to create a REST API using json-server npm package ?
    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.I
    4 min read
    How to Create a MySQL REST API
    Creating a REST API is important for enabling communication between different software systems. MySQL is one of the most popular relational database management systems which serves as the backbone for data storage in web applications. In this article, we will learn how to create a REST API using MyS
    6 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
    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 create API in Ruby on Rails?
    Building APIs with Ruby on Rails: A Step-by-Step GuideRuby on Rails (Rails) is a popular framework for web development, known for its convention over configuration approach. It also excels in creating robust and maintainable APIs (Application Programming Interfaces). APIs act as intermediaries, allo
    3 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