For creating a mock api we will use the json-server package that will help us to create a mock api without any hassle. Which can be consumed by any framework of javascript like React, Vue, Angular etc. Even without them.

To install this in your machine globally run this command.

npm install -g json-server

Create a folder where you want to create a mock api in my case I will create a folder with api name. And open the terminal in that folder and run this command.

json-server --watch db.json

If there is no file with db.json name it will create one with some prepopulated that you can edit according to your needs.

It looks something like this and all the endpoint will be present there that can be edited too. Json Server Terminal Screenshot

Genrated json will look like this.

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

Here json keys work as endpoints. For example key posts’s data can be access with this endpoint /posts. If your api is runing on localhost:3000 the api url will be http://localhost:3000/posts. The endpoints and data can be edited according to our needs.

If you make POST, PUT, PATCH or DELETE requests, changes will be automatically and safely saved to db.json

For more details visit this url https://www.npmjs.com/package/json-server#getting-started

Happy Coding 🙌 !