Building Mock JSON APIs

How to create a mock JSON API for use in a lesson.

Sometimes in lessons it is useful to illustrate how requests can be made to a JSON API. The following steps explain how to create a basic JSON API that can be used in any lesson.

Lesson Setup

The basic approach to creating the API is:

  1. Create a file with the mock data

  2. Use service to run the json-server package with the mock data

To get started, create a startup script with the following:

npm install -g json-server
cp /home/nt-user/workspace/.db.json /tmp/db.json
cp /home/nt-user/workspace/.mock-db.service /etc/systemd/system/mock-db.service
sudo systemctl start mock-db

This script:

  1. Installs the json-server library into the lesson environment.

  2. Moves the database and service file into place (explained below)

  3. Starts the mock database service

You will need to have the following files located in /home/nt-user/workspace:

.db.json
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
.mock-db.service
[Unit]
Description=Mock API
[Service]
ExecStart=/usr/local/bin/json-server --port 8888 --host 0.0.0.0 --watch /tmp/db.json
[Install]
WantedBy=multi-user.target

That's it! Launch the lesson, and localhost:8888 will return the data in .db.json.

This is just the beginning of what you can do with the json-server library. There are many more advanced examples explained here.

Using the API

Once you have the API setup, it's possible to request it via localhost:8888 (or whatever port you have specified).

For example, here's how you could request it with the Python requests module:

>>> import requests
>>> response = requests.get('http://localhost:8888/posts')
>>> print(response.json())
[{'id': 1, 'title': 'json-server', 'author': 'typicode'}]