Creating a fake REST API with json-server
A couple of months ago I watched a great Pluralsight course about setting up a JavaScript development environment; it introduced me to the idea of using a fake REST API during development.
The main benefit of using a fake REST API is that it allows you to concentrate on building your app without the need to develop a fully fledged API at the same time to support it. This would be increasingly beneficial where separate teams are building the app and APIs, as this can prevent any potential blockers caused by the back-end not being ready in time for the front-end. Personally in my current side project, I am using a fake REST API in order that I can concentrate on what I wanted to learn which is building React apps.
I am going to share with you how I created my fake REST API using two modules:
- json-server which allows you to create a REST API supporting all the HTTP verbs by defining a JSON file containing the data you want to make available. Then as you use the API, any changes you make are automatically saved to this file.
- json-schema-faker is a fake data generator that uses schemas you define using JSON Schema.
Now why use these two modules together? Well by using json-schema-faker you can generate random sets of data and save that to a JSON file. Now if we use that JSON file as input to json-server, you now have an API that changes every time you start the server and helps you discover and develop your app to cover a wide range of scenarios e.g. no results, large list of results, short/long strings, high/low positive/negative numbers and anything else you could probably think of.
Lets look at an example (the complete example can be found on my GitHub). Imagine we have an API for a Password Manager type app where you have Sites with information such as URL, Username and Password and Sites can be contained in Groups. First step is to define the JSON Schemas for Site and Group which looks as follows:
A useful tool to help define your schemas is the editor on the json-schema-faker site. Now that we have these schemas defined we can use them with json-schema-faker to generate a JSON file.
That’s all the code written, now we just need some npm scripts to call this build script and start json-server.
"generate-mock-api-data": "ts-node buildScripts/generateData.ts", "prestart": "npm run generate-mock-api-data",
"start": "json-server --watch buildScripts/db.json --port 3000"
Just simply run the start script and now you have a REST API.
All the code featured is from the complete example on GitHub.