Create A REST API With JSON Server in minutes
🤔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
Subscribe to my newsletter
Read articles from mahi samia directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
mahi samia
mahi samia
hey there 👋 i'm Samia, a Backend developer turning to frontend world. i used to work as a Laravel and PHP developer for 3 and half years, in that journey, i had to deal from time to time with some frontend tasks, like fixing responsiveness or converting some psd files into HTML & CSS, that was when i fall in love with it. I loved the idea of turning creative and beautiful design into reality, so i made that career switch and now turning fully to Frontend development. Feel free to checkout my journey on Instagram or just pass Hi