Quickly Create an API With Json-Server

I was working on a web application prototype where I had to quickly write data to a database and read it. I had to configure the database and connect it to my web application but lucky enough, I didn't go through all that hustle. My good friend, Author, introduced me to json-server.

In this article, I would like to show you how you can quickly create an API with json-server in less than 10 minutes.

json-server

JSON-Server is an open-source mock API server that makes it easy to create and test REST APIs. It is written in JavaScript, using Node.js, and provides a simple way to create a database of data that can be used for testing and prototyping. The server can be used to simulate real-world scenarios, such as reading and writing data to a database, and also supports custom routes, middleware, and other options.

Installation

Let's create a new folder for our project and initialize npm then install the json-server and axios:

$ mkdir hello-api
$ cd hello-api
$ npm init -y 
$ npm i json-server
$ npm i axios

Axios is a JavaScript library used for making HTTP requests from Node.js or XMLHttpRequests from the browser. It is promise-based and supports the Node.js environment as well as modern browsers. It provides a simple and clear API, handles errors, and can be used for making both HTTP requests and complex RESTful API calls.

json file

Let's create a json file named, languages.json, in our project folder and populate it with the following data:

{
  "languages": [
    {
      "id": 1,
      "name": "Python",
      "year": "1991"
    },
    {
      "id": 2,
      "name": "Visual Basic",
      "year": "1991"
    },
    {
      "id": 3,
      "name": "R",
      "year": "1993"
    }
  ]
}

Start the server

Before we can access the contents of the json file, we first need to start the json-server using the command:

$ json-server --watch languages.json

The --watch flag in json-server is used to watch the db.json file for any changes. If any changes are made to the file, the server will automatically restart and the new changes will be reflected in the API.

Get Request

The server is now up and running, let's create a new file in our project folder, get.js :

const axios = require('axios');

axios.get('http://localhost:3000/languages')
    .then(resp => {
        data = resp.data;
        data.forEach(e => {
            console.log(`${e.name}, ${e.year}`);
        });
    })
    .catch(error => {
        console.log(error);
    });

We're using axios to make a GET request, it returns an array of all the languages, and we loop through each entry in the array.

We can run the file by:

$ node get.js

This should display the following output:

Python, 1991
Visual Basic, 1991
R, 1993

Post Request

Let's create a new file to make a post request to the json-server, post.js:

const axios = require('axios');

axios.post('http://localhost:3000/languages', {
    id: 4,
    name: 'Java',
    year: '1995'
}).then(resp => {
    console.log(resp.data);
}).catch(error => {
    console.log(error);
});

We can run the file by:

$ node post.js

This should display the following output:

{ id: 4, name: 'Java', year: '1995' }

Put Request

We can modify the data in the languages.json file using the put request. We need to specify the id of the entry, we need to modify.

Let's create a new file and name it, put.js:

const axios = require('axios');

axios.put('http://localhost:3000/languages/4/', {
    name: 'Java',
    year: '1996'
}).then(resp => {
    console.log(resp.data);
}).catch(error => {
    console.log(error);
});

We can run the file by:

$ node put.js

This should display the following output:

{ name: 'Java', year: '1996', id: 4 }

Delete Request

We can delete an entry in the json file by using the delete request. Let's create a new file, delete.js:

const axios = require('axios');

axios.delete('http://localhost:3000/languages/4/')
    .then(resp => {
        console.log(resp.data)
    }).catch(error => {
        console.log(error);
    });

This will delete the entry with the id, 4.

We can run the file by:

$ node delete.js

This should display the following output:

{}

Sorting Data

Let's now sort our data by name and arrange it in ascending order. Create a new file, sort.js :

const axios = require('axios');

axios.get('http://localhost:3000/languages?_sort=name&_order=asc')
    .then(resp => {
        data = resp.data;
        data.forEach(e => {
            console.log(`${e.name}, ${e.year}`)
        });
    }).catch(error => {
        console.log(error);
    });

We can run the file by:

$ node sort.js

This should display the following output:

Python, 1991
R, 1993
Visual Basic, 1991

Searching

We use the q parameter in the url to search in the json file. Create a new file, search.js:

const axios = require('axios');

axios.get('http://localhost:3000/languages?q=R')
    .then(resp => {
        console.log(resp.data)
    }).catch(error => {
        console.log(error);
    });

This will return an array of all entries that have the letter, R, in them.

We can run the file by:

$ node search.js

We should see the following output:

[ { id: 3, name: 'R', year: '1993' } ]

Range

We can also get a specific range of data by using _lte and _gte . _lte stands for less than or equal to while _gte stands for greater than or equal to.

Let's create a new file, range.js:

const axios = require('axios');

axios.get('http://localhost:3000/languages?id_lte=2')
    .then(resp => {
        console.log(resp.data)
    }).catch(error => {
        console.log(error);
    });

This will only display the values that have an id of 2 or less than 2.

We can run the file by:

$ node range.js

This should display the following output:

[
  { id: 1, name: 'Python', year: '1991' },
  { id: 2, name: 'Visual Basic', year: '1991' }
]

Conclusion

In this article, we looked at how you can quickly creata an API with json-server in less than 10 minutes.