Creating Mock APIs for Front-End Testing with JSON Server

Creating Mock APIs for Front-End Testing with JSON Server

Creating Mock APIs for Front-End Testing with JSON Server

 

Introduction

When building modern front-end applications, developers often need to test their UI before the API is ready. This is where JSON Server shines — it allows you to spin up a fully functional mock REST API in minutes, so your front-end can call realistic endpoints during development. In this post, we’ll walk through how to use JSON Server effectively, create a mock data set, set up routes, and integrate with your front-end for realistic testing.

1. Setting Up JSON Server

JSON Server is a lightweight Node.js tool that generates a REST API from a simple JSON file. To get started, install it globally using npm:

npm install -g json-server

Next, create a db.json file in your project root with mock data:

{
  "users": [
    { "id": 1, "name": "Alice", "email": "alice@example.com" },
    { "id": 2, "name": "Bob", "email": "bob@example.com" }
  ],
  "posts": [
    { "id": 1, "title": "Getting Started with Vue", "authorId": 1 },
    { "id": 2, "title": "Understanding React Hooks", "authorId": 2 }
  ]
}

Run the server using:

json-server --watch db.json --port 4000

Your mock API is now live at http://localhost:4000 with endpoints like /users and /posts. The beauty of JSON Server is that it automatically exposes standard REST routes for you — GET, POST, PUT, and DELETE.

2. Consuming Mock APIs from the Front-End

Once your mock API is running, you can interact with it from your front-end application. For example, here’s how to fetch user data using JavaScript’s fetch API:

fetch('http://localhost:4000/users')
  .then(response => response.json())
  .then(data => {
    console.log('Mock users:', data);
  })
  .catch(error => console.error('Fetch error:', error));

In a typical React component, you can call this API inside useEffect() to load data when the component mounts. The advantage here is that you can test your UI fully — forms, lists, loading states — without waiting for real backend endpoints to be implemented.

3. Customizing Routes and Query Parameters

JSON Server supports powerful query options to mimic real-world scenarios. For example:

// Filtering users by email
GET /users?email=bob@example.com
// Pagination example
GET /posts?_page=1&_limit=2
// Sorting posts by title
GET /posts?_sort=title&_order=asc

These parameters simulate typical API behaviors and allow front-end developers to build pagination and filtering components early in the dev cycle. You can also define custom routes in a routes.json file:

{
  "/authors/:id/posts": "/posts?authorId=:id"
}

Run your server with custom routes using:

json-server db.json --routes routes.json

This configuration allows you to create realistic nested API structures, closely resembling your production design.

4. Adding Delays, Validation, and Middleware

To simulate backend latency or authentication, you can extend JSON Server with custom middleware. First, add a server.js file:

const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();

server.use(middlewares);

// Simulated delay
server.use((req, res, next) => {
  setTimeout(() => next(), 800);
});

// Simple validation example
server.post('/users', (req, res, next) => {
  if (!req.body.name) return res.status(400).json({ error: 'Name is required' });
  next();
});

server.use(router);
server.listen(4000, () => {
  console.log('Mock API running at http://localhost:4000');
});

This setup demonstrates how to simulate production-like behaviors. Front-end teams can now validate form submissions, handle errors, and test loading indicators realistically.

5. Automation and Integration Tips

JSON Server can be integrated into automated workflows. For example, many developers include it as part of their local development with npm scripts:

"scripts": {
  "mock-api": "json-server --watch db.json --port 4000"
}

Run it alongside your front-end build using tools like concurrently:

npm install concurrently --save-dev
"scripts": {
  "dev": "concurrently \"npm run mock-api\" \"npm start\""
}

This setup starts both the mock API and your React or Vue app together, enabling seamless front-end testing. For CI/CD pipelines, you can start JSON Server before running your automated UI tests using Playwright or Cypress.

Conclusion

JSON Server is an incredibly useful tool for front-end prototyping and testing. It accelerates development workflows by letting developers work independently of backend teams while still maintaining realistic API interactions. With custom routes, validation middleware, and flexible integration, JSON Server can mimic most backend behaviors — making it an essential tool in any front-end developer’s toolkit.

 

Useful links: