Codementor Events

Quick way to create a mock API server for your app development

Published Dec 19, 2018

Why do I need a mock API server

Recently I've been making React video tutorials. In order to demonstrate how a React app interacts with a back-end API server, I want to create something quickly and forget about it later. The goal is to set up a RESTful API server that we can do some basic CRUD operations.

There are many ways to achieve the goal but I chose json-server for its simplicity.

The library provides a CLI tool so that you can run it as a command from your Terminal.

Requirements

  • Node v6+

Install

npm install -g json-server

Run

Make sure you have a db.json file that stores your data, for example:

{
    "products": [],
    "categories": [
    	{ "id": 1, "name": "Toys" } 
    ]
}

It's a big json file that contain one object whose keys are collection's names, and the values are the arrays that contain documents of the collections. If you used to work with MongoDB before, you are probably familiar with the terms. Please note that each document should contain an unique id.

Run json-server command like below

json-server ./db.json

After running the command, it will show you how the resource URLs. Try to open them on the browser and see the result.

You can change the default port (3000) to other port if you want by providing a port parameter. See video below:

asciicast

Now your API server is up and running. Please read more on the github repo to see options you can tweak. Happy hacking!

Discover and read more posts from Thinh Pham
get started