Claude
Skills
Sign in
Back

mock-server

Included with Lifetime
$97 forever

Create and manage mock API servers for development and testing.

Backend & APIs

What this skill does


# Mock Server Skill

Create and manage mock API servers for development and testing.

## Instructions

You are a mock API server expert. When invoked:

1. **Create Mock Servers**:
   - Generate mock API endpoints from OpenAPI specs
   - Create custom mock responses
   - Simulate different response scenarios
   - Mock REST and GraphQL APIs
   - Handle various HTTP methods

2. **Configure Behavior**:
   - Set response delays/latency
   - Simulate error conditions
   - Return different responses based on input
   - Implement state management
   - Mock authentication

3. **Advanced Scenarios**:
   - Simulate network failures
   - Random error injection
   - Rate limiting simulation
   - Conditional responses
   - CORS configuration

4. **Integration**:
   - Proxy to real APIs
   - Record and replay requests
   - Generate mock data
   - Integration with testing frameworks

## Usage Examples

```
@mock-server
@mock-server --from-openapi
@mock-server --port 3000
@mock-server --with-delays
@mock-server --graphql
```

## JSON Server (Simple Mock)

### Quick Setup
```bash
# Install
npm install -g json-server

# Create db.json
cat > db.json << EOF
{
  "users": [
    { "id": 1, "name": "John Doe", "email": "[email protected]" },
    { "id": 2, "name": "Jane Smith", "email": "[email protected]" }
  ],
  "posts": [
    { "id": 1, "title": "Hello World", "userId": 1 },
    { "id": 2, "title": "Mock APIs", "userId": 2 }
  ]
}
EOF

# Start server
json-server --watch db.json --port 3000
```

### Available Endpoints (Auto-generated)
```bash
# GET all users
curl http://localhost:3000/users

# GET user by ID
curl http://localhost:3000/users/1

# POST new user
curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Bob", "email": "[email protected]"}'

# PUT update user
curl -X PUT http://localhost:3000/users/1 \
  -H "Content-Type: application/json" \
  -d '{"id": 1, "name": "John Updated", "email": "[email protected]"}'

# PATCH partial update
curl -X PATCH http://localhost:3000/users/1 \
  -H "Content-Type: application/json" \
  -d '{"name": "John Patched"}'

# DELETE user
curl -X DELETE http://localhost:3000/users/1

# Query parameters
curl "http://localhost:3000/users?_page=1&_limit=10"
curl "http://localhost:3000/users?_sort=name&_order=asc"
curl "http://localhost:3000/posts?userId=1"
```

### Custom Routes
```javascript
// routes.json
{
  "/api/*": "/$1",
  "/users/:id/posts": "/posts?userId=:id",
  "/auth/login": "/login"
}

// Start with custom routes
json-server db.json --routes routes.json
```

## Mock Service Worker (MSW)

### Setup
```bash
npm install --save-dev msw
```

### REST API Mocking
```javascript
// src/mocks/handlers.js
import { http, HttpResponse } from 'msw';

export const handlers = [
  // GET users
  http.get('/api/users', () => {
    return HttpResponse.json([
      { id: '1', name: 'John Doe', email: '[email protected]' },
      { id: '2', name: 'Jane Smith', email: '[email protected]' }
    ]);
  }),

  // GET user by ID
  http.get('/api/users/:userId', ({ params }) => {
    const { userId } = params;

    // Simulate not found
    if (userId === '999') {
      return new HttpResponse(null, { status: 404 });
    }

    return HttpResponse.json({
      id: userId,
      name: 'John Doe',
      email: '[email protected]'
    });
  }),

  // POST create user
  http.post('/api/users', async ({ request }) => {
    const data = await request.json();

    // Simulate validation error
    if (!data.email) {
      return HttpResponse.json(
        { error: 'Email is required' },
        { status: 400 }
      );
    }

    return HttpResponse.json(
      {
        id: '123',
        ...data,
        createdAt: new Date().toISOString()
      },
      { status: 201 }
    );
  }),

  // PUT update user
  http.put('/api/users/:userId', async ({ params, request }) => {
    const { userId } = params;
    const data = await request.json();

    return HttpResponse.json({
      id: userId,
      ...data,
      updatedAt: new Date().toISOString()
    });
  }),

  // DELETE user
  http.delete('/api/users/:userId', ({ params }) => {
    return new HttpResponse(null, { status: 204 });
  }),

  // Simulate delay
  http.get('/api/slow-endpoint', async () => {
    await delay(2000); // 2 second delay
    return HttpResponse.json({ message: 'Slow response' });
  }),

  // Simulate random errors
  http.get('/api/unreliable', () => {
    if (Math.random() > 0.5) {
      return new HttpResponse(null, { status: 500 });
    }
    return HttpResponse.json({ status: 'ok' });
  }),

  // Authentication
  http.post('/api/auth/login', async ({ request }) => {
    const { email, password } = await request.json();

    if (email === '[email protected]' && password === 'password') {
      return HttpResponse.json({
        accessToken: 'mock-jwt-token',
        refreshToken: 'mock-refresh-token',
        expiresIn: 3600
      });
    }

    return HttpResponse.json(
      { error: 'Invalid credentials' },
      { status: 401 }
    );
  })
];

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
```

### Browser Setup
```javascript
// src/mocks/browser.js
import { setupWorker } from 'msw/browser';
import { handlers } from './handlers';

export const worker = setupWorker(...handlers);

// src/index.js
if (process.env.NODE_ENV === 'development') {
  const { worker } = await import('./mocks/browser');
  await worker.start();
}
```

### Node.js Setup (Testing)
```javascript
// src/mocks/server.js
import { setupServer } from 'msw/node';
import { handlers } from './handlers';

export const server = setupServer(...handlers);

// src/tests/setup.js
import { server } from '../mocks/server';

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
```

## Prism (OpenAPI-based)

### From OpenAPI Spec
```bash
# Install
npm install -g @stoplight/prism-cli

# Start mock server from OpenAPI spec
prism mock openapi.yaml

# Specify port
prism mock openapi.yaml --port 4010

# Enable validation
prism mock openapi.yaml --errors

# Dynamic responses based on examples
prism mock openapi.yaml --dynamic
```

### Example OpenAPI for Prism
```yaml
openapi: 3.0.0
info:
  title: Mock API
  version: 1.0.0

paths:
  /api/users:
    get:
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'
              examples:
                success:
                  value:
                    - id: "1"
                      name: "John Doe"
                      email: "[email protected]"

  /api/users/{userId}:
    get:
      parameters:
        - name: userId
          in: path
          required: true
          schema:
            type: string
      responses:
        '200':
          description: Success
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
              examples:
                user:
                  value:
                    id: "1"
                    name: "John Doe"
                    email: "[email protected]"
        '404':
          description: Not found
          content:
            application/json:
              examples:
                notFound:
                  value:
                    error: "User not found"

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
        email:
          type: string
```

## Express Mock Server

### Custom Implementation
```javascript
const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors());
app.use(express.json());

// Middleware for random delays
app.use((req, res, next) => {
  const delay = Math.random() * 1000; // 0-1 second
  setTimeout(next, d

Related in Backend & APIs