This site uses cookies to offer you a better browsing experience. Find out more on Privacy Policy.

Fake JSON service: json-server

September 20, 2016, Piotr Chodziński

I wanted to present my own quick introduction to Linux process manager, but I realized that I need something that could be managed.

Good example of such process is JSON Server, a tool that will be used to create fake strings repository. I had no access to the production version of a server that delivers translations, but I had a sample request and response, so I could build something that simulates a real service.

So, let’s focus on json-server now.

As it’s home page describes:

“Get a full fake REST API with zero coding in less than 30 seconds (seriously)”

We will build a simple REST API that will mock service that returns proper strings in various languages. It should handle following cases:

  • Return all translations in all languages
  • Return filtered results with following filters
    • Key (placeholder)
    • Language using ISO codes
    • Context

Original service uses GET method to pass the parameters, we will do it in the same way then.

Let’s get required tools, like NPM and NodeJS:

  1. Install NPM first
    $ sudo apt install npm
  2. Install Node.js
    $ sudo apt install node nodejs-legacy
  3. Install json-server finally (may require sudo as well)
    $ npm install -g json-server
  4. If you experience an error indicating lack of permissions you can fix it in the following way:
    $ sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

    Or install it not globally without -g option, like this:
    $ npm install json-server

Done. But to run the server we also need a database with data expected from a real web service.

Let’s create one and call the file db.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
  "translations": [
    {
      "id": 1,
      "key": "NEW",
      "language": "en_GB",
      "value": "NEW",
      "context": "myapp"
    },
    {
      "id": 2,
      "key": "STORE",
      "language": "en_GB",
      "value": "STORE",
      "context": "myapp"
    },
    {
      "id": 3,
      "key": "STORES",
      "language": "pl_PL",
      "value": "STORES",
      "context": "myapp"
    }
  ]
}

We can now test whether our data are handled correctly:
$ json-server –watch db.json

And what do we see?
1
All right, we have a server up and running which will serve our simple db.json database.
Now we can try accessing the server using Postman or any other REST-oriented tool, but for me a web browser is good enough.

If you installed json-server on your machine you can use http://localhost:3000 address, if on any other machine (Vagrant for instance) please use the machine IP address.

In my case it’s Vagrant working on 10.0.0.200 IP address.
2

But what about our database? Just add translations suffix or click on the translations link visible on this screen: http://10.0.0.200:3000/translations

3
It’s our data! We can even use filters!

4
OK, it works and we can filters results. But our goal is to get the same results format as we expects from original web service:

Current

Expected

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[
  {
    "id": 1,
    "key": "NEW",
    "language": "en_GB",
    "value": "NEW",
    "context": "myapp"
  },
  {
    "id": 2,
    "key": "STORE",
    "language": "en_GB",
    "value": "STORE",
    "context": "myapp"
  },
  {
    "id": 3,
    "key": "STORES",
    "language": "pl_PL",
    "value": "STORES",
    "context": "myapp"
  }
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
  "response": {
    "content": {
      "translations": [
        {
          "translation": {
            "key": "NEW",
            "language": "en_GB",
            "#value": "NEW"
          }
        },
        {
          "translation": {
            "key": "STORE",
            "language": "en_GB",
            "#value": "STORE"
          }
        },
        {
          "translation": {
            "key": "STORES",
            "language": "pl_PL",
            "#value": "STORES"
          }
        }
      ]
    }
  }
}

To do this we have to create small script – server.js – to tell the server what to do with our data:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
var jsonServer = require('json-server')
var server = jsonServer.create()
var router = jsonServer.router('db.json')
var middlewares = jsonServer.defaults()
 
server.use(middlewares)
server.use(router)
server.listen(3000, function () {
    console.log('JSON Server is running')
})
 
router.render = function (req, res) {
 
    var intArr = [];
 
    if (res.locals.data.length > 0) {
        res.locals.data.forEach(function (e, i, a) {
            intArr.push({
                "translation": {
                    "key": e.key,
                    "language": e.language,
                    "#value": e.value
                }
            });
        })
    }
 
    res.jsonp({
        response: {
            content: {
                translations: intArr
            }
        }
    })
}

Now we are ready to serve properly formatted response but we have to start our json-server in a bit different way than before:

$ node server.js
5
If you experience an issue like this:
json dsa

then the easiest workaround is to install json-server locally (if you installed it globally in one of previous steps):

$ npm install json-server

Then try to run it again:

$ node server.js

Let’s look at what we can see in the browser now:
6 (1)
And the same as before, we can use filtering.

All the details about json-server you can find on their github.

But what if we need to keep it running permanently? I will show it in the next chapter soon.

Last posts