NOTE
Don’t create mock data files under /src/assets/ or /src/app/ folder.
Angular used to watch all the files residing in the above path. Placing json file outside the folder would prevent Angular from keeping a consideration on data files. It is a known behavior of Angular to reload the application if it finds a change in the files that are being watched. On trying any CRUD operation on JSON file, in our case it is db.json, the file tends to change, which in turn makes the Angular application compile and reload.
Note down the location of db.json in the above screenshot.
Step 4 - Running the server
It can be done in two ways.
Direct Command execution
Start JSON server by executing the following command
json-server –watch db.json
Adding json file manually in package.json
In package.json, add the below code to run json-server with short code.
"json:server": "json-server --watch db.json",
Refer line#8
Now, run the server
npm run json:server
Step 5
Your JSON Server will be running on port 3000. The below data will be shown in the terminal
Resources
http://localhost:3000/posts
Home
http://localhost:3000
Now hit the URL http://localhost:3000/posts in the browser and you will get the following result.
Now you can click on the posts link in the page, which will show the JSON data given in db.json file now that we have our server and API running.
Test it with a tool like POSTMAN. Initiate a HTTP GET request to http://localhost:3000/posts shows the following result,
Conclusion
Now, we’ve learned to create a mock REST API using json-server. It included the routing of api calls from Angular application to json-server and the process involves execution of both the servers together concurrently.
CRUD operations are possible by default on any api using json-server and the data can be accessed using different RESTful routes based on the operation.