JSON Server - The Easiest Way to Set Up a REST API

JSON Server - The Easiest Way to Set Up a REST API

In learning a new library or framework, reading its official documentation, watching YouTube tutorials, and reading online articles aren’t sufficient to fully absorb what I’ve learned. For me, the best way to accomplish this is to create a mini-app that uses the technology that I studied. For client-side libraries and frameworks, I would always do my own version of Angular’s Tour of Heroes. Basically, the goal is to create an app that fetches data from your chosen external API and display it in the client in a form of listing and details pages.

However, searching for your desired external API can sometimes be an unnecessary stress because of any of the following reasons:

  1. The external API’s format doesn’t meet your needs as a client (e.g. there are missing fields and values in the returned JSON, the JSON returned has a deep nesting).
  2. The external API is not free (e.g. the client is only allowed to access the API for a limited number of times).

JSON Server

JSON Server is an NPM Package that allows us to have a fake REST API given a JSON without having to code (or maybe just a little). With JSON Server, problems regarding the desired structure of data, and its accessibility issues are addressed because developers will have the freedom to define their own data, and JSON Server is totally free.

Why JSON Server Over Other Available Alternatives?

JSON Server is not the only solution in order for us to have a customized external data source or API. There are other workarounds as well that can aide the problem. However, these workarounds may have pitfalls in terms of behavior, difficulty, and required effort.

  1. Creating a JSON file and importing it within the client - This may be the easiest way to get data and display it in the client but the problem is it is only useful in static websites or websites whose contents don’t change. Also, you can’t really practice sending HTTP requests.

  2. Creating your own REST API using popular backend frameworks such as NodeJS, Django, and Laravel - This is ideal in creating a full-stack application because it offers us control in the behavior of the HTTP requests. However, if the purpose is only to learn a client-side library or framework, this is very impractical since this may be time-consuming. In this approach, installation of the initial files required for the chosen backend framework, setting up of routes, handling HTTP requests, and sometimes creating your own database and connecting it to your backend should be implemented.

  3. Creating a Firebase Database REST API - This approach allows us to define or upload our JSON online and Firebase will automatically provide us accessible API endpoints based on our JSON. This is very similar to JSON Server but the main difference is JSON Server runs in the localhost while Firebase Database REST API runs online.

{
    users: [
        {
            id: 0,
            name: "Lyzer"
        },
        {
            id: 1,
            name: "Bautista"
        }
    ]
}

For example, if we try to use the JSON above in our Firebase REST API, Firebase will provide us a URL in the form of https://<FIREBASE_GIVEN_URL>/.json and it will return the entire JSON we have provided. To access the array of users, the URL to be used should be https://<FIREBASE_GIVEN_URL>/users.json. And to access the first user for example, the URL is https://<FIREBASE_GIVEN_URL>/users/0.json.

While this approach is relatively easier than setting up your own backend (workaround #2), in my own opinion, configuring these in Firebase can still be difficult especially for beginners.

How to Use JSON Server?

To use JSON Server:

  1. Make sure you have your Node and NPM installed so that you can install this NPM package.
  2. Create a folder for your project.
  3. Install JSON Server globally by typing npm i -g json-server in the Command Prompt or Terminal.
  4. In the same folder, create or paste the JSON file that would contain your data. For example, you can create data.json and paste the JSON code in the previous section.
  5. To start the JSON Server, type json-server --watch ./<YOUR_JSON_FILE> -p <YOUR_CHOSEN_PORT>
    1. For example, json-server --watch ./data.json -p 3500
    2. If you are using React, you may skip this and type npx json-server --watch ./<YOUR_JSON_FILE> -p <YOUR_CHOSEN_PORT> and press “Y” to automatically install JSON Server instead.
  6. There you go! You can now access your data through [http://localhost:<YOUR_CHOSEN_PORT>/](http://localhost:3500/users)<outermost_field>.
    1. For example, http://localhost:3500/users

You can add more routes by adding more fields in the JSON file. For example, if you want to have an endpoint with the route /cars , you may add the cars property to the JSON (make sure that it is in the same level with users. So your JSON file would something like:

{
    users: [{id: 0, name: "Lyzer" },{id: 1,name: "Bautista"}],
    cars: [{id: 0, brand: "Ford" },{id: 1, model: "Toyota"}]
}

Using Multiple JSON Files

The code can further be improved in terms of maintainability and readability by having a separate JSON file for each main route. First, separate the users and cars objects by creating a JSON file for each - users.json and cars.json .

//users.json
{    users: [{id: 0, name: "Lyzer" },{id: 1,name: "Bautista"}] }

//cars.json
{    cars: [{id: 0, brand: "Ford" },{id: 1, model: "Toyota"}] }

Next, create an index.js file. The role of this file is to import the individual JSON files, collate them, and export a single collated JavaScript Object which will serve as the main data.

// import the json files
const usersJson = require('./users.json');
const carsJson = require('./cars.json');

module.exports = () => {
    // return an object
    return {
        users: usersJson.users,
        cars: carsJson.cars
    }
}

Now, you can run this using json-server --watch ./index.js -p 3500 Github: [github.com/mercklyzer/json-server]

P.S. This is the first tech article that I wrote. If you have feedback, please let me know!