JSON Server: A Simple Way to Create Mock APIs

JSON Server is a lightweight and easy-to-use tool that allows developers to create mock REST APIs based on JSON files. It’s particularly useful for prototyping, testing, or developing front-end applications when a backend API is not yet available.

Features of JSON Server

  1. Quick Setup: Generate a full API with minimal configuration.
  2. CRUD Support: Supports Create, Read, Update, and Delete operations out of the box.
  3. Custom Routes: Allows you to define custom API routes and behavior.
  4. Static File Serving: Can also serve static content alongside the API.
  5. Middleware Support: Enables adding custom middleware for advanced use cases.

Installing JSON Server

JSON Server is a Node.js package. To install it, use the following command:

npm install -g json-server

Setting Up JSON Server

  • Create a JSON File: Create a db.json file to serve as the database. Example:
{
  "posts": [
    { "id": 1, "title": "JSON Server", "author": "Jane Doe" },
    { "id": 2, "title": "API Mocking", "author": "John Smith" }
  ],
  "comments": [
    { "id": 1, "body": "Great post!", "postId": 1 }
  ]
}
  • Start the Server: Run the following command to start the server:
json-server --watch db.json
  • Access the API:
    • Base URL: http://localhost:3000
    • Example Endpoints:
      • GET /posts – Retrieve all posts.
      • GET /posts/1 – Retrieve the post with id 1.
      • POST /posts – Add a new post.
      • PUT /posts/1 – Update the post with id 1.
      • DELETE /posts/1 – Delete the post with id 1.

Advanced Configuration

Custom Routes

You can define custom routes using a routes.json file:

{
  "/api/posts": "/posts",
  "/api/comments": "/comments"
}

Run the server with:

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

Middleware

To customize behavior, you can create 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);

// Add custom middleware
server.use((req, res, next) => {
  console.log(`Received ${req.method} request for ${req.url}`);
  next();
});

server.use(router);
server.listen(3000, () => {
  console.log('JSON Server is running');
});

Use Cases

  1. Front-End Prototyping: Quickly set up a working backend to test and develop your front-end.
  2. Mocking APIs: Simulate API responses for integration testing.
  3. Learning and Training: Useful for beginners learning REST API concepts.

Benefits of JSON Server

  • Saves time during development.
  • Eliminates the need for a full-fledged backend during early stages.
  • Encourages rapid prototyping.

For more details and examples, visit the official JSON Server GitHub repository.

For additional tutorials on modern web development tools, check out The Coding College.

Leave a Comment