Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Introduction to Spring Boot
Next article icon

Json-Server Setup And Introduction

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

What is JSON Server?

JSON-Server is an npm(Node Package Manager) module that allows you to create a mock REST API using just a JSON file. It is highly useful for prototyping, testing, or building front-end applications without needing a complex back-end infrastructure. Data is transferred in JSON(JavaScript Object Notation) format between client and server using HTTP methods like GET, POST, PUT, PATCH, and DELETE.

How to Set Up JSON-Server

Step 1: Install JSON-Server

To get started with JSON-Server, install it globally using NPM. Open your terminal and run the following command:

npm install -g json-server

This installs JSON-Server globally, meaning you can access it from anywhere on your system.

Step 2: Create a JSON Data File

Next, you need to create a JSON file that will act as your database. For example, you can create a file named db.json and structure it as follows:

{     "posts": [         {             "id": 1,             "title": "JSON-Server",             "author": "Amit"         },         {             "id": 2,             "title": "Node.js",             "author": "Mohit"         }     ],     "comments": [         {             "id": 1,             "body": "Great post!",             "postId": 1         },         {             "id": 2,             "body": "Informative!",             "postId": 2         }     ],     "profile": {         "name": "Amit Kumar"     } }

This JSON structure defines three endpoints:

  • /posts: to handle posts-related data.
  • /comments: to handle comments related to posts.
  • /profile: to represent user profile information.

Step 3: Start JSON-Server

Once you have created your db.json file, you can start the JSON-Server with a simple command:

json-server --watch db.json

This command will start the server and watch for changes in the db.json file. By default, the server will be hosted at http://localhost:3000, and you can start making HTTP requests to the endpoints defined in the JSON file.

Example: Testing Endpoints

Now that the server is running, you can test the following endpoints using an API client like Postman, or even directly from your browser:

1. GET all posts:

http://localhost:3000/posts

This will return all the posts from the db.json file.

2. GET a single post by ID:

http://localhost:3000/posts/1

This returns the post with an ID of 1.

3. POST a new post:

You can create a new post by sending a POST request to:

http://localhost:3000/posts

With the following JSON body:

{     "id": 3,     "title": "New Post",     "author": "Rohit" }

4. PUT (Update a post):

Update an existing post with:

http://localhost:3000/posts/1

Along with a new body, such as:

{     "id": 1,     "title": "Updated Post",     "author": "Amit" }

5. DELETE a post:

To delete a post:

http://localhost:3000/posts/1

Customizing JSON-Server

You can customize the behavior of JSON-Server in various ways to suit your needs.

1. Custom Routes

You can use a routes.json file to customize the routes of your API. For example, to alias the /posts route as /articles, create a routes.json file:

{     "/articles": "/posts" }

Now start the server with the custom routes file:

json-server --watch db.json --routes routes.json

Middlewares

JSON-Server allows you to add custom middlewares to extend its capabilities. Middlewares are useful for logging, adding authentication, or handling specific use cases.

For example, you can log requests using a middleware:

const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();

server.use(middlewares);

// Custom middleware to log requests
server.use((req, res, next) => {
console.log('Request received:', req.method, req.url);
next();
});

server.use(router);
server.listen(3000, () => {
console.log('JSON Server is running');
});


Next Article
Introduction to Spring Boot

P

pcssai
Improve
Article Tags :
  • JavaScript
  • Node.js
  • Web Technologies
  • JavaScript-Questions
  • JSON

Similar Reads

  • Introduction to MEAN Stack
    MEAN Stack is one of the most popular Technology Stack. It is used to develop a Full Stack Web Application. Although it is a Stack of different technologies, all of these are based on JavaScript language. MEAN Stands for: M - MongoDBE - ExpressA - AngularN - Node.js This stack leads to faster develo
    5 min read
  • Web Server and Its Types
    A web server is a system—either software, hardware, or both—that stores, processes, and delivers web content to users over the Internet using the HTTP or HTTPS protocol. When a user’s browser sends a request (like visiting a website), the web server responds by delivering the appropriate resources s
    7 min read
  • Introduction to Spring Boot
    Spring is widely used for creating scalable applications. For web applications, Spring provides Spring MVC, a commonly used module for building robust web applications. The major drawback of traditional Spring projects is that configuration can be time-consuming and overwhelming for new developers.
    5 min read
  • Production Level Directory Setup for Backend
    When we make a project, even a small project there are a lot of files & folders that have their importance. But to maintain it is very hectic. So It is an approach that is used by tech giant & startups to make their codebase easy, maintainable & structured. If you use this approach it wi
    8 min read
  • How to Run Node Server?
    A Node server runs JavaScript outside the browser to handle web requests. It listens for incoming requests, processes them, and sends responses. Unlike traditional servers, it handles multiple requests at once without waiting for each to finish. Some of the key features of the Node Server are: Non-B
    3 min read
  • AWS EC2 Instance Setup with Apache Server
    Amazon Web Services (AWS): Amazon Web Services (AWS) is a secure cloud services platform, offering compute power, database storage, content delivery and other functionality to help businesses scale and grow. Explore how millions of customers are currently leveraging AWS cloud products and solutions
    5 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
  • How to choose Web Hosting Server and Web Domain ?
    “Today it’s not about ‘get the traffic’ — it’s about ‘get the targeted and relevant traffic.’” – Adam Audette When we want to host business online then the things that come in mind are Which Domain name to buy? Which domain is good? What are its features? What is hosting? What is it’s use? And vario
    4 min read
  • Environment setup for JSP
    The environment setup for JSP mainly consists of 3 steps: Setting up the JDK. Setting up the webserver (Tomcat). Starting tomcat server. All the steps are discussed in details below: Setting up Java Development Kit : Step 1: This step involves downloading JDK from Download JDK. Step 2: Setting up th
    2 min read
  • 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 sim
    3 min read
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