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

@vidhyasagarthakur/mockapi-cli

v1.0.1

Published

A CLI tool that generates a local mock server from an API contract JSON file

Readme

MockAPI CLI

A powerful CLI tool that generates a local mock server from an API contract (JSON/YAML). Perfect for frontend development when the backend isn't ready yet.

Installation

npm install -g @vidhyasagarthakur/mockapi-cli

Quick Start

mockapi init                              # Create sample contract
mockapi start -c api-contract.json        # Start mock server

Commands

mockapi start

mockapi start -c <contract> [options]

| Option | Description | |--------|-------------| | -c, --contract <path> | Contract file (JSON/YAML) required | | -p, --port <number> | Port (default: 3000) | | -d, --delay <ms> | Response delay | | -w, --watch | Auto-reload on file changes | | -s, --stateful | Persist CRUD operations in memory | | -v, --validate | Validate request bodies | | --no-faker | Disable faker pattern processing | | --no-dashboard | Disable web dashboard | | --proxy <url> | Forward to real backend | | --proxy-mode <mode> | fallback, mock-first, proxy-only | | --response-mode <mode> | condition, sequential, random |

mockapi init

mockapi init [-o filename] [--yaml]

mockapi import

mockapi import <openapi-spec> [-o filename] [--yaml] [--preview]

mockapi record

Record real API responses and generate a contract:

mockapi record -t https://api.example.com [-p port] [-o output.json]

| Option | Description | |--------|-------------| | -t, --target <url> | Target API URL to record required | | -p, --port <number> | Proxy port (default: 3000) | | -o, --output <file> | Output filename (default: recorded-contract.json) | | -n, --name <name> | API name in contract | | --yaml | Generate YAML format |

mockapi test

Run scenario tests against your mock server:

