This site runs best with JavaScript enabled.

How to Mock an API with random data from NodeJS

Raymon S

May 25, 2019

Video Blogger

As a frontend developer you often need data from an API. But sometimes the backend hasn't been setup by your team. In order for you to continue and mock your data, it's a good idea to not store your data structure on memory.

It's a good idea to start as soon as possible to talk with an external API where your data comes from. In this tutorial I want to go through a minimal setup for mocking your data. After this you should be able to extend it with your own data as needed.

Dependencies

In order to work with Node you need to have it installed on your machine. For the mac users I highly recommend to install it with NVM, because it will make it easier to update NodeJS in the future. (There is also a version for Windows).

Create a new folder to start for this project. Run npm init -y to initialize the folder with Node and it will create automaticly a package.json for you.

In order to create the mockserver we need 2 npm dependencies. json-server and casual so we run npm install json-server casual --save-dev in our project.

Base for the mock-server

Create a index.js and paste this code in it.

const jsonServer = require('json-server')
const server = jsonServer.create()
const middlewares = jsonServer.defaults()
const port = process.env.PORT || 3000
server.use(jsonServer.bodyParser)
server.use(middlewares)
server.listen(port, () => {
console.log('JSON Server is running')
})

We include the json-server in order to use it. Then we create a server instance in the const server. With the middlewares we can set a few options like path to static files, CORS and few more. But here we just use it without and specific options.

The port is very important. If you want this to run on a server it will first search if there is any default port set for a Node server, otherwise it will pick port 3000.

We include the bodyParser and middleswarses by using server.user(). And after that we do a console log so you know the mock-server is running.

Generate data for 100 users

Create a folder /users and create a index.js in it.

First include the npm package casual in order to use it.

const casual = require('casual')

For specific language, if you don't want the english default:

const casual = require('casual').nl_NL

Than below it we need to export a module in order for use it in de index.js in the root later.

module.exports = () => {
casual.define('user', function() {
return {
name: casual.first_name,
surname: casual.last_name,
address: casual.street,
phone: casual.phone,
email: casual.email,
postalCode: casual.zip,
city: casual.city,
number: casual.building_number,
id: casual.uuid,
}
})
const data = {
users: [],
}
// Create 100 users
for (let i = 0; i < 100; i++) {
data.users.push(casual.user)
}
return data
}

With casual.define we define a object with a type "user". So in order to create data for 100 users in 1 go, we create a for loop that will run 100 times and pushes a user in the user array in our data object.

After that we return the whole object so we can use that in the root index.js.

Create a /user endpoint

In order to get the data for 100 users, we need to create an endpoint for the mock-server. Paste the code below in the root index.js, before the server.listen() function.

server.get('/users', (request, response) => {
if (request.method === 'GET') {
const users = require('./users/index')
response.status(200).jsonp(users())
}
})

In this case we use server.get() for a get request. But we also could choose "post", "put", "delete" and so on.

How to Mock an API with random data from NodeJS

As a frontend developer, you often need data from an API. But sometimes the backend hasn't been set up by your team. In order for you to continue and mock your data, it's a good idea to not store your data structure on memory.

It's a good idea to start as soon as possible to talk with an external API where your data comes from. In this tutorial, I want to go through a minimal setup for mocking your data. After this, you should be able to extend it with your own data as needed.

Dependencies

In order to work with Node, you need to have it installed on your machine. For the Mac users, I highly recommend to install it with NVM, because it will make it easier to update NodeJS in the future. (There is also a version for Windows).

Create a new folder to start for this project. Run npm init -y to initialize the folder with Node and it will create automatically a package.json for you.

In order to create the mockserver we need 2 npm dependencies. json-server and casual so we run npm install json-server casual --save-dev in our project.

Base for the mock-server

Create an index.js and paste this code in it.

const jsonServer = require('json-server')
const server = jsonServer.create()
const middlewares = jsonServer.defaults()
const port = process.env.PORT || 3000
server.use(jsonServer.bodyParser)
server.use(middlewares)
server.listen(port, () => {
console.log('JSON Server is running')
})

We include the json-server in order to use it. Then we create a server instance in the const server. With the middlewares, we can set a few options like the path to static files, CORS and a few more. But here we just use it without any specific options.

The port is very important. If you want this to run on a server it will first search if there is any default port set for a Node server, otherwise, it will pick port 3000.

We include the bodyParser and middleware by using server.user(). And after that, we do a console log so you know the mock-server is running.

Generate data for 100 users

Create a folder /users and create an index.js in it.

First, include the npm package casual in order to use it.

const casual = require('casual')

For specific language, if you don't want the English default:

const casual = require('casual').nl_NL

Then below it we need to export a module in order to use it in de index.js in the root later.

module.exports = () => {
casual.define('user', function() {
return {
name: casual.first_name,
surname: casual.last_name,
address: casual.street,
phone: casual.phone,
email: casual.email,
postalCode: casual.zip,
city: casual.city,
number: casual.building_number,
id: casual.uuid,
}
})
const data = {
users: [],
}
// Create 100 users
for (let i = 0; i < 100; i++) {
data.users.push(casual.user)
}
return data
}

With casual.define we define an object with a type "user". So in order to create data for 100 users in 1 go, we create a for loop that will run 100 times and pushes a user in the user array in our data object.

After that, we return the whole object so we can use that in the root index.js.

Create a /user endpoint

In order to get the data for 100 users, we need to create an endpoint for the mock-server. Paste the code below in the root index.js, before the server.listen() function.

server.get('/users', (request, response) => {
if (request.method === 'GET') {
const users = require('./users/index')
response.status(200).jsonp(users())
}
})

In this case, we use server.get() for a get request. But we also could choose "post", "put", "delete" and so on.

Inside we check if the request was a "GET" request. If so, we require our user's script and call the function inside the response so you will see the array of randomly generate users.

Run the mock-server

Now we are able to run that mock-server and get the data inside our frontend application.

Run node index.js inside the root folder of the project. Visit localhost:3000/users and you will see 100 users in the user array.

I hope this tutorial formed the base for you to generate more random data and expand your mock-server. If you have any questions, please let me know in the comments.

Inside we check if the request was a "GET" request. If so, we require our users script and call the function inside the response so you will see the array of random generate users.

Run the mock-server

Now we are able to run that mock-server and get the data inside our frontend application.

Run node index.js inside the root folder of the project. Visit localhost:3000/users and you will see 100 users in the user array.

I hope this tutorial formed the base for you to generate more random data and expand your mock-server. If you have any questions, please let me know in the comments.

Follow us on:

Follow us on Medium: https://medium.com/mr-frontend-communityFollow us on Twitter: https://twitter.com/frontendmrFollow us on Facebook: http://facebook.com/mrfrontendcommunity/ Follow us on Instagram: @mrfrontend

Share article