Setting up a fake JSON REST API

Oct 10th, 2021


Setting up a fake JSON REST API

cd ~/faker-sandbox
npm install --save json-server
mkdir server
cd server

In the server folder, create a database.json file and add the following JSON object:

    "products": []

This JSON file will act as a database for your REST API server. You can simply add some data to be served by your REST API or use Faker.js for automatically generating massive amounts of realistic fake data.

cd ..
npm install faker --save

Now, create a generate.js file inside server directory and add the following code:

var faker = require('faker');

var database = { products: []};

for (var i = 1; i<= 300; i++) {
    id: i,
    name: faker.commerce.productName(),
    description: faker.lorem.sentences(),
    price: faker.commerce.price(),
    imageUrl: "",
    quantity: faker.datatype.number()


We converted the database object to a string and log it to standard output. Next, add the generate and server scripts to the package.json file:

"scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "generate": "node ./server/generate.js > ./server/database.json",
    "server": "json-server --watch ./server/database.json"

Run the generate script using the following command:

npm run generate

Finally, run the REST API server by executing the following command:

npm run server

Your server will be available from the http://localhost:3000/ address.

  • GET /products for getting the products,
  • GET /products/<id> for getting a single product by id,
  • POST /products for creating a new product,
  • PUT /products/<id> for updating a product by id,
  • PATCH /products/<id> for partially updating a product by id,
  • DELETE /products/<id> for deleting a product by id.

You can use _page and _limit parameters to get paginated data. In the Link header you’ll get first, prev, next and last links.

  • GET /products?_page=1 for getting the first page of data
  • GET /products?_page=1&_limit=5 for getting the first five products of the first page of data.

For the features such as filters, sorting and ordering, check out the docs.