How to mock your entire backend server?

This is the last post in our series on mocking data for testing purposes. So far, we have seen how to generate mock data using Mockaroo and then how to incorporate such fake data in our Angular application.

Today, let’s push this one step further and use that same JSON data to mock our entire backend server, including CRUD (CReate Update Delete) operations, so you can also test data updates.

Enter JSON Server

JSON server is a small npm library that reads a JSON file and turns it automatically into a RESTful web server. Yes, you read that right: All we need as input is our JSON data in a file!

The format of that JSON is one single object where each property will be turned into a backend endpoint. So, for instance, say you need to support two types of data: users and teams.

Then your JSON database will look like this:

{
   "users": [ 
      // Array of all users data
   ],
   "teams": [ 
      // Array of all teams data
   ]
}Code language: JSON / JSON with Comments (json)

You would substitute those arrays with the mock data generated with Mockaroo, and then running JSON server would give you the following RESTful API:

  • HTTP GET /users => Returns the list of all users
  • HTTP GET /users/21 => Returns the user with id = 21
  • HTTP POST /user => Creates a new user
  • HTTP DELETE /user/21 => Deletes the user with id = 21
  • HTTP PUT /user/21 => Updates the user with id = 21

JSON server also supports pagination, full-text search, and custom routes if you want to add more endpoints to your test backend. Any changes you make to your data persist in your JSON file, too. This means you have a single file database for testing purposes, which is excellent!

If you want to try it, here is a complete tutorial on how to use JSON server with Angular apps. The getting started section of the npm package is also very well documented.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.