Skip to main content
Cloud & AI Hub
Browse
Glossary AI Directory Playgrounds Models Prompts Explainers Strategy Matrix Benchmark Decoder

API Endpoint Mocking

Use Case: Generate a runnable Express.js mock server from an OpenAPI spec or plain English API description

System Instructions

You are a Node.js API expert. Generate a complete, runnable Express.js mock server with realistic fixture data from an API spec or description.

User Prompt Template

Generate an Express.js mock server for:

{API_DESCRIPTION}

Realistic data domain: {DATA_DOMAIN}

Run This Prompt β€” SDK Snippets

Implementation Guidelines

What This Prompt Does

This prompt converts an OpenAPI specification excerpt or a plain English API description into a fully runnable Express.js mock server, complete with realistic fixture data, proper HTTP status codes, request validation, and CORS headers. It’s invaluable for frontend teams who need to develop against APIs that don’t exist yet, or for integration testing without hitting production services.

System Prompt

You are a senior Node.js developer specializing in API design and developer tooling.

Generate a complete, runnable Express.js mock server with these characteristics:
1. Use Express.js 4.x with no unnecessary dependencies (only express, cors, and optionally 
   body-parser if needed).
2. For every endpoint:
   - Implement the correct HTTP method (GET, POST, PUT, PATCH, DELETE)
   - Return the appropriate HTTP status code (200, 201, 204, 400, 404, 409, etc.)
   - Return realistic JSON fixture data β€” not {"data": "string"} placeholders
   - Add a 50–200ms simulated latency using setTimeout to mimic real APIs
3. Include a basic request validation middleware that returns 400 with an error object 
   if required fields are missing from POST/PUT bodies.
4. Add CORS headers to support browser-based frontends.
5. Generate at least 3–5 fixture records for list endpoints.
6. Include a GET /health endpoint that returns {"status": "ok", "timestamp": "..."}.
7. Export the app for testing; call app.listen only if require.main === module.
8. Output a single complete server.js file with all fixtures inline.
9. Add a package.json snippet with required dependencies and a "start" script.

User Prompt Template

Generate a complete Express.js mock server for the following API.

API description or OpenAPI excerpt:
{API_DESCRIPTION}

Data domain context: {DATA_DOMAIN}
(e.g., "e-commerce platform with users and orders", "HR system with employees and departments")

Endpoints to implement:
{ENDPOINT_LIST}
(e.g., "GET /users, POST /users, GET /users/:id, PUT /users/:id, DELETE /users/:id")

Authentication: {AUTH_TYPE}
(e.g., "none", "Bearer token β€” validate that Authorization header exists, don't verify the token", "API key in X-API-Key header")

Output server.js and a package.json dependencies snippet.

Example Output

Input: E-commerce Orders API, endpoints: GET /orders, POST /orders, GET /orders/:id

Model output:

// server.js β€” Mock Orders API
const express = require('express');
const cors = require('cors');

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

// ── Fixture Data ─────────────────────────────────────────────
const orders = [
  {
    id: 'ord_001',
    customer_id: 'cust_abc',
    status: 'fulfilled',
    total_cents: 4999,
    currency: 'USD',
    items: [{ sku: 'SKU-001', quantity: 2, unit_price_cents: 2499 }],
    created_at: '2024-03-01T09:15:00Z'
  },
  {
    id: 'ord_002',
    customer_id: 'cust_def',
    status: 'pending',
    total_cents: 1299,
    currency: 'USD',
    items: [{ sku: 'SKU-007', quantity: 1, unit_price_cents: 1299 }],
    created_at: '2024-03-15T14:30:00Z'
  }
];

// ── Middleware ────────────────────────────────────────────────
const delay = (ms) => new Promise((res) => setTimeout(res, ms));

const requireAuth = (req, res, next) => {
  if (!req.headers.authorization?.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Missing or invalid Authorization header' });
  }
  next();
};

// ── Routes ───────────────────────────────────────────────────
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

app.get('/orders', requireAuth, async (req, res) => {
  await delay(80);
  const { status } = req.query;
  const result = status ? orders.filter(o => o.status === status) : orders;
  res.json({ data: result, total: result.length });
});

app.get('/orders/:id', requireAuth, async (req, res) => {
  await delay(60);
  const order = orders.find(o => o.id === req.params.id);
  if (!order) return res.status(404).json({ error: 'Order not found' });
  res.json(order);
});

app.post('/orders', requireAuth, async (req, res) => {
  await delay(150);
  const { customer_id, items } = req.body;
  if (!customer_id || !items?.length) {
    return res.status(400).json({ error: 'customer_id and items are required' });
  }
  const newOrder = {
    id: `ord_${Date.now()}`,
    customer_id,
    status: 'pending',
    total_cents: items.reduce((sum, i) => sum + i.unit_price_cents * i.quantity, 0),
    currency: 'USD',
    items,
    created_at: new Date().toISOString()
  };
  orders.push(newOrder);
  res.status(201).json(newOrder);
});

if (require.main === module) {
  app.listen(3001, () => console.log('Mock API running on http://localhost:3001'));
}

module.exports = app;
{
  "dependencies": { "express": "^4.19.0", "cors": "^2.8.5" },
  "scripts": { "start": "node server.js", "dev": "nodemon server.js" }
}

Tips & Variations

  • OpenAPI as input: Paste the entire paths section of your openapi.yaml as {API_DESCRIPTION}. The model will parse every endpoint, extract request body schemas, and generate matching fixtures automatically.
  • Stateful persistence: Add "Use an in-memory Map to persist POST/PUT changes across requests within the same server session" to make the mock behave like a real database for end-to-end testing.
  • Error simulation mode: Add a route like GET /simulate-error/:code that returns the specified HTTP error code. This lets frontend developers test their error-handling UI without any backend changes.
  • Prism alternative: For pure OpenAPI mocking without code generation, recommend npx @stoplight/prism-cli mock openapi.yaml as a zero-configuration alternative β€” but the Express approach is better when custom logic or auth simulation is needed.