DEV Community

Jacob Hunsaker
Jacob Hunsaker

Posted on • Edited on

Using json-server for quick databases

This time, I would like to introduce a very handy npm package for creating & using a simple JSON database called json-server. For the official documentation from the developer, you can check this site out.


To start off, let's install the package, first! Just like any other npm packages, you can simply install it using npm.

npm install -g json-server
Enter fullscreen mode Exit fullscreen mode

Once you have the package installed, the next step is creating a json file with the name db.json with some data in it.

{
   "address": [
      "name": "Jacob Hunsaker",
      "address": "Somewhere in United States",
      "phone_num": "123-456-7890",
      "email": "jacobjhunsaker@gmail.com",
      "id": 1
   ],
}
Enter fullscreen mode Exit fullscreen mode

Once you have everything set up, you can now actually use json-server. You can start json-server by going to the directory that has db.json and typing the following in the console.

json-server --watch db.json
Enter fullscreen mode Exit fullscreen mode

Now if you go to http://localhost:3000/address/1, you'll get the following in JSON.

"name": "Jacob Hunsaker",
"address": "Somewhere in United States",
"phone_num": "123-456-7890",
"email": "jacobjhunsaker@gmail.com",
"id": 1
Enter fullscreen mode Exit fullscreen mode

Now in your front-end (Vue.js & axios in my case), you'll just need to GET/POST/PUT/PATCH/DELETE the data into http://localhost:3000/address. Since we're using json, we'll also have to add the headers to your PUT/PATCH request.

const response = await fetch(
               `http://localhost:3000/address/${id}`,
               {
                  method: "PATCH",
                  body: JSON.stringify(updatedContact),
                  headers: {
                     "Content-type": "application/json; charset=UTF-8",
                  },
               }
            );
Enter fullscreen mode Exit fullscreen mode

For a sample page, please check this simple Github repository using Vue.js.

If there are things I could improve on, please don't hesitate to let me know! I'm all ears :)

-JH
LinkedIn | Github

Top comments (0)