🤔Why do we need a JSON Server?
A common task for front-end developers is to simulate a backend Rest service, that delivers JSON data to the frontend,
JSON-SERVER is a Node Module for front-end developers who need a quick back-end for prototyping and mocking
🤷🏽♀️How to use it?
1- Installation
Install the package with npm, the following command will install json-server globally on your system using -g flag, if you want to install it locally just remove that flag.
npm install -g json-server
2- Creating the JSON data
Create a JSON file to store the data that should be exposed by the REST API, in this example, we called the file "db.json".
fill it with some data as shown below.
{
products:[
{
id:1,
category:"shoes",
name:"moccasins",
price:39.95,
},
{
id:2,
category:"shoes",
name:"Claquettes",
price:10.5,
},
{
id:3,
category:"shoes",
name:"High boots",
price:50.95,
}
]
}
products represent an endpoint of the API, which returns JSON data containing 3 shoes.
3- Start the server
open your terminal and type the following command :
json-server --watch db.json
If you're running another app on port 3000, you need to use a different one for json-server, since it also uses port 3000 by default, to do that simply add your desired one with this command: json-server --watch db.json --port 3001
4- Testing your API
Now all that's left is to test your API, If you go to "http://localhost:3000/products/1", you'll get the product with id = 1, as following:
{
"id": 1,
"category": "shoes",
"name": "moccasins",
"price": 39.95
}
note that the following endpoints will be automatically generated by the JSON Server:
GET /products - This retrieves a list of all resource entities of products.
GET /products/:id - This retrieves a specific product by its id.
POST /products- This creates a new product.
PUT /products/:id - This updates a product based on a specified id.
DELETE /products/:id - This deletes a product based on the specified id.
Reference
- json-server Github repository