cft

JS - Mocking a REST API with JSON Server

In this article you will learn how to implement a mocked REST API using JSON Server that will help you speed up conceptual and proof-of-concept applications development.


user

Pablo Veiga

2 years ago | 4 min read

Depending on how your team works, you might need to move forward with the front end while the back end is still being structured.
Or perhaps you need speed to create an MVP or a proof of concept.

This means that you probably will receive interface designs from the designer or product manager and will need to implement them using mocked data, while the back end is still not ready.

When I first started developing web applications, I used to mock data within the components by replicating pieces of HTML or setting variables with mocked arrays or objects according to what the interface required.

The problem is when you do this, you increase the amount of work needed when the integration time comes because you will need to:

  • remove mocked data from components;
  • create the services which connect the front end to the back end;
  • consume these services to display real data;

It turns out that this path can be much less painful if you use mock API's.

TL;DR

In this article I show you how to easily mock a simple REST API using JSON Server

JSON Server is just one option amongst several others that allow you to fake REST APIs to deal with interface prototyping.

JSON Server - Mock REST API

Let's start with JSON Server. This package allows you to bootstrap a mocked REST API server without much effort.

Considering you have already created the main structure of your project using NPM or Yarn, install the package to your project using one of the following commands:

// If using NPM
npm install json-server --save-dev
// If using Yarn
yarn add json-server -D

Then, you need to follow these three steps:

  1. Configure an entry-point file;
  2. Create a JSON file with mocked data;
  3. Add a new script to your package.json file;

1. Configuring an entry-point file

JSON Server will act like a simplified Express server, so, this is how you create the main file required by it to run:

JSON Server entry point
JSON Server entry point

Notice that here, I intend to use the prefix /api for my requests. You may change it to whatever you like.

2. Creating mocked data

JSON Server works based on Low DB a "Tiny local JSON database for small projects". So you need to configure a db.json file that will serve the data.

Let's suppose I need to list users and products, for example. This is how our JSON file will be:

db.json file
db.json file

This is enough for the mock API to be started and for you to make requests right away.

But first, let's create a new script into the package.json file so that we don't need to install json-server globally in your machine.

3. Creating the mock API script:

Add the following property to the scripts section of the package.json file:

"mock:api": "node json-server/server"

And that's it. In this implementation, we configured JSON server to bootstrap the mock API using the port 3000 but you might change it in the server.js file.

This is an example of the results when requesting http://localhost:3000/api/users directly from the browser.

JSON server browser request output
JSON server browser request output

I'm using the JSON Viewer extension to display the data properly formatted and coloured as seen above.

4. JSON Server basic operations

JSON Server will let you implement front-end services that make real API calls and let them ready to wait for the real back-end API because it works exactly like a REST API.

This also means you can use the most common verbs to perform actions with your data:

  • GET: used to retrieve full arrays, objects by id or even filter by certain attributes:
GET: /users => retrieves all users
GET: /users/1 => retrieve the user with id = 1
GET: /users?_sort=age&_order=desc => retrieve users sorted by age descending
GET: /users?age_gte=10 => retrieve users whose ages are greater than 10
  • POST - used to create new values. Make a POST request using the URL of the resource you want to add and pass the value using the body.
Adding an entry to mocked database
Adding an entry to mocked database
  • PUT - used to update a resource. Make a PUT request passing the id of the resource you want to update as a query param and the value to be set using the body.
Updating an entry in mocked database
Updating an entry in mocked database
  • DELETE - used to remove a resource. Make a DELETE request passing the id of the resource you want to be deleted as a query param.
Removing an entry from the mocked database
Removing an entry from the mocked database

5. JSON Server advanced operations

As JSON server works just like Express JS, you can also extend it to perform more advanced operations, map different URL's to specific data in the db.json file or even implement middlewares and _ parsers_.

I'm not going to dive deep into all of the possibilities because they are endless. It's worth taking a look at the full documentation in their Github to take advantage of its full power.

Conclusions

You don't need to install and configure databases and back-end API anymore when starting a new front-end project. Sometimes all you need is some sample data to simulate real scenarios.

In this article you were introduced to JSON Server, an extraordinary tool that can help you bootstrap a simple (or not so simple) REST API very quickly that will provide support for your next front-end prototyped application.

You can find a fully-working example in this repository.

I hope you liked it.
Please, share and comment!

Cover image by Marc-Olivier Jodoin

Upvote


user
Created by

Pablo Veiga

JavaScript expert | Agile developer | Amateur writer | Beer lover


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles