Web API – Json Server

In this post, we will see how to create a full fake Rest API for testing, using a Javascript library called Json-Server.
Here, it is possible to find the project.


[HOW TO INSTALL]
First of all, we have to install node.js in our system, because Json Server is available as a NPM package.
Then, using the command npm install -g json-server we will install the library:


Now, we have to create a file json where we will insert our ‘fake data’:

[data.json]

{
    "users": [
      {
        "id": 1,
        "username": "username1",
        "password": "password1",
        "email": "user1@test.com"
      },
      {
        "id": 2,
        "username": "username2",
        "password": "password2",
        "email": "user2@test.com"
      },
      {
        "id": 3,
        "username": "username3",
        "password": "password3",
        "email": "user3@test.com"
      }
    ]
  }


In this case, we will have a list of users with 4 properties.

Finally, with the command json-server –watch data.json, we will start our ‘fake’ server:




[HOW TO USE]
Json Server is running and now, using Postman, we will check everything works fine.


GET All
We open Postman, select GET and we insert this url: http://localhost:3000/users


GET {id}
We open Postman, select GET and we insert this url: http://localhost:3000/users/2


POST
We open Postman, select POST, insert this url: http://localhost:3000/users and in the Body we write:

{
  "id": 4,
  "username": "username4",
  "password": "password4",
  "email": "user4@test.com"
}



Now, we run [Get all] to check the Post operation:



PUT
We open Postman, select PUT, insert this url: http://localhost:3000/users/2 and in the Body we write:

{
  "username": "new username2",
  "password": "new password2",
  "email": "user2@test.com"
}

Now, we run [Get all] to check the Put operation:



DELETE
We open Postman, select DELETE and we insert this url: http://localhost:3000/users/4:


Now, we run [Get all] to check the Delete operation: