Getting Started with JSON Server
If you have been working as a front-end developer on a team project, you have most likely encountered a scenario where the client-side app was ready, but the server-side or APIs were still underway. Another possible situation is one where even while building the client side, there exists some server-dependent function you would like to test out, but the server side is still not ready. In any scenario where you need a server quickly, a “magical” tool can help you spin up a mock server locally in seconds. This article will look at
JSON Server
and how it makes the work of a front-end developer a little easier and much faster.
In computer networking, a client and a server are separate computer systems that communicate with each other over a network. Here, the server is the system that provides resources or services to other computer systems in the network, which are called the clients.
When creating fully functional web applications, we often have two distinct parts: a front-end or client-side (part of the application with the UI) and a backend or server-side.
The backend is part of the application responsible for handling the business logic and management of resources in web applications. It dictates the operations that can be performed on the application’s resources (or database) and provides front-end developers with ways to carry out these operations, usually as API endpoints.
Now that we have a basic understanding of the server side and what it does, let us look at how JSON Server
fits into this story.
At the end of this article, you will:
- know what JSON Server is and why you need it.
- know how to build a mock server quickly using JSON Server.
- Know how to populate your mock database using faker.js
What is JSON Server?
JSON Server
is a simple, lightweight, and easy-to-use fake REST API server. The keywords here are “fake,” API, and “REST”; let us quickly look at these terms.
-
“Fake” in this context means that
JSON Server
is not a standard or production-grade server; instead, it is a mock server that can stand in place of an actual server for use only in development. -
An API is an interface created on the server that allows the client to communicate with and manipulate the resources on the server in a predictable way that has already been pre-defined by the server.
-
The type of APIs provided to us by
JSON Server
is of a pattern called “REST” (or RESTful APIs), which happens to be the most common convention used in writing APIs today.
JSON Server
provides us with this RESTFUL mock server with zero coding and a simple setup, making it the perfect tool for a front-end developer to test quickly out the functionalities of their client-facing application. It is typically used for testing front-end code in applications using frameworks such as Angular, React, or Vue that interact with a REST API.
Setup of JSON Server
Setting up JSON Server
is pretty straightforward. However, before we start, we must ensure that we have Node.js
and NPM installed on our system. Then we can proceed to follow the steps below:
1. Install JSON Server
To install JSON Server
from NPM, open up a terminal, move to the root directory of your project, and run the command below:
npm install -g json-server
This command will install JSON Server
globally on your computer so you can easily access it across multiple projects where you might need a mock server.
However, if for any reason you prefer not to install it globally, you can still run the command without the global flag, as shown below;
npm i json-server
This command will make the JSON Server
package scoped locally for just one project.
2. Create a JSON database file
After installing the JSON Server
package, the next step is to create a JSON file that will serve as your local database. To do this, create a new file on your text editor ending in the extension .json
. Also, to keep your project neatly separated from the JSON Server
files, I recommend putting every file concerning JSON Server
in a single folder. Let’s name this folder Data
.
3. Add data in JSON format
Add some data you wish to use to test your front-end’s functionality in JSON format in your JSON database file. Visit https://dgold3680.hashnode.dev/how-to-write-json-quick-dive to quickly learn how to write JSON if you do not already know how. Sample data:
{
"profiles": [
{
"id": 1,
"name": "Bruce Wayne",
"position": "Owner",
"contract": false,
"job description": "Individual or group with full ownership and responsibility for a business."
},
{
"id": 2,
"name": "Oliver Queen",
"position": "Manager",
"contract": false,
"job description": "Oversees operations and employees to achieve business goals."},
{
"id": 3,
"name": "Wally West",
"position": "Chief Distributor",
"contract": true,
"job description": "Leads distribution of products or services to customers."
},
{
"id": 4,
"name": "Clark Kent",
"position": "Chief Auditor",
"contract": true,
"job description": "Manages internal audit functions, assesses financial risk, and provides recommendations for improving organization performance and compliance."
},
{
"id": 5,
"name": "Diana Prince",
"position": "Head of Human Resources",
"contract": false,
"job description": "Manages personnel, recruitment, and employee relations."
}
],
"branches": [
{
"id": "abc1",
"state": "Metropolis",
"Address": "33 kent Street"
},
{
"id": "efg2",
"state": "Gotham",
"Address": "439 Wayne Estate"
},
{
"id": "ijk3",
"state": "Anthens",
"Address": "12 Princess Creak Street"
}
]
}
The JSON database will act like a NoSQL database, with each top-level key (profiles & branches - from our sample data) representing a NoSQL collection and its corresponding value representing a NoSQL document within the collection.
Each top-level key would represent a unique resource endpoint that can be accessed and manipulated individually. Usually, I refer to these top-level keys as resource keys
. The value of these resource keys, which are the resources themselves, will usually be an array of objects, each representing an entry into the database and having a unique id. This id is necessary and very important as it would allow you to identify the object as unique when querying the database, as we shall see in later sections.
4. Start up the server
With your installation done and your data entered, you are finally ready to use the JSON Server
package in one last step. Start up your mock server with the prompt
json-server --watch Data/Db1.json
Here Data
is the name for the folder, which I initially recommended should contain all our JSON Server
related files, and Db1.json
is our database file name.
File Structure
Once you have spun up the mock server, JSON Server
will provide you with a home endpoint where your resources are being hosted on your browser and endpoints to each different resource within your database.
JSON Server
Started
JSON Server Routes
JSON Server
provides us with a fake REST API, and this comes with a built-in set of REST endpoints that allow us to interact with our JSON database. Each endpoint will allow us to manage and manipulate the data in our database differently.
Let us have a look at them:
CRUD Operations
CRUD operations are the bread and butter of the backend. CRUD is an abbreviation representing the four most basic operations carried out on data: create
, read
, update
, and delete
. Since we are using a REST API, it is standard practice for all CRUD endpoints to look similar but differ in action based on the HTTP verb used.
Read
The read route lets us view all the documents within our makeshift JSON database. Here we would make a get request to the common endpoint for the resource we are interested in.
A request to the http://localhost:3000/profiles
endpoint would fetch all the data under the resource key - “profiles”
For the “branches” resource, we would make a get request to http://localhost:3000/branches
.
Recall that JSON Server
provided these endpoints immediately after we started the server. A close look at these endpoints shows that it is just the home endpoint and the resource key.
Read-One
Now there are situations where you need to view a particular object in the array of objects that is your resource. For example, if we wanted to fetch an entry in the profiles resource with the id of 2, we use the endpointhttp://localhost:3000/profiles/2
, where 2 is the unique id given to that object within the array of objects.
Note that this unique id must not necessarily use numbers; for instance, in trying to get the third entry on the branches resource, we would have http://localhost:3000/branches/ijk3
, where ijk3
is the id for the third entry.
Since the default browser search bar performs a get request, we can easily visit an endpoint for any get requests to visualize the response.
Get a request to http://localhost:3000/profiles
using the search bar
Get a request to http://localhost:3000/branches/ijk3
using the search bar.
Create
To create a new entry to any of the resources, we would send a post request to the same endpoint,http://localhost:3000/profiles
, which gives us access to the profiles resource. The post-request body will contain the data you want to add to that resource.
fetch("http://localhost:3000/profiles", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "Kara kent",
position: "Head of Advertisement",
contract: false,
jobDescription:
"Develops and executes advertising campaigns to promote a business or product.",
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
The code block above will send a post request that adds a sixth entry to the profiles resource. Note that you do not need to specify an id as this will automatically be created by JSON Server
.
Update
To update an already existing entry in our database, we will make a patch request to a slightly modified endpoint. This endpoint will consist of the base endpoint and the entry’s id we want to edit. For updating branches with the id of 2, we would send our patch request tohttp://localhost:3000/branches/def2
with our update contained within the body of the patch request. Note that the endpoint is similar to getting a single specific entry.
fetch("http://localhost:3000/branches/def2", {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
state: "New York",
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
The patch request above will change the state of the 3rd entry in branches from Gotham to New York.
Delete
The delete operation is a pretty straightforward one. Here, we send a delete request to the endpoint referencing the unique id for the entry we want to delete. A delete request tohttp://localhost:3000/profiles/2
will delete the entry with id 2 in the profiles resource.
More operations
While fetching data, we often want to organize them in a certain manner on the front end, which makes them easier to access for users of our application. Instead of fetching all the data to the front end before manipulating and organizing it, JSON Server
gives us some helper endpoints to make this easier. These endpoints are created by adding on some specific query strings outlined in the JSON Server
documentation (see https://github.com/typicode/json-server). Let us proceed to take a look at some of these operations:
- Filtering Operations
This operation is commonly used when making a search bar. It uses a query string on the resource endpoint that looks something like this:
http://localhost:3000/profiles?q=w
; where the key must be “q” and “w” (the value) can be any keyword that a user is looking for amongst the resources in our database. The above endpoint will filter through the entries under the profiles key and only return entries with the letter “w.” Since this is aget
request, we can see the result by searching this in the browser while our server runs in the background.
Get request to http://localhost:3000/profiles?q=w
using search-bar
- Sorting Operations
This operation requires a query string with a “sort” key and an order key that looks like these examples:
http://localhost:3000/profiles?_sort=id&_order=desc
http://localhost:3000/profiles?_sort=name&_order=asc
The sort key is assigned a value which is the property you want the data to be sorted by, and the “order” key takes a value of “asc” or “desc” for ascending and descending order, respectively. This can help organize your data and ensure it comes out in a predictable order after fetching it from the server.
- Pagination Operations
Pagination is a common technique used for presenting a long list of data. It may be implemented by fetching only a certain number of data entries for each page. Using query strings, the limit key (
http://localhost:3000/profiles?_limit=3
) provided byJSON Server
allows us to specify how many entry results should be sent back on each fetch and the start and end keys (http://localhost:3000/profiles?_start=2&_end=4
) function just as you would expect. They allow us to define which entry to start sending results from and where to stop at. Combining these two operations would make pagination so much easier.
Session Replay for Developers
Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — an open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data. Check our GitHub repo and join the thousands of developers in our community.
Custom Routes
At this point, you already have the key operations down and should be ready to use JSON Server
, but consider this a bonus section.
Custom Routes allow us to rename the endpoints provided to us initially by JSON Server
.
To create a custom route;
- Create a routes file within your Data folder.
- The file name should be route.json.
- Create a JSON object matching the resource name to a custom path. The resource name will be the key. The custom path will be the property.
- Be sure to start all routes with a ”/.”
- Our routes.json file should look something like the code sample below.
{
"profiles": "api/staff/profiles",
"branches": "api/branches"
}
- Go ahead and run the command
json-server --watch Data/Db1.json --routes Data/routes.json
You should notice that the custom routes you defined on executing the command are listed as alternate routes. You can now use these routes instead of the original ones; they should work the same.
Using faker-js with JSON Server
faker-js is a library for generating fake data, which can be valuable during testing and development. It provides us with methods that we can call that return data of a certain kind which we can then use in developing our application. A quick look at https://www.npmjs.com/package/@faker-js/faker will bring you up to speed on how it works independently.
To use faker.js with JSON server
, you can create a script that generates fake data using faker.js and then write that data to a .json
file that JSON Server
can use as its data source.
Here’s an example of such a script:
const faker = require("faker");
const fs = require("fs");
const db = {
users: [],
};
for (let i = 0; i < 10; i++) {
db.users.push({
id: i,
name: faker.name.findName(),
email: faker.internet.email(),
address: faker.address.streetAddress(),
});
}
fs.writeFileSync("./db1.json", JSON.stringify(db), (err) => {
if (err) {
console.error(err);
} else {
console.log("Data written to file 'db.json'");
}
});
This script generates ten fake users and writes the data to a file called db1.json
. You can then start JSON server
and use this file (db1.json) as the data source.
json-server --watch db1.json
Now you have a REST API that returns fake user data generated using faker.js. You can access this data by making requests tohttp://localhost:3000/users
.
Summary
JSON Server
is a simple, lightweight, and easy-to-use fake REST API server. It falls under the category of a mock or stub server used for testing purposes during web development. It provides a full fake REST API with zero coding and allows developers to simulate a REST API by defining the data, routes, and responses in a JSON file. JSON Server
is typically used in testing front-end code, such as Angular, React, or Vue applications that interact with a REST API.
However, note that JSON Server
is not a production-ready server and should not be used for hosting critical applications or data.