Building Mock JSON APIs

Sometimes in contents 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 content.

Content 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 content 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:

"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
"profile": { "name": "typicode" }
Description=Mock API
ExecStart=/usr/local/bin/json-server --port 8888 --host --watch /tmp/db.json

That's it! Launch the content, 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'}]