Json-Server Setup And Introduction
Last Updated : 15 Oct, 2024
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');
});
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