json-server : Mock DB + API Server for testing and development
As a Front-End Developer you may got resentful or sometimes angry 😡about api issues in your project related to many reasons like :
- New API is not ready for use
- API is not tested and the BackEnd Dev wait for feedback to fix the api issue
- Api server is not available
So those are just some of many reasons that can push you to think about a solution instead of waiting for production api to be ready.
One of the simplest solution is json-server, this one provide a simple way to configure a MockDB managed by apis with less code. This mock server can be used rather for development purposes or end to end testing purposes.
To initialize a new project with Mock DB + API Server follow these steps :
1 – Initialize node project
2 – Install required package
- json-server : Gives us a full fake REST API
- npm-run-all : To run multiple npm-scripts in parallel or sequential
3 – Create database init file
Let’s imagine a data structure of Products And Categories, a product is attached to a category and many products can be attached to same category :
The following file contains init data for your api server, this data will be used to initialize db content each time we run the server
4 – Add code for mock db file initialization
5 – Create a simple configuration file for api server with following content
6 – Finally add api server configuration
7 – To run the server you have to add the following configuration on your package.json file
8 – Run API Mock Server
Use http://localhost:3030, Example :
- GET http://localhost:3030/products : To display product list
- GET http://localhost:3030/categories : To display category list
- DELETE http://localhost:3030/products/1 : To display product of Id = 1
Find the source code of this example in GitHub.
Java/JavaEE (Hybris/Spring) & Full Stack Senior Developer
I’m passionate about new technologies or any kind of thing that change our lifestyle to better either by automatisation of existing process or creating new solution.