IPC Blog

Node.js module: JSON Server

Mock server for development

Jul 12, 2018

Most cases of web frontend development, require a functioning backend. Yet quite often the frontend and backend are developed separately. This means, that the functionality of the frontend can only be tested, if there’s a backend providing it with a counterpoint station. And to decrease this backend dependency you can actually use a Mock server instead.

The Mock server systems take on the role of the backend and provide the respective interfaces, but they don’t implement business logic. There’s a Node.js module called JSON Server, which you can use instead of implementing this kind of support system all by yourself. And just like its namesake it gets everything it needs from a JSON file. However, JSON Server can do much more than just providing a pure, read-only interface: You can also access the server through the HTTP methods POSTPUTPATCH and DELETE, while writing.

 

Installation

JSON Server is managed as an open source project under the MIT license on GitHub. It is available as an npm package under the name of json-server. With the control command npm install –D json-server, you install the package as a DevDependency in your project. Since the 5.2 version of npm you can also use the control command npx to run JSON Server directly in your project, without having to globally install the package on your system. Before you can start the server, you must create a database file beforehand. Here is an example for such a file:

{
  "todo": [{
    "id": 1,"title": "get up"
  },{
    "id": 2, "title": "eat"
  }]
}

Save this file under the name of db.json and now you can start with the command npx json-server db.json.
The server is committed to Port 3000 by default, so that you can talk to it under the URL http:// localhost:3000. For every single porperty of the top level of the database file, a route is generated. This means for this example that you can call the list of Todos with http://localhost:3000/todo. Should this port be occupied on your system already, you can use the option –port to choose another port.

 

Read access

JSON Server provides you with an interface like those of many other REST APIs. With a common path, in this case /todo, you are getting all the related data records. If you are just interested in one specific object, then you can identify it with the ID-property and specify its value in the path. The entry with the ID 4 you can get over the URL http://localhost:3000/todo/4. Additionally to the access of individual data records, you can also filter the list of all data records with specific criteria. In this case the query string is used in the URL. To request the secondary entry of the list with the title eat, use the following URL: http://localhost:3000/todo?title=eat.

To influence the responses from JSON Server, pass the commands in the query string to the request. These usually begin with an underscore and differ this way from the filtering. Two of these useful features, which JSON Server provides in the context of read operations, are sorting and paginating. To sort the list of objects, which come from the server, you enter the key _sort into the query string, with the name of the property by which you want to sort. Multiple properties are separated with a comma.

With the key _order you can also sort ascending (asc), the default, or descending (desc). Some control commands are available to you to influence the pagination, like _start_end, and _limit, and _start marks the last element of the page while _end is marking the last one. A limited amount of elements will be returned with _limit, if you don’t enter one of them. If you don’t state anything further, the limit lies at ten records.

Learn more about
International PHP Conference 2019

Write access

Just like it was mentioned beforehand, JSON Server does not only support read operations, but also write operations. These are implemented by lowdb. It is a lightweight database, build upon a Lodash library and uses a JSON file as a storage medium. You can use Postman to test the interface of JSON Server. This tool allows you to send  HTTP requests. To create a new record you set a POST request to the URL http://localhost:3000/todo with a Content-Type-header with the value application/json.

The body of the request contains the newly to be created object. The ID property is automatically set by the server with the next free value, so that you do not have to take care of it. To change the data record with the ID5, send a PUT request to the URL http://localhost:3000/todo/5. In this case also note, to set the Content Type correctly and format the Request Body correctly. If you send a DELETE request to this address instead of a PUT, the corresponding data record is then deleted.

 

Utilization with Express

JSON Server is already a very helpful tool by itself, but in combination with the web application framework Express you can go even further with the possibilities.

Express is based upon the Middleware concept. Those are, simply put, features which are standing between the incoming request and the outgoing response. JSON Server can also be used as such Middleware. Listing 1 contains the source code for the integration.

const express = require('express');
const jsonServer = require('json-server');
 
const app = express();
 
app.use('/api', jsonServer.router('db.json'));
 
app.listen(8080);

You can reach JSON Server in your application via the path /api. With the accesses to the databases and possibilities of sorting and filtering, this variant doesn’t differ from standalone operation. But in combination with Express you can, for example, implement authentication or an extended logging or you can use the Node.js debugger to analyze incoming requests for the runtime.

 

Authentication

As an example for the utilization of Express I would like to show you the use of JSON Web tokens, for securing such an interface. One of the first questions, which comes to mind, is why a Mock server should be protected. The answer to this is quite simple: The Mock server should behave like the actual backend and in any case, some form of authentication will come into play. For the realization you first install the jsonwebtoken package, which allows you to create tokens for registered users and the package express-jwt, to check the tokens. Listing 2 contains the source code responsible that is responsible for the authentication.

const express = require('express');
const jsonServer = require('json-server');
const jwt = require('express-jwt');
const jsonwebtoken = require('jsonwebtoken');
 
const secret = 'topSecret';
 
const app = express();
 
app.post('/login', (req, res) => {
  // check credentials, fetch userdata
  // ...
  const token = jsonwebtoken.sign(userdata, secret);
  res.json({ token });
});
 
app.use('/api', jwt({ secret }), jsonServer.router('db.json'));
 
app.listen(8080);

Send a POST request to the path /login, this feature must be concerned with checking the user name and password. Afterwards the token gets created with the user data and another character string and is then returned to the place that requested it. You must send this token in the authorization header for all the requests to the with Express encapsulated JSON server, otherwise you receive a 401 unautherized error message as a reply from the server.

 

Conclusion

JSON Server provides an excellent service, especially during lightweighted tests and development. Its most important features are the very low set-up effort and the high flexibility, which can be further increased by integration into an express server.

Stay tuned!

Register for our newsletter

Behind the Tracks of IPC

PHP Core
Best practices & applications

General Web Development
Broader web development topics

Test & Performance
Software testing and performance improvements

Agile & People
Getting agile right is so important

Software Architecture
All about PHP frameworks, concepts &
environments

DevOps & Deployment
Learn about DevOps and transform your development pipeline

Content Management Systems
Sessions on content management systems

#slideless (pure coding)
See how technology really works

Web Security
All about
web security