Skip to main content

Command Palette

Search for a command to run...

Running Db.json Using Json Server

Updated
3 min read

In a typical crud(create read update delete) application we need data in which we can read, add, delete, and do a lot of stuff with. Most of this data are always stored in an api.

An api is simply just an json with a couple of keys and values. such api can be used in our application by mapping through the api(data) and displaying it in our application.

Now there are a lot of ways to use or consume an api but for the sake of this article. we are gonna be focusing on axios.

Axios is a node package manager that allows you to make a request to the api. it could be a get, delete or post request.

With all this said, let's shift our focus to JSON SERVER.

What is a json server?

Most developers have heard of the term JSON. It abbreviates for "JavaScript Object Notation". JSON Server is a Node Module that you can use to create demo REST JSON services within a short span of minutes. All we need to do is have a JSON file as sample data. Let's see this in action

Step 1: Create a folder with any name you want. Then open your favorite code editor (I use VS Code) and open the folder in Editor you just created. The folder is empty now. If you are using VS Code open terminal (View > Integrated Terminal). If you are using another code editor open Terminal/Command Prompt and cd into the folder.

Make sure that you have Node.JS installed in your machine. If it isn’t there, just download it. Step 2: Write command in terminal/command prompt: npm init Now it will ask to provide some info. Just ignore and hit enter for everything.

Step 3: Now we have a package.json file inside the folder. Time to Install the JSON server together with axios. Write to the terminal: npm install --save json-server axios It will take some time to install. Once it installed you can see some other files/code added to your folder.

Step 4: Create a new file & name it db.json Put the JSON data you want to retrieve in your apps. I am pasting this data in db.json The data should look like this:

`{ “collection”: [ { “id”: 1, “date”: “08/09/2021”, “collect_id”: 11221, “farmer_uin”: 114422, “pond_id”: 1144, “procedure”: “20,000 UN”, “group”: “10,000UN”, “amount”: “10,000 UN”, “driver_name”: “John Smith”, “truck_plate_no”: “YLA-291EL”, “dep_time”: “09:35pm” }``

Step 5: In package.json replace the existing value of key name: “scripts” to: "scripts": { "json:server": "json-server --watch db.json" },

Step 6: Time to run the server. Write the command: npm run json:server The server should start on http://localhost:3000

Step 7: When you run http://localhost:3000 on your browser it would serve as your json data(api) then you can consume it with axios

NOTE You have to be conversant with axios in order to use the json server