Building a 24/7 Fake REST API with JSON Server and Generated Data in 5 minutes

Alex Josef Bigler
Full Struggle Developer
7 min readApr 2, 2023

Have you ever found yourself in need of a backend solution to test/integrate with your front-end? We’ve all been there, and it happens more often than we’d like to admit. But fear not, my comrades! JSON Server is here to save the day.

This nifty tool allows you to create a backend in less than a minute that not only stores data but also supports various RESTful requests, including GET, POST, PUT, and more, all following standard operations. It’s the perfect solution for scenarios like this and many more.

In this article, we’ll not only install and run the server, but we’ll also write a script to generate random music data and turn our server into a constantly running service. So, prepare your droplet.

Rick looks at you somehow sternly, but at the same time with bewilderment

Build a server

First, make sure you have a dedicated server set up and installed with Node.js and npm. If you don’t have them installed yet, make sure to install them beforehand. JSON Server is available as an npm package, which can be installed using the Node.js package manager:

npm install -g json-server

Alright, we’ve tackled the hard installation step (I’m proud of you, champ 🤛). Now let’s skip the clichéd part that almost all tutorials suggest — creating a db.json file to demonstrate the server’s functionality.

Mocking data

We skipped the step of manually adding data to a JSON file. We’re not going to deal with that tedious task, okay? Instead, we’ll use the Faker module to generate fake data. Integrating Faker into JSON server is a breeze, just follow the steps below.

First, install Faker by using the NPM package:

npm install --save-dev @faker-js/faker

Second, make sure that you are imports it correctly:

// ESM
import { faker } from '@faker-js/faker';

// CJS
const { faker } = require('@faker-js/faker');

In this code, the first line uses the import statement, which is part of the ESM module system, while the second line uses the require statement, which is part of the CJS module system. Next, we will be using CJS.

Now, nothing is stopping us from getting creative and writing a script that generates the data we need. As an example, we will generate data for a music service, including artists, albums, songs, users, and posts. To add a cherry on top, we will use real images of fake album covers taken from r/fakealbumcovers.

In principle, you could just go to the GitHub repository that I created for you and skip reading the article further.

So, let’s start from the base. We create a file named index.js that will generate data for us:

This code is a script that generates data for a JSON Server database. It imports the Faker library and the Faker-js/Faker package. It also reads album data from a JSON file and sets a base URL for album covers. The data generated includes artists, albums, songs, users, profiles, and posts. It creates artists from album data, creates albums for each artist, creates songs for each album, creates users, creates profiles for each user, and creates posts for each user. Finally, it returns the generated data.

To run the script, you need a file named albums.json with the following structure (artist: albums[title, cover]):

{
"Childish Gambino": {
"albums": [
{
"title": "This Is America",
"cover": "60tp85ihwbl21.jpg"
},
{
"title": "Because The Internet",
"cover": "1d6d1e7nj0j21.jpg"
}
]
}
}

Don’t forget to specify your path/to/images. Also, feel free to change the data structure as you wish.

Starting a server

Next, we need to upload all the files to the server in the home directory and run the command:

json-server index.js

You will see console output:

Our server has successfully started and is now available at localhost. But that is not enough 🤔.

Turning a server into a service

As you might have read in other tutorials, after running the console command, your server will only work until you close the terminal. That’s not cool, especially if you have project collaborators working in different time zones. Therefore, let’s make this thing available 24/7.

Here, systemd comes to our rescue, as we simply explain to it that we need to run the server on our behalf.

Create a new configuration file for json-server, for example, /etc/systemd/system/json-server.service, and open it for editing:

sudo nano /etc/systemd/system/json-server.service

Insert the following text into the file:

[Unit]
Description=JSON Server

[Service]
Type=simple
ExecStart=json-server /root/index.js
Restart=always

[Install]
WantedBy=multi-user.target

Make sure that you have inserted the correct path to the json-server executable and the index.js file on your server.

Save and close the file.

Restart the systemd daemon to load the new configuration file:

sudo systemctl daemon-reload

Start the json-server service:

