How to create a REST API using json-server npm package ?
Last Updated :
06 Aug, 2024
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.
Installation: Execute the below command in your project directory.
npm install json-server
Creating a database file: The data is stored in JSON format. Create a .json file that stores the data in JSON format. This JSON file works as a database. for example, we name the database file db.json. json-server recognizes the id attribute specially and treats it with unique constrain. This attribute is useful in getting data accessed individually by id.
Note: double quotes must be used for string value-pairs, and value pairsThe last key-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: json-server uses port 3000 as default and the server can be run using the command 3000
json-server db.json
Note: 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 number is
json-server db.json --port PORT_NUMBER
Running a live serve: To get the server updated/re-run on manual changes in the .json file use the command
json-server --watch db.json
On running, the json-server module generates a home route for the data server which can be accessed through the URL "http://localhost:3000" (if the port is 3000)
Reading data from the database:
We use the GET method to request data from the server. Higher order attribute in our json includes student object which contains records of the student. As json-server automatically generates routes for higher order attributes.
Example:
1. Retrieving all students
The URL to request Student data from the database is http://localhost:3000/students (the server is running at port 3000).
Below GIF shows get to request which is done in thunder client (An extension in vs code). Tools like postman and web browsers can also be used.
2. Retrieving student by id
Note: id in json-server data is treated as a special attribute. The server allows data only with the unique id.
The URL to retrieve students by their id is http://localhost:3000/students/1 This URL retrieves the student data whose id is "1". This URL pattern doesn't work for other attributes like name, grade, etc.(http://localhost:3000/students/name doesn't work). The below GIF shows the working of this request.
Adding data to the database:
We use the post method to send data requests to the server. HTTP post method sends a request to the server with data in the request body.
Example: URL to add data to the database is http://localhost:3000/students with post method. let's data to be added is
{
"id": 4,
"name": "binny",
"grade": 12,
"marks": {
"maths": 90,
"physics": 100,
"chemistry": 20
}
}
The below GIF shows the execution of the post method and updated data in the database:
Updating data in the database:
We use the HTTP PATCH method to update data in the database. This method sends a request to the server to update the data where the data to be updated is in the request body.
Example: The URL to update data in the database is http://localhost:3000/students/4 with the patch method. This method updates the data of the student with id "4" with data in the request body. Let's data to be updated is
{
"name": "bunny"
}
The name of the student will be changed to bunny on successful request. The below GIF shows the working of the patch method.
Deleting data in the database:
We use the HTTP DELETE method to delete data in the database. This method sends a request to the server to delete the data. The data to be deleted is specified in the request URL.
Example: The URL to delete the student with a particular id is http://localhost:3000/students/4 with the delete method. This method deletes the data of the student with id "4".The below GIF shows the working of delete method.
Similar Reads
How to Create A REST API With JSON Server ?
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 Re
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 resolve error "npm WARN package.json: No repository field" ?
The warning "npm WARN package.json: No repository field" indicates that the package.json file in your project lacks a "repository" field. The "repository" field is crucial for providing information about the version-controlled source code repository of your project. While not mandatory, including th
3 min read
How to Generate or Send JSON Data at the Server Side using Node.js ?
In modern web development, JSON (JavaScript Object Notation) is the most commonly used format for data exchange between a server and a client. Node.js, with its powerful runtime and extensive ecosystem, provides robust tools for generating and sending JSON data on the server side. This guide will wa
3 min read
How To Make A GET Request using Postman and Express JS
Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. In this tutorial, we will see how To Make A GET Request using Postman and Express JS PrerequisitesNode JSExpress JSPostmanTable of Content What is GET Request?Steps to make a GET Request
3 min read
How to add a non-npm dependency to package.json?
One of the great features of the npm ecosystem is the ability to install and manage packages from the npm registry. These dependencies are listed in the "dependencies" section of the project's package.json file. Â However, sometimes you may need to use a dependency that isn't available through npm, s
5 min read
Create and use mock servers for API testing or development in Postman
Postman, a comprehensive API platform, includes a robust API client for exploring, testing and defining requests. Its notable feature is the ability to create mock servers, simulating API responses for testing and development purposes. Developers can organize requests in collections, generate mock s
4 min read
How Proxy Backend Server using React.js ?
When building a web application with React.js, you may need to request a backend server. However, if the backend server does not allow Cross-Origin Resource Sharing (CORS), you may encounter an error when requesting from the frontend application. In this case, you can use the proxy server to forward
3 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