How to mock your API’s easily with Json-Server

Share this post

Introduction

Front-end developers often need to interact with one or more API’s to retrieve and display data in an application. However, during the development phase, the API may not be available just yet, or not fully developed. In such cases, mocking an API server response is a valuable technique for the developers, to make progress in their tasks, without being blocked until the API is fully ready and available for usage.

This can help streamline the development process and ensure that the application works as expected when the actual API is available for integration.

One of the ways to achieve this is by using Json-Server – a popular tool for creating a mock API server with minimal setup and configuration.

Let’s dive in together and see how you can have Json-Server as a mock backend setup easily in just a few steps!

Getting Started

What is Json-Server?

JSON Server is a lightweight and user-friendly open-source tool designed to enable developers to rapidly create a RESTful API by using a JSON file as the data source. It effectively emulates a fully-featured API server, offering endpoints for CRUD (Create, Read, Update, Delete) operations on JSON data. JSON Server shines in its ability to define data structures, establish relationships, and configure API routes through a straightforward configuration file. This makes it an invaluable resource for swiftly simulating API behavior and server responses during development.

Setting up Json-Server

Installing JSON Server

First, make sure you have JSON Server installed globally. Use the following command to install it:

npm install -g json-server

This command installs JSON Server as a global package, allowing you to use it from the command line.

Creating the Mock Database

To create a mock database, you need a db.json file that serves as your data source. Place this file in the project’s root folder. You can populate it with mock data that you’ll later use for simulating API responses.

There are some good resources available on the web to help you generate some mock data, one of my favorite ones is Mockaroo.

Running Json-Server

To start the server, use the following command:

json-server --watch db.json

Accessing Mock data

Without writing any code, you can immediately access the mock data from your browser by using REST-like paths:

  1. To view the list of all clients, simply navigate to http://localhost:3000/clients.
  2. To retrieve data for a single client by ID, use the following format: http://localhost:3000/clients/ID. For instance, to access data for a client with ID 2, use http://localhost:3000/clients/2.

JSON Server offers a range of built-in features for filtering, sorting, paging, slicing, and more. I highly recommend exploring these capabilities in detail by visiting the official documentation at https://github.com/typicode/json-server#getting-started.

Custom Routing

While Json-Server simplifies the process of mocking RESTful APIs for your front-end development needs, it also offers the flexibility to define custom routes to handle specific use cases you may have.

Scenario: Categorizing Clients

Suppose our database contains information about clients, where each client can be associated with a subscription plan: Free, Premium, and Ultimate.

Step 1 : Edit DB.Json file

let’s modify our DB.Json to include a “table” for plans :

{
  "clients": [
    {
      "id": 1,
      "name": "Perkin",
      "email": "pkedward0@histats.com",
      "phone": "555-281-5058",
      "address": "0118 Hayes Alley",
      "city": "Cotovia",
      "plan": "0"
    },
    {
      "id": 2,
      "name": "Gideon",
      "email": "gpratten1@sciencedaily.com",
      "phone": "118-814-0662",
      "address": "7086 Iowa Way",
      "city": "Haifa",
      "plan": "20"
    },
    {
      "id": 3,
      "name": "Suellen",
      "email": "sarangy2@newyorker.com",
      "phone": "739-684-5687",
      "address": "1463 Waubesa Crossing",
      "city": "Hirara",
      "plan": "0"
    },
    {
      "id": 4,
      "name": "Frasier",
      "email": "fpietesch3@chicagotribune.com",
      "phone": "132-355-9644",
      "address": "3 Thompson Circle",
      "city": "Meixian",
      "plan": "0"
    },
    {
      "id": 6,
      "name": "Trey",
      "email": "tgordongiles5@ebay.co.uk",
      "phone": "641-480-7626",
      "address": "50186 Clyde Gallagher Place",
      "city": "Dengjia",
      "plan": "10"
    },
    {
      "id": 7,
      "name": "Standford",
      "email": "sgarbutt6@gnu.org",
      "phone": "303-672-8056",
      "address": "63 Hazelcrest Pass",
      "city": "Gorki Vtoryye",
      "plan": "10"
    },
    {
      "id": 8,
      "name": "Edan",
      "email": "elapley7@imdb.com",
      "phone": "546-708-7544",
      "address": "30977 Elgar Drive",
      "city": "Chilmāri",
      "plan": "10"
    },
    {
      "id": 9,
      "name": "Ashley",
      "email": "asparkwill8@comsenz.com",
      "phone": "836-364-4471",
      "address": "886 Lien Crossing",
      "city": "Ciawi",
      "plan": "0"
    },
    {
      "id": 10,
      "name": "Darell",
      "email": "dweyland9@mediafire.com",
      "phone": "857-548-8462",
      "address": "6645 Lien Terrace",
      "city": "Loma Alta",
      "plan": "0"
    }
  ],
  "plans": [
    {
      "id": 1,
      "name": "Free",
      "price": 0
    },
    {
      "id": 2,
      "name": "Premium",
      "price": 10
    },
    {
      "id": 3,
      "name": "Utimate",
      "price": 20
    }
  ]
}

Step 2: Creating the custom routing definition

To define custom routes in JSON Server, you’ll need to create a routes.json file in the same directory as your db.json. This file allows you to specify routing definitions tailored to your API needs. For instance:

{
  "/clients/plans/:planId": "/clients?plan=:planId"
}

In this example, requests to /clients/plans/:planId will be routed to the JSON Server endpoint /clients?plan=:planId, enabling you to customize routing for specific endpoints.

Once you’ve set up your routes.json file, you can configure JSON Server to use these custom routes. Make sure to stop the server if it’s already running, and then start it with the following command:

json-server --watch db.json --routes routes.json

This command instructs JSON Server to watch the db.json file for data and apply the custom routing configurations defined in routes.json.

Conclusion

In frontend development, JSON Server stands as a practical solution for creating mock APIs. It facilitates the development process by enabling developers to continue their work, even when real APIs are unavailable or incomplete. The simplicity and versatility of JSON Server make it a valuable asset in a developer’s toolkit, ensuring smoother and more efficient web application development.

So, why not give it a try in your next project? JSON Server’s ease of use, coupled with its powerful features, can significantly enhance your frontend development workflow. Start by setting up your own mock backend, experiment with different configurations, and experience the benefits firsthand. It’s a valuable tool that can save you time and accelerate your development process.

Cover photo by Google DeepMind