sudo systemctl start json-server

Now the json-server will be running as a daemon and will continue running even after closing the console.

To automatically start the json-server on server boot, execute:

sudo systemctl enable json-server

Now let’s check how our service is doing by executing the command:

sudo systemctl status json-server -l

You will see console output:

✧*。٩(ˊᗜˋ*)و✧*。

Connect a domain

So now our service is available 24/7, but only locally. That’s not cool enough, so let’s add the finishing touches: we need to make the service accessible from the internet.

I will skip the steps for creating a domain or adding a DNS record. I will just say that you need to add an A-record for the white IP address of your server in your DNS zone. And this may take more than 5 minutes, so you can consider me trolled with such a title for the article 🤡.

Alright, let’s proceed at a good pace, bam-bam.

Install Nginx:

sudo apt install nginx

To avoid a potential memory hashing issue when adding additional server names, one value needs to be changed in the /etc/nginx/nginx.conf file. Open the file:

sudo nano /etc/nginx/nginx.conf

Find the server_names_hash_bucket_size directive and remove the # symbol to uncomment the line. If you’re using nano, you can quickly find words in the file by pressing CTRL and w:

...
http {
...
server_names_hash_bucket_size 64;
...
}
...

Save the file and close it once done. Perform testing to ensure there are no syntax errors in the Nginx files:

sudo nginx -t

If there are no issues, restart Nginx to activate the changes:

sudo systemctl restart nginx

Next, we will create a server block for the domain example.com, which should be located at /etc/nginx/sites-available/example.com.

Don’t forget to replace “example.com” with your actual domain name.

sudo nano /etc/nginx/sites-available/example.com

Add the server_name line, as well as access_log and error_log paths as directives inside the server {} section. The configuration should look like this:

server {
server_name example.com;
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
}

To activate the file, create a symlink in the sites-enabled directory that Nginx reads on startup:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

Run nginx -t testing to make sure there are no syntax errors in the Nginx configuration files. If you receive an error message, reopen the server block file and check for typos or missing characters. When the configuration file syntax is correct, reload Nginx to load the new configuration.

Next, install Certbot.

sudo apt install certbot python3-certbot-nginx

To use Certbot’s Nginx plugin, which modifies Nginx configuration and reloads it when necessary, run the following command:

sudo certbot --nginx -d example.com

This command launches Certbot with the nginx plugin, using the -d option to specify the domain names for which we want to use the certificate. If this is the first time running Certbot, you will be prompted to provide an email address and accept the terms of service. After that, Certbot will contact the Let’s Encrypt server and send a request to verify that you control the domain for which you are requesting the certificate.

To add a reverse proxy for json-server, open the configuration file for your domain:

sudo nano /etc/nginx/sites-available/example.com

Then add the following code block to your domain’s configuration file. To pass the request to the proxy server, the proxy_pass directive is specified in the location section inside server section. This configuration results in forwarding all requests processed at this location to the proxy server at the specified address:

    location / {
proxy_pass http://localhost:3000/;
}

Save the file and close it once you are done. Test to ensure there are no syntax errors in the Nginx files, and then restart it.

This is it. Your domain name is now connected to the json-server, your certificates are loaded, installed, and activated. Try opening your domain using https:// and check the security indicator in your browser:

Now you have access to all API resources and can work with it from anywhere and using any tools, such as Postman or your new mobile application.

Conclusion

Respect if you have read this article to the end. As you can see, creating a fake API is not that difficult, and if you have deployed your own, you can customize and develop it as needed for your projects. There are no limitations here.

Or, if you don’t want to deploy your own, you can use what I have created: https://fake-api.sandbox.koodalabs.com/.

Also, feel free to use my repository or create an issue if you really like using my resource but feel that something is missing from the API. For example, authentication and JWT?

The link to my GitHub repository:

Have fun! See you in the next article.

--

--

Alex Josef Bigler
Full Struggle Developer

Enthusiast of new technologies, entrepreneur, and researcher. Writing about IT, economics, and other stuff. Exploring the world through the lens of data.