input license here

Create Mock API with JSON Server

During the development of the mobile app, sometimes the server rolls to death or the network line in the company has a problem, you have to wait until the server is restored or stable transmission can test and code again. Too wasted time right? To solve this problem, mock api is the solution that helps us avoid dependency on response from server returned. This article will introduce JSON Server help us create mock api simply and quickly.

Basic

Install json-server with the following command
npm install -g json-server
Create a json database and name it db.json as shown below:
{
"users": [
{
"id": 1,
"userId": 101,
"name": "Alice"
},
{
"id": 2,
"userId": 102,
"name": "Bob"
},
{
"id": 3,
"userId": 103,
"name": "Carol"
}
]
}
Initialize the server with the database created
json-server --watch db.json
You can request to server following link:
curl http://localhost:3000/users
The GET request returns the created data in the json database file. Add new data to the database using the POST command as follows:
curl -d "userId=104&name=Dan" http://localhost:3000/users

Custom Routes

If you want to create different routes or create package.json as follows:
{
"name": "json-server-test",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"devDependencies": {
"json-server": "^0.14.0"
}
}
and a server.js as follows:
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./db.json');
const middlewares = jsonServer.defaults();
const port = process.env.PORT || 3000;

server.use(middlewares);
server.use(router);
server.listen(port);
With server.js we will create the server, set up the database and router and use default middlewares.
To extend the route we need to add a rewriter.
server.use(jsonServer.rewriter({
'/api/users': '/users'
}));

POST Routes

To customize the route for the POST command, we need to use the bodyParser
server.use(jsonServer.bodyParser)
server.post('/post/user', (req, res) => {
if (req.method === 'POST') {
let userId = req.body['userId'];
if (userId != null && userId >= 0) {
let result = db.users.find(user => {
return user.userId == userId;
})

if (result) {
let {id, ...user} = result;
res.status(200).jsonp(user);
} else {
res.status(400).jsonp({
error: "Bad userId"
});
}
} else {
res.status(400).jsonp({
error: "No valid userId"
});
}
}
});
So, the only difference here is that we get the body from the request instead of the query. If you do not use bodyParse then the body part will not be defined curl -d "userId=101" http://localhost:3000/post/user
Result : 

Create Fake Data

The moke api creation is complete, but suppose you need a lot of data in the database for thousands of records. At that point, creating manual data is not working. Faker will help us solve this problem Install Faker
npm install --save faker
Create and run a js as follows
var faker = require('faker');

function generateData () {
var messages = [];
for (var id = 0; id < 10; id++) {
let priority = faker.random.number({min: 1, max: 2});
let date = faker.date.between("2018-01-01", "2018-07-31").toISOString().split("T")[0];
let fromId = faker.random.number({min: 1000, max: 9999})
let message = faker.hacker.phrase();
let status = faker.random.number(1);
messages.push({
"id": id,
"from_userId": fromId,
"date_sent": date,
"priority": priority,
"message": message,
"status": status
});
}

return {messages};
}

module.exports = generateData;
json-server generate-data.js
Examine the previous data using the GET command

Hosting JSON Server on Heroku

In addition to saving the server on the local machine you can completely put your mock api server to Heroku https://www.heroku.com/ very easy and free with personal account
Related Posts
SHARE

Related Posts

Subscribe to get free updates

Post a Comment

Sticky