mockapi test -s scenarios.json [-b http://localhost:3000]

| Option | Description | |--------|-------------| | -s, --scenarios <path> | Scenarios file required | | -b, --base-url <url> | Server URL (default: http://localhost:3000) | | -v, --verbose | Detailed output | | --stop-on-failure | Stop on first failure |

Features

YAML Support

Contracts can be JSON or YAML:

name: My API
basePath: /api/v1
endpoints:
  - method: GET
    path: /users
    response:
      status: 200
      body:
        users: []

Faker.js Integration

Generate realistic random data:

{
  "body": {
    "id": "faker:number.int({min:1,max:1000})",
    "name": "faker:person.fullName",
    "email": "faker:internet.email",
    "avatar": "faker:image.avatar"
  }
}

| Pattern | Example Output | |---------|---------------| | faker:person.fullName | "John Doe" | | faker:internet.email | "[email protected]" | | faker:number.int({min:1,max:100}) | 42 | | faker:date.recent | "2026-03-08T..." | | faker:lorem.paragraph | "Lorem ipsum..." | | faker:company.name | "Acme Corp" | | faker:location.city | "San Francisco" | | faker:helpers.arrayElement(["a","b"]) | "a" or "b" |

Multiple Responses

Define conditional responses per endpoint:

{
  "method": "GET",
  "path": "/users",
  "responses": [
    {
      "status": 200,
      "body": { "users": [...], "total": 10 },
      "when": { "query": { "status": "active" } }
    },
    {
      "status": 200,
      "body": { "users": [], "total": 0 },
      "when": { "query": { "status": "inactive" } }
    },
    {
      "status": 200,
      "body": { "users": [...] }
    }
  ]
}

Selection methods:

  • ?_response=0 - Force specific response by index
  • X-Mock-Response: 1 - Via header
  • --response-mode sequential - Rotate through responses
  • --response-mode random - Random selection

Auth Simulation

Global auth in contract:

{
  "auth": {
    "type": "bearer",
    "tokens": ["dev-token-123", "test-token"]
  },
  "endpoints": [
    {
      "method": "GET",
      "path": "/users",
      "auth": false
    },
    {
      "method": "POST",
      "path": "/users"
    }
  ]
}

Auth types:

// Bearer token
{ "type": "bearer", "tokens": ["token1", "token2"] }

// API Key (header)
{ "type": "apiKey", "header": "X-API-Key", "keys": ["key1"] }

// API Key (query param)
{ "type": "apiKey", "query": "api_key", "keys": ["key1"] }

// Basic auth
{ "type": "basic", "users": [{ "username": "admin", "password": "secret" }] }

Endpoints inherit global auth. Use "auth": false to make public.

Stateful Mode

Enable with -s or --stateful:

# POST creates new records
curl -X POST http://localhost:3000/api/v1/users \
  -d '{"name":"John"}'

# GET returns updated data
curl http://localhost:3000/api/v1/users

# DELETE removes records
curl -X DELETE http://localhost:3000/api/v1/users/1

Proxy Mode

Forward requests to real backend:

# Try backend first, fall back to mock
mockapi start -c contract.json --proxy https://api.example.com

# Use mock for defined endpoints, proxy others
mockapi start -c contract.json --proxy https://api.example.com --proxy-mode mock-first

# Forward everything (no mocking)
mockapi start -c contract.json --proxy https://api.example.com --proxy-mode proxy-only

Request Validation

Enable with -v or --validate:

{
  "method": "POST",
  "path": "/users",
  "requestBody": {
    "name": { "type": "string", "required": true },
    "email": { "type": "string", "required": true },
    "age": "number"
  }
}

Returns 400 with details on validation failure.

OpenAPI Import

mockapi import openapi.yaml -o contract.json
mockapi import swagger.json --preview

Converts OpenAPI 3.x / Swagger 2.x specs to MockAPI format with faker patterns.

Web Dashboard

Access the built-in dashboard at http://localhost:3000/_mockapi when the server is running:

  • View all registered endpoints
  • Monitor request history in real-time
  • Test endpoints directly from browser
  • View and edit contract (live reload)

Disable with --no-dashboard.

Recording Mode

Record real API responses to generate contracts:

# Start recording proxy
mockapi record -t https://api.example.com -p 3001

# Make requests through the proxy
curl http://localhost:3001/api/users
curl -X POST http://localhost:3001/api/users -d '{"name":"John"}'

# Press Ctrl+C to save contract

The generated contract includes:

  • All recorded endpoints with methods and paths
  • Response bodies and status codes
  • Inferred query/path parameters
  • Multiple response variants per endpoint

WebSocket Mocking

Mock WebSocket connections in your contract:

{
  "websockets": [
    {
      "path": "/ws/chat",
      "onConnect": {
        "type": "welcome",
        "message": "Connected to chat"
      },
      "onMessage": [
        {
          "when": { "type": "ping" },
          "respond": { "type": "pong" }
        },
        {
          "when": { "type": "subscribe" },
          "respond": { "type": "subscribed", "channel": "$data.channel" }
        }
      ],
      "sequence": [
        { "delay": 5000, "emit": { "type": "heartbeat" } },
        { "delay": 10000, "emit": { "type": "update", "data": "faker:lorem.sentence" }, "repeat": 30000 }
      ]
    }
  ]
}

Features:

  • onConnect: Message sent when client connects
  • onMessage: Handlers for incoming messages with conditions
  • sequence: Scheduled messages with delays and repeats
  • Template variables: $data.field references incoming message fields
  • Faker patterns work in WebSocket responses

Scenario Testing

Define and run test scenarios:

{
  "name": "User CRUD workflow",
  "baseUrl": "http://localhost:3000",
  "variables": {
    "authToken": "Bearer test-token"
  },
  "steps": [
    {
      "name": "Create user",
      "request": {
        "method": "POST",
        "path": "/api/v1/users",
        "headers": { "Authorization": "$authToken" },
        "body": { "name": "John", "email": "[email protected]" }
      },
      "expect": {
        "status": 201,
        "body": {
          "id": { "$exists": true },
          "name": "John"
        }
      },
      "extract": {
        "userId": "$.id"
      }
    },
    {
      "name": "Get created user",
      "request": {
        "method": "GET",
        "path": "/api/v1/users/$userId"
      },
      "expect": {
        "status": 200,
        "body": { "name": "John" }
      }
    }
  ]
}

Assertion matchers: | Matcher | Example | Description | |---------|---------|-------------| | $exists | { "$exists": true } | Field exists | | $type | { "$type": "string" } | Type check | | $contains | { "$contains": "foo" } | String contains | | $regex | { "$regex": "^[A-Z]" } | Regex match | | $gt/$gte | { "$gt": 0 } | Greater than | | $lt/$lte | { "$lt": 100 } | Less than | | $length | { "$length": 5 } | Array/string length |

Variable extraction:

  • Use extract to save response values for later steps
  • Reference with $variableName in subsequent requests

Contract Schema

{
  "name": "API Name",
  "basePath": "/api/v1",
  "auth": { "type": "bearer", "tokens": ["..."] },
  "endpoints": [
    {
      "method": "GET|POST|PUT|PATCH|DELETE",
      "path": "/resource/:id",
      "description": "Description",
      "auth": false,
      "queryParams": [{ "name": "page", "type": "number" }],
      "pathParams": [{ "name": "id", "type": "number", "required": true }],
      "requestBody": { "field": { "type": "string", "required": true } },
      "response": { "status": 200, "body": {...}, "headers": {...} },
      "responses": [
        { "status": 200, "body": {...}, "when": { "query": {...} } }
      ]
    }
  ]
}

License

MIT