Introduce two great artifacts! Using json-server and faker.js to simulate REST API

Today, we found a magic artifact, json-server! With his help, we can build a Rest API in a very short time, and then we can let the front end develop without relying on the back end.

About what RESTful API is:
"RESTful API Design Guide" - Ruan Yifeng
http://www.ruanyifeng.com/blo...

JSON-Server

Simply put, JSON-Server is a Node module that runs the Express server. You can specify a json file as the data source of the api.

For instance:
Now we want to make an app to manage customer information and implement simple CRUD functions (create/retrieve/update/delete), such as:

  • Getting customer information

  • Add a customer

  • Delete a customer

  • Update customer information

Okay, let's use json-server to complete this series of actions.

Install JSON-Server

npm install -g json-server   //osx system plus'sudo'

Create a new folder while cd it:

mkdir customer-manager && cd customer-manager

Create a new json file and store a bit of data in it:

touch customers.json
{
  "customers": [
    { "id": 1, "first_name": "John", "last_name": "Smith",  "phone": "219-839-2819" }
  ]
}

Turn on json-server functionality

All you have to do is just let json-server point to this customer. json, ok ay!

json-server customers.js

And then there's this hint, ok ay!

In addition, the cool thing about JSON-Server is that it supports various GET/POST/PUT/DELETE requests.
Look at a few examples:

//GET
fetch('http://localhost:3000/tasks/')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json: ', json)
  }).catch(function(ex) {
    console.log('parsing failed: ', ex)
  });


//POST
fetch('http://localhost:3000/tasks/', {
  method: 'post',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
       "title":   "Add a blogpost about Angular2",
       "dueDate": "2015-05-23T18:25:43.511Z",
       "done": false
   })
}).then(function(response) {
      return response.json()
    }).then(function(json) {
      console.log('parsed json: ', json)
    }).catch(function(ex) {
      console.log('parsing failed: ', ex)
    });
    
    
//PUT
fetch('http://localhost:3000/tasks/1', {// specify id after url
  method: 'put',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
       "done": true
   })
}).then(function(response) {
      return response.json()
    }).then(function(json) {
      console.log('parsed json: ', json)
    }).catch(function(ex) {
      console.log('parsing failed: ', ex)
    });
    
    
//DELETE
fetch('http://localhost:3000/tasks/1', {
method: 'delete'
}).then(function(response) {
   return response.json()
 }).then(function(json) {
   console.log('parsed json: ', json)
 }).catch(function(ex) {
   console.log('parsing failed: ', ex)
 });

JSON-Server is basically like this! Next, I will introduce another artifact.

Faker.js

If you want to make up API data by yourself, it's troublesome. It's easy to solve this problem with faker.js. It can help you automatically generate a large number of fake json data as back-end data

Install faker.js

Or use npm to install faker.js:

npm install faker

Now we use javascript to generate a json file containing 50 customer data:

//customers.js
var faker = require('faker')

function generateCustomers () {
  var customers = []

  for (var id = 0; id < 50; id++) {
    var firstName = faker.name.firstName()
    var lastName = faker.name.firstName()
    var phoneNumber = faker.phone.phoneNumberFormat()

    customers.push({
      "id": id,
      "first_name": firstName,
      "last_name": lastName,
      "phone": phoneNumber
    })
  }

  return { "customers": customers }
}

// If you want to use json-server, you need export, the function that generates fake data.
module.exports = generateCustomers

Then let json-server point to the js file:

json-server customers.js

So you can http://localhost:3000/customers Here we see 50 customer data.
More faker.js attributes can be seen here:
https://github.com/marak/Fake...

Well, that's basically it, happy coding!

Tags: Javascript JSON npm github REST

Posted on Sat, 29 Dec 2018 07:09:08 -0800 by please_explain