JSON-Server as a Fake REST API in Frontend Development


Frontend development is changing day by day and we have to learn a lot more stuff. When we start learning a new framework or library, the first thing that is recommended to build a todo list which helps in doing all CRUD functions. But there is no solid backend/library available to make use of it to build a todo list.

Simulate a backend server and a REST API with a simple JSON file.

To overcome that problem json-server came into the picture. With it, we can make a fake REST api. I have used it in my app and thought of sharing it to the frontend community.

JSON Server is an npm package that you can create a REST JSON webservice. All we need is a JSON file and that will be used as our backend REST.

#Installing JSON Server

You can either install it locally for specific project or globally. I will go with locally.

$ npm install -D json-server

Above is a single line command to install the json server. -D Package will appear in your devDependencies. I am not going to explain about that much here. If you want to learn more about that go through the docs for npm install. Check JSON Server version using json-server -v.

#JSON file

As per the standard convention, I am going to name the file db.json, you can name it as per your needs.

{
  "Todos": [
    {
      "id": 1,
      "todo": "Check Todo"
    },
    {
      "id": 2,
      "todo": "New Todo"
    }
  ]
}

For simplicity I have included two elements into the Todos array. You can add more also.

#Start the JSON Server

$ json-server --watch db.json

TerminalYour JSON Server will be running on port 3000.

Now that we have our server and API running, we can test it and access it with a tool like POSTman or Insomnia.

These are REST clients that help us run http calls.

#CRUD Operations

Moving onto the CRUD operations. This is how we can access our data using RESTful routes.

Routing Url's
[GET] http://localhost:3000/Todos
[POST] http://localhost:3000/Todos post params:!
[PUT] http://localhost:3000/Todos post params:!
[DELETE] http://localhost:3000/Todos/id

#Testing via POSTman

GET REQUEST

POSTman

POST REQUEST

POSTman

PUT REQUEST

POSTman

DELETE REQUEST

POSTman

 

Thanks to Madhankumar for this article help.

Happy Coding 🙂

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s