JS - Mocking a REST API with JSON Server
Tags: javascript, development, json, api
Published: 2021-07-17 16:19:31

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](https://www.agilealliance.org/glossary/mvp/) or a [proof of concept](https://searchcio.techtarget.com/definition/proof-of-concept-POC).

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](https://github.com/typicode/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](https://www.npmjs.com/) or [Yarn](https://yarnpkg.com/), install the package to your project using one of the following commands:

```shell
// If using NPM
npm install json-server --save-dev
```

```shell
// If using Yarn
yarn add json-server -D
```

Then, you need to follow these three steps:

1. [Configure an entry-point file](#configure-entry-point);
2. [Create a JSON file with mocked data](#creating-mocked-data);
3. [Add a new script to your `package.json` file](#creating-mock-api-script);

<a name="configure-entry-point"></a>
#### 1. Configuring an entry-point file
JSON Server will act like a simplified [Express](https://expressjs.com/) server, so, this is how you create the main file required by it to run:

```javascript
const path = require('path')
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router(path.join(__dirname, 'db.json'))
const middlewares = jsonServer.defaults()

server.use(
  jsonServer.rewriter({
    '/api/*': '/$1'
  })
)

server.use(middlewares)
server.use(jsonServer.bodyParser)

server.use(router)
server.listen(3000, () => {
  console.log('JSON Server is running')
})
```

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

<a name="creating-mocked-data"></a>
#### 2. Creating mocked data
JSON Server works based on [Low DB](https://github.com/typicode/lowdb) 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:

```json
{
  "users": [
    {
      "id": 1,
      "name": "Jon Doe",
      "age": 30,
      "active": true
    },
    {
      "id": 2,
      "name": "Jane Doe",
      "age": 25,
      "active": true
    },
    {
      "id": 3,
      "name": "Bob Taylor",
      "age": 45,
      "active": false
    }
  ],
  "products": [
    {
      "id": 1,
      "name": "Pizza",
      "price": 10,
      "active": true
    },
    {
      "id": 2,
      "name": "Hamburger",
      "price": 7,
      "active": true
    },
    {
      "id": 3,
      "name": "Ice Cream",
      "price": 2.5,
      "active": false
    }
  ]
}
```

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.

<a name="creating-mock-api-script"></a>
#### 3. Creating the mock API script:

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

```javascript
"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.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vmq3q1rleyot0r6r0qeb.png)

_I'm using the [JSON Viewer extension](https://chrome.google.com/webstore/detail/json-viewer/gbmdgpbipfallnflgajpaliibnhdgobh) 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.

```
// This will add a new product to the "products" array

URL: `/api/products`
BODY:
{
  "id": 4,
  "name": "Chocolate",
  "price": 6,
  "active": true
}
```

- `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.

```
// This will update the user with the id = 2

URL: `/api/users/2`
BODY:
{
 "id": 2,
 "active": false
}
```

`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.

```
This will remove the user with id = 3

DELETE: `/api/users/3`
```



#### 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](https://github.com/typicode/json-server) 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](https://github.com/vcpablo/js-json-server-mock-api).

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

_Cover image by [Marc-Olivier Jodoin](https://unsplash.com/@marcojodoin)_