npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

json-api-mocker

v3.1.0

Published

A mock server based on JSON configuration

Readme

JSON API Mocker

A lightweight and flexible mock server that uses JSON configuration to quickly create RESTful APIs.

✨ Features

  • 🚀 Quick setup with JSON configuration
  • 🔄 Support for GET, POST, PUT, DELETE methods
  • 🖥️ Visual admin console, no JSON editing required
  • 📝 Automatic data persistence
  • 🔍 Built-in pagination support
  • 🛠 Customizable response schemas
  • 🎭 Integration with Mock.js for powerful data mocking
  • 📤 File upload support
  • 🔌 Real-time communication with WebSocket
  • 💡 TypeScript support

📦 Installation

# Using npm
npm install json-api-mocker

# Using yarn
yarn add json-api-mocker

# Using pnpm
pnpm add json-api-mocker

🚀 Quick Start

1. Create Configuration File

Create a data.json file in your project root:

{
  "server": {
    "port": 8080,
    "baseProxy": "/api"
  },
  "routes": [
    {
      "path": "/users",
      "methods": {
        "get": {
          "type": "array",
          "pagination": {
            "enabled": true,
            "pageSize": 10,
            "totalCount": 100
          },
          "response": [
            {
              "id": 1,
              "name": "John",
              "age": 30,
              "city": "New York"
            }
          ]
        }
      }
    },
    {
      "path": "/upload/avatar",
      "methods": {
        "post": {
          "type": "object",
          "mock": {
            "enabled": true,
            "template": {
              "success": true,
              "message": "Upload successful",
              "data": {
                "url": "@image('200x200')",
                "filename": "@string(10).jpg",
                "size": "@integer(1000, 1000000)"
              }
            }
          }
        }
      }
    }
  ]
}

2. Start the Server

There are several ways to start the mock server:

# Method 1: Using npx (Recommended)
npx json-api-mocker

# Method 2: Using npx with a custom config file
npx json-api-mocker ./custom-config.json

# Method 3: If installed globally
json-api-mocker

# Method 4: If installed as a project dependency
# Add this to your package.json scripts:
{
  "scripts": {
    "mock": "json-api-mocker"
  }
}
# Then run:
npm run mock

Now your mock server is running at http://localhost:8080!

You'll see output like this:

Mock 服务器已启动:
- HTTP 地址: http://localhost:8080
- 管理后台: http://localhost:8080/admin
- 基础路径: /api
可用的接口:
  GET http://localhost:8080/api/users
  POST http://localhost:8080/api/users
  POST http://localhost:8080/api/upload/avatar

🖥️ Visual Admin Console

Don't want to write JSON config by hand? After starting the server, open the admin console in your browser:

http://localhost:8080/admin

The admin console provides the following features:

  • 📝 Visual Editor: Configure routes, methods, and Mock fields via forms — no JSON knowledge required
  • 🎨 Field Builder: Select field types (random name, age range, email, city, etc.) from a dropdown to auto-generate Mock.js templates
  • 💻 JSON Source Editor: Switch to source mode to edit JSON directly, with formatting and syntax checking
  • 👀 API Preview: View all available APIs; GET endpoints can be tested with one click
  • 💾 One-click Save: Save changes and they're automatically written back to data.json

💡 After saving, static data changes take effect immediately; newly added routes require a server restart.

📖 Configuration Guide

For detailed configuration options, please refer to CONFIG.md.

Server Configuration

The server section configures basic server settings:

{
  "server": {
    "port": 8080,      // Server port number
    "baseProxy": "/api" // Base path for all routes
  }
}

Route Configuration

Each route can support multiple HTTP methods:

{
  "path": "/users",    // Route path
  "methods": {
    "get": {
      "type": "array", // Response type: "array" or "object"
      "pagination": {  // Optional pagination settings
        "enabled": true,
        "pageSize": 10,
        "totalCount": 100
      },
      "response": []   // Response data
    },
    "post": {
      "requestSchema": {  // Request body validation schema
        "name": "string",
        "age": "number"
      },
      "response": {
        "success": true
      }
    }
  }
}

File Upload Support

You can configure file upload endpoints in your data.json:

{
  "path": "/upload/avatar",
  "methods": {
    "post": {
      "type": "object",
      "mock": {
        "enabled": true,
        "template": {
          "success": true,
          "message": "Upload successful",
          "data": {
            "url": "@image('200x200')",
            "filename": "@string(10).jpg",
            "size": "@integer(1000, 1000000)"
          }
        }
      }
    }
  }
}

Example Usage:

# Upload single file
curl -X POST http://localhost:8080/api/upload/avatar \
  -H "Content-Type: multipart/form-data" \
  -F "avatar=@/path/to/your/image.jpg"

# Upload multiple files
curl -X POST http://localhost:8080/api/upload/images \
  -H "Content-Type: multipart/form-data" \
  -F "images=@/path/to/image1.jpg" \
  -F "images=@/path/to/image2.jpg"

For detailed configuration options, please refer to CONFIG.md.

🎯 API Examples

Basic CRUD Operations

Get Users List

curl http://localhost:8080/api/users

Get Single User

curl http://localhost:8080/api/users/1

Create User

curl -X POST http://localhost:8080/api/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice","age":25,"city":"Boston"}'

Update User

curl -X PUT http://localhost:8080/api/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice","age":26,"city":"Boston"}'

Delete User

curl -X DELETE http://localhost:8080/api/users/1

Advanced Usage

Pagination

# Get page 2 with 10 items per page
curl http://localhost:8080/api/users?page=2&pageSize=10

Custom Response Headers

The server automatically adds these headers:

  • X-Total-Count: Total number of items (for paginated responses)

🔧 Advanced Configuration

Dynamic Routes

You can use URL parameters in routes:

{
  "path": "/users/:id/posts",
  "methods": {
    "get": {
      "type": "array",
      "response": []
    }
  }
}

Request Validation

Add schema validation for POST/PUT requests:

{
  "requestSchema": {
    "name": "string",
    "age": "number",
    "email": "string"
  }
}

WebSocket Support

You can configure WebSocket endpoints in your data.json:

{
  "websocket": {
    "enabled": true,
    "path": "/ws",
    "events": {
      "realtime-data": {
        "mock": {
          "enabled": true,
          "interval": 5000,  // Send data every 5 seconds
          "template": {
            "timestamp": "@datetime",
            "value|1-100": 1,
            "status|1": ["normal", "warning", "error"]
          }
        }
      },
      "user-status": {
        "mock": {
          "enabled": true,
          "template": {
            "userId|+1": 1,
            "status|1": ["online", "offline", "away"],
            "lastActive": "@datetime"
          }
        }
      }
    }
  }
}

Client Usage Example:

// Connect to WebSocket server
const ws = new WebSocket('ws://localhost:8080/ws');

// Handle connection open
ws.onopen = () => {
  console.log('Connected to WebSocket server');
  
  // Request real-time data
  ws.send(JSON.stringify({
    event: 'realtime-data'
  }));
};

// Handle incoming messages
ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
  // {
  //   event: 'realtime-data',
  //   data: {
  //     timestamp: '2024-01-01 12:00:00',
  //     value: 75,
  //     status: 'normal'
  //   }
  // }
};

// Handle errors
ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

// Handle connection close
ws.onclose = () => {
  console.log('Disconnected from WebSocket server');
};

Features:

  • Event-based communication
  • Automatic data sending at specified intervals
  • Mock.js template support for dynamic data
  • Multiple event handlers

🤝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

MIT © [Xiong Haiyin]

🙏 Acknowledgments

  • Express.js for the excellent web framework
  • All our contributors and users