Spin Up A RESTful API in 30 Seconds or Less with json-server

An Introduction to json-server

Zachary Orona-Calvert
Level Up Coding
Published in
5 min readApr 27, 2020

--

Introduction

Oftentimes when developing a front-end project you need to retrieve data from a REST API and serve it on the front-end and when starting out, the idea of creating a full fledged API seems a bit much. Either you don’t know how to go about creating this API or your circumstances dictate that build the front-end out first. If this sounds like your situation, enter json-server.

What is json-server?

json-server is a package that allows a front-end dev to quickly spin up a REST API without manually setting up routes and schemas. It just works.

How To Integrate json-server.

As usual, we need to actually add the package to our project. You can do so with this command:

yarn add json-server --dev

Sidenote: The official documentation calls for a global install of json-server. I personally don’t like installing packages globally unless absolutely necessary because sometimes different projects might use different versions of package and global installations make it difficult to keep track of package versioning, especially when collaborating with other devs. I have not noticed any adverse effects of my local install of this package. If you want to do a global install you can use this command instead:

yarn global add json-server

Now that we’ve got json-server installed we have to tell it what data we want to use. We do this by creating a json file with some data in it. For simplicity, I am just going to name my file db.json, but you can name your file whatever you would like. The inside of db.json will be formatted like this:

{
"users": [{ "id": 1, "name": "Sally", "username": "yaGirlSally"}],
"comments": [{ "id": 1, "body": "Heyo", "postId": 1 }]
}

In this file users and comments are the path names and the stuff inside the curly braces is the content of those paths. Now that we have our data we can spin up our server by running this (make sure you’re in the same directory of db.json when you run this):

json-server --watch db.json

Assuming all is good you should see something like this in your console window (If all is not well with your json file, json-server will alert you):

And if we go make a get request on http://localhost:3000/users and http://localhost:3000/comments and we should see our data:

Nice! json-serveralso watches for file changes we make meaning any changes made to db.json inside the editor will automatically trigger a server reload. GET, HEAD, PUT, PATCH, POST, DELETE, and OPTIONS requests are all supported on these routes out of the box. Some important caveats though are:

  • A POST, PUT or PATCH request should include a Content-Type: application/json header in the request body. Otherwise, it will result in a 200 OK but without changes being made to the data.
  • Id values are not mutable. Any id value in the body of your PUT or PATCH request will be ignored. Only a value set in a POST request will be respected, but only if not already taken by another object.

Generating More Data For The Server

The above steps will get you up and running, but json-server can do more. A nice feature of json-server is the ability to randomly generate data with a script. We can do something like generate 10 random users:

//simpleUserGen.jsmodule.exports = () => {
const data = { users: [] };
// Create 10 users
for (let i = 0; i < 10; i++) {
data.users.push({ id: i, name: `user${i}` });
}
return data;
};

After writing our script we can run it by using this command:

json-server simpleUserGen.js

This is nice, but it is a little bland in terms of data depth and uniqueness. We can do better with help from a package called faker. To install run:

yarn add faker --dev

After installing we can create a file and inside write a basic script like this one:

// userGen.js
const faker = require('faker');
const genUsers = () => {
const users = [];
for (let i = 0; i < 10; i++) {
const id = i;
const firstName = faker.name.firstName();
const lastName = faker.name.lastName();
const email = faker.internet.email();
users.push({
id,
first_name: firstName,
last_name: lastName,
email,
});
}
return { users };
};
module.exports = genUsers;

This script uses the Faker.js methods to generate 10 random users. If you wanted more data fields, Faker.js supports many methods like addresses, dates, and phone numbers.

Then we run:

json-server userGen.js

And we see all of our new data:

The only downside of this is we cannot save this data into file without some middleware, which is referenced in this Github Issue thread. One hacky way of saving this data is to type s + <Enter Key> into the console when running json-server to save a snapshot of our data and then restart json-server while using that new saved db file.

Alternative port

Another neat feature is we can start json-server on other ports with the --port flag:

json-server --watch db.json --port 3003

CORS Issues

Sometimes when using json-server or any remote resource your browser will issue a CORS warning like this:

To get around this we can tell json-server that we would like to disable CORS with this flag:

json-server --no-cors db.json

Sidenote: Do not disable CORS on anything that will be released to the public. json-server isn’t meant for production anyways it just acts as a placeholder until a proper solution is implemented.

Defining a Config File

At this point your option flag list might be getting pretty long, fortunately json-server allows us to define the options in a file for use. All you need to do is create a file and define our rules. Something like this works perfectly:

{
“port”: 3000,
“no-cors”: true
}

and then tell json-server which config file we would like to use:

json-server -c settings.json db.json

Conclusion

json-server is great package that can act as a quick fix for a RESTful API server. It can be set up with more configuration options that I haven’t covered, but it can be read about in its well-written documentation.

Feel free to leave a comment if you have any questions, suggestions, or anything else!

--

--

Technology has been my passion since I was young, it started when I first edited a configuration file to get more in game credits. zachcodes.com