Open In App

Json-server Setup And Introduction

Last Updated : 11 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

What is json-server?

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

Installation:

npm install json-server

Creating a database file: Create a .json file that stores the data of the mock database in JSON format. Let’s add some data to the file. Let’s name the file db.json.Id attribute must be used to get access to data individually and its value should be unique.

Note:

A valid object has the usual structure {key: data}. data can be a number, a string, a nested object, or an array. data can also be a variable or the result of a function call, in which case it will be evaluated before being converted into a string. Double quotes should be used for assigning string keys, value pairs, and the last key, the 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: The default port is 3000, and the server can be run using the command 3000

json-server db.json

Note: Here, 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 is 

json-server db.json --port PORT_NUMBER

Running a live serve: To get the server updated the manual change in the .json file using the command

json-server --watch db.json

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

Routes and Requests: json-server modules automatically generate routes for the higher order attributes in the JSON file, You can see in the json-server run image, that the route for students is generated as home_route/students which returns student’s data as a response.

Routes:

How to execute Routes?

To execute the route we can use a web browser or tools like postman and Thunderclient extension in vscode.

1. Route to display all students:

home_route(localhost:3000)/students

This route returns a JSON response of the student’s data:

localhost:3000/students

2. Route to display student by id:

home_route/students/id

json-server recognizes id as a primary key when added to database objects and it provides a route for that object array to retrieve documents based on id. Let’s say we want the student with an id 2, we will get that student data by requesting the route “home_route/students/2”

localhost:3000/students/2

Requests:

json-server supports

1. GET: An HTTP GET request is used to retrieve data from the server/database. It sends resource requests to the server which response to the request with appropriate data. GET request uses the URL(Uniform Resource Locator) to send the request to the server.

Example: URL http://localhost:3000/students is used to retrieve student data.

2. POST: An HTTP POST  request is used to send data to the server or database. It sends the data to the server within the request body. The server parses the data and adds the data to the database.

Example: URL http://localhost:3000/students is used to add student’s data to the server/database/ (Where data to be added is in the request body)

3. DELETE: An HTTP DELETE request is used to send delete requests to the server/database. It sends a delete request using a URL with appropriate details.

Example: URL is used to delete student’s data whose id is ‘1

4. PUT: An HTTP PUT request is used to send add/replace data requests to the server/database. It sends the data to be replaced/added to the request body.

This is the same as a post request technically but logically put request doesn’t create duplicates as a post request.

5. PATCH: An HTTP PATCH request is used to send update requests to the server/database. It sends the data to be updated in the request body.

Example: URL http://localhost:3000/students/1 is used to update student’s data whose id is ‘1’ (where data to be updated is in the request body )

Advanced features and queries:

1. Advanced queries for:

  • SORT: This query is used to fetch data from the server in sorted order. Example: URL http://localhost:3000/students?_sort=name&_order=asc is used to fetch data with names in ascending order.
  • FILTER: This query is used to fetch data from the server with a particular value. Example: URL http://localhost:3000/students?name=Alex is used to fetch data with the name “Alex“.
  • PAGINATE: This query is used to limit the number of rows to be returned. Example: URL http://localhost:3000/students?_limit=5 is used to fetch a maximum of 5 rows of data.

2. Custom routes:

json-server creates default routes for the data. but json-server also supports customized routes.

Customized routes are added to the server dynamically with the command json-server db.json –routes routes.json where routes.json is the file with customized routes.

3. Middlewares:

middlewares are the functions that have access to the request to the request object and the response object and also have the ability to call the next middleware. 

middlewares are added to the server dynamically with the command json-server db.json –middlewares ./mware.js where mware.js is the file with middlewares.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads