Mock Server

A production-ready mock server with API recording and replay capabilities.

Quick Start

# Start mock server
FakeDataDSL::MockServer.start(
  schema_dir: "schemas/",
  port: 3000
)

Features

  • 🎲 Schema-based generation - Generate data from your DSL schemas
  • 📼 Recording mode - Record real API responses for replay
  • ⏱️ Behavior simulation - Simulate latency and failures
  • 🔒 Rate limiting - Protect against overuse
  • 🌐 CORS support - Ready for frontend development

Configuration

FakeDataDSL::MockServer.start(
  schema_dir: "schemas/",
  port: 3000,
  recording: true,                # Enable recording
  recordings_dir: "recordings/",  # Where to save recordings
  cors: true,                     # Enable CORS
  rate_limit: 100,                # Requests per minute (0 = unlimited)
  default_mode: :random           # Default generation mode
)

API Endpoints

Schema Endpoints

Method Path Description
GET /api/schemas List all schemas
GET /api/:schema Generate single record
GET /api/:schema/batch Generate batch
GET /api/:schema/stream Stream NDJSON
POST /api/:schema Generate with overrides
GET /api/:schema/schema Get schema info

Recording Endpoints

Method Path Description
POST /api/recordings/:name Save a recording
GET /api/recordings/:name Replay a recording

Generation Parameters

All generation endpoints accept:

  • seed - Random seed for deterministic output
  • mode - Generation mode: random, edge, invalid, hostile, mixed
  • count - Number of records (batch/stream only)

Examples

# Generate with seed
curl "http://localhost:3000/api/user?seed=42"

# Generate edge cases
curl "http://localhost:3000/api/user?mode=edge"

# Generate batch
curl "http://localhost:3000/api/user/batch?count=100&seed=42"

Recording & Replay

Save Recording

# Record a response manually
curl -X POST http://localhost:3000/api/recordings/users_list \
  -H "Content-Type: application/json" \
  -d '{
    "data": [
      {"id": 1, "name": "Real User 1"},
      {"id": 2, "name": "Real User 2"}
    ],
    "content_type": "application/json"
  }'

Replay Recording

# Get the recorded response
curl http://localhost:3000/api/recordings/users_list

Automatic Recording

With recording: true, all generation responses are automatically saved:

FakeDataDSL::MockServer.start(
  schema_dir: "schemas/",
  recording: true,
  recordings_dir: "recordings/"
)

Recordings are saved as {schema_name}_{timestamp}.json.

Behavior Simulation

Schemas with behaviors are honored by the mock server:

User:
  @latency 50..200ms
  @failure 5%

  id: uuid
  name: name

When this schema is requested:

  • Responses will be delayed 50-200ms
  • 5% of requests will return 500 error

Rate Limiting

FakeDataDSL::MockServer.start(
  schema_dir: "schemas/",
  rate_limit: 100  # 100 requests per minute per IP
)

When rate limited:

{
  "error": "Rate limit exceeded"
}

HTTP Status: 429

CORS Support

CORS is enabled by default:

# Default headers
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400

Disable CORS:

FakeDataDSL::MockServer.start(
  schema_dir: "schemas/",
  cors: false
)

Async Mode

Start server in background:

server = FakeDataDSL::MockServer.new(schema_dir: "schemas/", port: 3000)

# Start in background thread
server.start_async

# Do other work...

# Stop when done
server.stop

Use Cases

Frontend Development

# Start mock server for frontend dev
FakeDataDSL::MockServer.start(
  schema_dir: "schemas/",
  port: 3000,
  cors: true,
  default_mode: :random
)

Integration Testing

# In test setup
before(:all) do
  @server = FakeDataDSL::MockServer.new(
    schema_dir: "spec/fixtures/schemas/",
    port: 3001
  )
  @thread = @server.start_async
end

after(:all) do
  @server.stop
end

it "fetches users from API" do
  response = HTTParty.get("http://localhost:3001/api/user?seed=42")
  expect(response["id"]).to be_present
end

Contract Testing

# Record real API responses
FakeDataDSL::MockServer.start(
  schema_dir: "schemas/",
  recording: true,
  recordings_dir: "contracts/"
)

# Later, replay for testing
curl http://localhost:3000/api/recordings/user_response

File Structure

When recording is enabled:

recordings/
├── User_1706123456.json
├── User_1706123457.json
├── Order_1706123458.json
└── custom_response.json

Recording format:

{
  "data": { "id": "...", "name": "..." },
  "recorded_at": "2026-01-24T10:30:00Z",
  "schema": "User",
  "content_type": "application/json"
}

Comparison: MockServer vs APIServer

Feature MockServer APIServer
Purpose Development/Testing Production
Recording ✅ Yes ❌ No
Authentication ❌ No ✅ Yes
Metrics ❌ No ✅ Yes
Rate Limiting ✅ Basic ✅ Advanced
Caching ❌ No ✅ Yes
Rack Support ❌ No ✅ Yes

Use MockServer for:

  • Frontend development
  • Integration testing
  • Contract testing
  • API prototyping

Use APIServer for:

  • Production deployment
  • Public APIs
  • Services requiring auth
  • High-traffic scenarios