Open In App

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

Similar Reads