πŸ“ Tutorials
Β· 5 min read

Build an AI API Mock Generator From OpenAPI Specs


Frontend developers waste hours waiting for backend APIs. What if you could describe an API and have AI generate a working mock server with realistic data?

In this tutorial, you’ll build a mock API generator that reads OpenAPI specs and creates a running server with AI-generated realistic responses. No API keys, no cloud calls, everything runs locally.

How It Works

  1. You provide an OpenAPI spec (or describe your API)
  2. AI generates realistic mock responses for each endpoint
  3. A local server runs with those responses
  4. Your frontend can call the API immediately

Prerequisites

  • Ollama installed
  • Node.js 18+
  • An OpenAPI spec file (or knowledge of your API)

Step 1: Pull the model

ollama pull qwen2.5-coder:7b

Step 2: Create the mock generator

// mock-generator.js
const fs = require('fs');
const http = require('http');
const { execSync } = require('child_process');

const OLLAMA_URL = 'http://localhost:11434/api/generate';
const MODEL = 'qwen2.5-coder:7b';

async function generateMockResponse(endpoint, method, schema) {
    const prompt = `Generate a realistic JSON mock response for this API endpoint.

Endpoint: ${method} ${endpoint}
Schema: ${JSON.stringify(schema, null, 2)}

Requirements:
1. Return realistic data, not placeholder text
2. Use proper data types (strings, numbers, booleans, arrays)
3. Include 2-3 items in arrays
4. Use realistic names, emails, dates
5. Output ONLY valid JSON, no explanations

Response:`;

    const payload = JSON.stringify({
        model: MODEL,
        prompt: prompt,
        stream: false,
        options: { temperature: 0.7, num_predict: 500 }
    });

    const response = await fetch(OLLAMA_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: payload
    });

    const data = await response.json();
    let mockData = data.response.trim();

    // Clean up response
    if (mockData.startsWith('```json')) {
        mockData = mockData.slice(7);
    }
    if (mockData.endsWith('```')) {
        mockData = mockData.slice(0, -3);
    }

    return JSON.parse(mockData.trim());
}

function parseOpenAPI(spec) {
    const endpoints = [];
    const paths = spec.paths || {};

    for (const [path, methods] of Object.entries(paths)) {
        for (const [method, details] of Object.entries(methods)) {
            if (['get', 'post', 'put', 'delete'].includes(method)) {
                endpoints.push({
                    path: path.replace(/{[^}]+}/g, ':id'),
                    method: method.toUpperCase(),
                    summary: details.summary || '',
                    responses: details.responses || {}
                });
            }
        }
    }

    return endpoints;
}

async function createMockServer(specFile) {
    const spec = JSON.parse(fs.readFileSync(specFile, 'utf8'));
    const endpoints = parseOpenAPI(spec);

    console.log(`Found ${endpoints.length} endpoints`);

    const mocks = {};
    for (const endpoint of endpoints) {
        console.log(`Generating mock for ${endpoint.method} ${endpoint.path}...`);
        mocks[endpoint.path] = {
            method: endpoint.method,
            response: await generateMockResponse(
                endpoint.path,
                endpoint.method,
                endpoint.responses
            )
        };
    }

    // Create server
    const server = http.createServer((req, res) => {
        const url = new URL(req.url, `http://${req.headers.host}`);
        const path = url.pathname.replace(/\/[^/]+\/v1/, '') || '/';

        const mock = mocks[path];
        if (mock && mock.method === req.method) {
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify(mock.response));
        } else {
            res.writeHead(404, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ error: 'Not found' }));
        }
    });

    server.listen(3001, () => {
        console.log('Mock API running on http://localhost:3001');
        console.log('Endpoints:');
        for (const [path, mock] of Object.entries(mocks)) {
            console.log(`  ${mock.method} ${path}`);
        }
    });
}

// Run if called directly
if (require.main === module) {
    const specFile = process.argv[2] || 'openapi.json';
    createMockServer(specFile);
}

module.exports = { generateMockResponse, parseOpenAPI };

Step 3: Create a sample OpenAPI spec

{
  "openapi": "3.0.0",
  "info": { "title": "User API", "version": "1.0.0" },
  "paths": {
    "/users": {
      "get": {
        "summary": "List all users",
        "responses": {
          "200": {
            "description": "A list of users",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": { "$ref": "#/components/schemas/User" }
                }
              }
            }
          }
        }
      },
      "post": {
        "summary": "Create a user",
        "responses": {
          "201": { "description": "User created" }
        }
      }
    },
    "/users/:id": {
      "get": {
        "summary": "Get a user by ID",
        "responses": {
          "200": { "description": "A user" }
        }
      }
    }
  }
}

Step 4: Run it

node mock-generator.js openapi.json

Under the Hood

The generator reads your OpenAPI spec, identifies each endpoint, and uses AI to generate realistic mock responses. It then creates a local server that serves those responses.

The AI understands the schema context and generates appropriate data:

  • User endpoints get realistic names, emails, and dates
  • Product endpoints get realistic prices and descriptions
  • List endpoints return arrays with multiple items
  • Nested objects get proper relationships

Real-World Use Cases

Frontend development without backend. Your backend team is two weeks behind. Use the mock generator to start frontend development immediately. The realistic data makes testing meaningful.

Integration testing. Run your frontend tests against mock APIs instead of a real backend. Faster, more reliable, and no database setup required.

API contract validation. Generate mocks from your OpenAPI spec to verify that the spec is complete and correct before backend implementation begins.

Demo environments. Create realistic demo APIs for client presentations without building actual backends.

Prototyping. Quickly prototype new features with realistic data before committing to backend implementation.

Tips for Better Mocks

  1. Use detailed schemas. The more detailed your OpenAPI spec, the better the mock data.
  2. Include examples. Adding example values to your spec helps the AI understand your data patterns.
  3. Define relationships. Use $ref to show how entities relate, and the AI will generate consistent data.
  4. Test edge cases. Add error responses to your spec and the mock will generate realistic error data.

Variations

  • Proxy mode: Forward to real API when available, fall back to mocks
  • Dynamic data: Generate fresh mock data on each request
  • Delay simulation: Add realistic latency to mock responses
  • Error simulation: Generate realistic error responses

My Take

This tool is a game changer for frontend development. Instead of waiting for backend APIs, you get realistic mocks in seconds. The AI-generated data is much better than static fixtures.

Rating: 8/10 β€” Essential for frontend teams working ahead of backend development.

FAQ

How realistic is the mock data?

Very realistic for standard entities (users, products, orders). The AI understands context and generates appropriate data types, formats, and relationships.

Can I customize the mock data?

Yes. Modify the prompt in generateMockResponse to specify exact data requirements, or provide example responses for the AI to follow.

Does this work with any OpenAPI spec?

Yes. The parser handles OpenAPI 3.0 specs. For older Swagger 2.0 specs, convert them first.

Can I use this in CI/CD pipelines?

Yes. The mock server can run in headless mode for integration tests.

Related: API Design Best Practices Β· OpenAPI Tutorial Β· Ollama Complete Guide