Mocking your API with JSON Server

Mocking your API with JSON Server

I've just learned recently about this NPM package to mock a REST API using a JSON file. That's a life changer and I see myself using it for any front-end development I do in the future.

It's super simple to get started, all you'll need is Node.js installed and json-server.

To install json-server:

npm i -g json-server

Now all you need is a JSON file and run json-server against it. So try with this one and save it as db.json

{
  "products": [
    {
      "name": "apple",
      "categoryId": 1,
      "id": 1
    },
    {
      "name": "banana",
      "categoryId": 1,
      "id": 2
    },
    {
      "name": "watermelon",
      "categoryId": 1,
      "id": 3
    },
    {
      "name": "orange",
      "categoryId": 1,
      "id": 4
    }
  ],
  "categories": [
    {
      "name": "fruit",
      "id": 1
    }
  ]
}

Time to run it. I'm using the --watch flag so any change made directly to the db.json file gets reflected to the server

json-server db.json --watch

And that's all. You can try it out in the browser http://localhost:3000/products for example.

Cheers