JSON Server

Kevin Neyer
3 min readDec 18, 2020

Firing Up a Quick Database

Introduction

This last week, I’ve been brushing up on ReactJS. When I think React, I think components, state, props, and event handling. As I was jotting down ideas and planning out topics to practice, it occurred to me — I hadn’t touched fetch requests in quite a bit of time. And honestly, the syntax wasn’t popping up rapidly. Not a great realization. However, I could change that! With that in mind, working on fetch requests became my goal. The next thought became — how can I do that without creating a full backend application for my server? I then remembered that some of our bootcamp labs and code challenges had a way for doing this. A little knocking around the old brain cobwebs, and it came to me: JSON Server!

What It Is

JSON Server is an npm package, and it is a full fake rest API intended for moments when a quick back-end for prototyping and mocking is needed.

How to Use

Getting Started

Since it is an npm package, to install within the desired project directory, use the command

$ npm install json-server

This will put JSON Server as a dependency for your project.

Setting Up

The meat and potatoes of the server will live in a file called db.json. In your file tree, create that file. Then, within that file, since we’re dealing with JSON, create what looks like a plain old JavaScript object. Then within that object, create a key, named whatever you want your endpoint to be named, and have that point to a value of an array. Then, within the array, create objects that will represent the data you’d like to store.

db.json file

Here, I was working on a banking app, so I created an endpoint called transactions, which points to an array of transactions. Each bit of data can contain as much or as little as you want. My app didn’t need much, so each transaction only has four qualities. The beauty of the JSON server, if I want to add or delete anything, I can go into the file and manually do it. Want to add a category to each transaction, add it! Want to delete one, let it go! No schema, no rollbacks. Plain, simple, and easy.

Using It

To get your server up and running, use the command.

$ json-server --watch db.json

The default port this will go to is 3000. To use a different port, simply flag it in your command.

$ json-server --watch db.json -p 3001

Now, going to ‘http://localhost:3001/transactions’ I should see my database.

localhost live

Awesome! The database is up and running! Now, for any fetch requests(get, post, patch, delete), this is my endpoint, and I can run my frontend based off of this.

Conclusion

JSON Server is a great resource for frontend developers looking to spin up a server quickly and with little effort. It’s perfect for making sure our code is working the way we intend. Give this npm a shot, and hopefully you’ll enjoy using it as much as I do. Happy coding!

--

--