Building mock APIs using JSON Schema Faker and JSON Server
In this tutorial, we are going to build a mock API using JSON Schema Faker and JSON server.
Why would we need a mock API?
Often, when working in a project, there are some parts of the projects that depend on making API calls. Some of which haven’t been built by the backend team.
This might sometimes cause the frontend team to stall on delivering the project.
Using a mock API, we can create the data we need and use it for the development of our app without waiting for the backend team and when the backend team is done, we can replace the mock API with the actual API.
Building the mock API
To build the API, we will use the following
- A JSON file — The JSON file will act as the data storage.
- A Server — We will need a server to serve the JSON file. The server should be able to create endpoints from the JSON file.
Since we are using a JSON file to store the data, we will need to generate this file and add content to it. This can be done using JSON Schema Faker.
JSON Schema Faker is a javascript library which can be used for generating JSON data. The data will be generated based on the schema which is presented to it.
Create a new folder mock-api which will be the hold the mock API.
Open up a terminal and change the directory to that of the folder and run the following command to initialize npm.
npm init -y
The above command will create a package.json file with the default settings. Feel free to edit the content of package.json to suite your choice.
Next, we need to install JSON Schema Faker.
npm install json-schema-faker
npm install faker
We are also installing faker since we will need to create some fake data. JSON schema faker has inbuilt support for faker. Hence it will be so easy to integrate.
In the root directory, create a file, index.js. This file will handle the responsibility of creating the JSON file using JSON Schema faker.
JSON Schema faker uses adheres to the JSON Schema so let’s learn a bit about that.
Introducing the JSON Schema
A JSON Schema is a standard for a valid JSON file. It is in itself a JSON document.
A JSON schema can be as simple as:
{
"type": "boolean"
}
The above schema will be valid for a boolean — true
or false
.
Other data types can be represented easily in JSON schema as shown below:
// string like "James"
{
"type": "string"
}
// integer like 10
{
"type": "integer"
}
Complex data like objects can be represented as:
{
"type": "object",
"properties": {
"name": {
"type": "string"
},
"school": {
"type": "string"
},
"class": {
"type": "string"
}
}
"required": ["name", "school", "class"],
}
After setting type to object, we need to set which properties will be in our object. we do this by setting properties as part of the schema. In this case, the properties our object should have is name
, school
and class
. We can further set the types for the properties. In the above example, all the properties are strings. In some other cases, the properties can be integers, numbers — including floats, arrays or even objects.
We set which properties are required in the object, by setting the required property on the schema. This property is an array of strings which represent the required properties of the object.
The above schema would be valid for the following object:
{
name: "A name",
school: "Monef High School",
class: "Junior Secondary"
}
Arrays can be represented as:
{
"type": "array",
"items": [
{
"type": "string"
},
{
"type": "number"
}
]
}
The items key shows the kind of items that should be in the object. in this case, the first item in the array should be a string, while the second item a number.
To learn more about JSON Schema, go through it here.
JSON Schema Faker
JSON Schema Faker is a tool that combines JSON Schema standard with fake data generators, allowing users to generate fake data that conform to the schema.
To generate fake data, we provide JSON schema faker with standard JSON Schema. JSON schema faker then uses this schema to create fake data.
You can try out JSON Schema faker at https://json-schema-faker.js.org/.
In index.js which was created earlier, import JSON Schema Faker by adding the following to it:
const jsf = require('json-schema-faker');
Using one of the schemas above, let us generate some fake data.
const schema = {
"type": "object",
"required": ["name", "email"],
"properties": {
"name": {
"type": "string"
},
"email": {
"type": "string"
},
}
}
jsf.resolve(schema).then(result => {
console.table(result);
});
The above code logs:
console.table
is used here so that we can get the details of the object in a tabular format.
JSON Schema Faker can be used with faker.js to provide fake data that actually make sense. We can use faker to get fake names, emails, etc.
Using faker,
const jsf = require('json-schema-faker');
jsf.extend('faker', () => require('faker'));
const schema = {
"type": "object",
"required": ["name", "email"],
"properties": {
"name": {
"type": "string",
"faker": "name.findName"
},
"email": {
"type": "string",
"faker": "internet.email"
}
}
}
jsf.resolve(schema).then(result => {
console.table(result);
});
Using faker, the generated object looks realistic.
Creating the data
Now that we have learned how to create schemas and generate objects from them, let’s create the data for our API.
We are going to build a mock users API. This means we will be able to carry out all CRUD operations on the data. Let’s write the schema:
Create a new file — users.schema.js.
const {resolve, extend} = require('json-schema-faker');
const fs = require('fs');
extend('faker', () => require('faker'));
const schema = {
type: "object",
required: ["users"],
properties: {
users: {
type: "array",
minItems: 20,
items: { "$ref": "#/definitions/users" }
}
},
definitions: {
users: {
type: "object",
required: [ "id", "first_name", "last_name", "age", "email", "username", "avatar" ],
properties: {
id: {
$ref: '#/definitions/positiveInt'
},
first_name: {
type: "string",
faker: "name.firstName"
},
last_name: {
type: "string",
faker: "name.lastName"
},
age: {
type: "integer",
maximum: 70,
minimum: 18
},
email: {
type: "string",
faker: "internet.email"
},
username: {
type: "string",
faker: "internet.userName"
},
avatar: {
type: "string",
faker: "internet.avatar"
}
}
},
positiveInt: {
type: 'integer',
minimum: 0,
exclusiveMinimum: true
}
}
}
resolve(schema).then(sample => {
console.log('Writing to db.json')
fs.writeFile(`${__dirname}/db.json`, JSON.stringify(sample), function(err) {
if(err) {
console.error(err);
} else {
console.log("done");
}
});
});
The above schema is that of an object that contains just one property — users. Users
is an array of objects, and each object contains data for a particular user. The minItems
property specifies the minimum number of elements that should be available in the generated array. The only item in the array is a user object, which is somewhat complex, hence we create something called a definition for it.
Definitions allow us to write the schema for specific properties, in this case, the user objects.
You can read more about definitions here.
The user object contains the following properties: id
, first_name
, last_name
, age
, email
, username
and avatar
. Id is the only complex data typed property here, hence a definition for it. Others are either strings or integers and are generated using Faker.
Lastly, after generating the data, we write it to a file called db.json. This file will be created in the same directory if it doesn’t exist already.
To complete the mock API, we need a way to serve our data.
Serving up the API
JSON server is a tool that is used to serve JSON files. It provides full rest functionality and even supports some additional features.
Install JSON server by running the command below:
npm install -g json-server
Once that is done, we are ready to serve our mock data.
Run the following command to serve the data.
json-server --watch db.json
Note that the above command must be run in the same folder as the generated db.json.
If everything works fine, you should have an output similar to:
The mock API can be accessed at http://localhost:3000/users/.
All CRUD functionality is supported and can be tested via postman.
Single user data can be found at http://localhost:3000/users/<id> where id is the id of the user as gotten from the API.
As you can see, the JSON server automatically creates the /users
route for us since it noticed the user property in the object contained in db.json. Adding more properties to the root object will create more routes for the mock API.
Conclusion
No longer do you need to wait for the backend folks to be done with the API. Create a mock API and build your frontend on the fly.