Fake REST API for Local Testing using
JSON Server
https://howtodoinjava.com/angular/mock-rest-server/
Learn to JSON server library for creating a mock REST server in the local development
environment and simulating online REST APIs for unit testing purposes. Using the JSON
server, we can produce desired JSON responses in no time. It is very handy to have such
REST APIs mocking capability for quick development time.
1. Install JSON Server
As we are in a Nodejs and Angular development environment, let’s import json-server
dependency.
Install JSON server
npm install -g json-server
Console Output:
C:\Users\admin\AppData\Roaming\npm\json-server -> C:\Users\admin\
AppData\Roaming\npm\node_modules\json-server\bin\index.js
+ json-server@0.14.0
added 229 packages from 130 contributors in 24.844s
2. Create a JSON File to Serve API Responses
The best thing about this approach is that you are not forced to consume any dummy meaning
less data. Rather you can create JSON data you want to consume and put it in a
file 'db.json' and start serving it.
db.json
{
"employees": [
{ "id": 1, "name": "Lokesh", "status": "active" },
{ "id": 2, "name": "Andy", "status": "Inactive" },
{ "id": 3, "name": "Brian", "status": "active" },
{ "id": 4, "name": "Charles", "status": "Inactive" }
]
}
And start serving the above db.json file with a simple command. Navigate to the directory
where you placed the db.json and run the following command.
json-server --watch db.json
Now test the REST API in the browser using the command
'http://localhost:3000/employees'.
JSON server running
Please note that REST endpoints served from JSON server are determined by data nodes in
db.json. It’s so much easy and powerful.
Drop me your questions in the comments section.
Happy Learning !!