Angular – Fake REST APIs using Mock Server

Learn to create mock REST server locally which will simulate online REST APIs and produce desired JSON responses online. It is very handy to have such REST APIs mocking capability for quick development time.

Install JSON Server

As we are in node and angular development environment, let’s import json-server dependency.

$ 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

Create Mock JSON Response and Serve it Online

  1. 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.
    {
      "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" }
      ]
    }
    
  2. And start serving above db.json file with simple command.
    $ json-server --watch 'E:\ngexamples\db.json'
    
    \{^_^}/ hi!
    
    Loading E:\ngexamples\db.json
    Done
    
    Resources
    http://localhost:3000/employees
    
    Home
    http://localhost:3000
    
    Type s + enter at any time to create a snapshot of the database
    Watching...
    
  3. Now test the REST API in browser using command 'http://localhost:3000/employees'.
    JSON server running
    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 comments section.

Happy Learning !!

Ref: json server github page

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.