Mock a REST API from an OpenAPI Spec

Goal: You have an OpenAPI specification (Swagger file) and want to automatically generate mock endpoints for frontend development.

Time: 3 minutes

What You’ll Learn

  • Load an OpenAPI/Swagger spec into MockForge
  • Auto-generate mock responses from schema definitions
  • Enable dynamic data with template expansion
  • Test your mocked API

Prerequisites

  • MockForge installed (Installation Guide)
  • An OpenAPI 3.0 or Swagger 2.0 spec file (JSON or YAML)

Step 1: Prepare Your OpenAPI Spec

Use your existing spec, or create a simple one for testing:

petstore-api.json:

{
  "openapi": "3.0.0",
  "info": {
    "title": "Pet Store API",
    "version": "1.0.0"
  },
  "paths": {
    "/pets": {
      "get": {
        "summary": "List all pets",
        "responses": {
          "200": {
            "description": "Successful response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/Pet"
                  }
                }
              }
            }
          }
        }
      },
      "post": {
        "summary": "Create a pet",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/Pet"
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Pet created",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Pet"
                }
              }
            }
          }
        }
      }
    },
    "/pets/{petId}": {
      "get": {
        "summary": "Get a pet by ID",
        "parameters": [
          {
            "name": "petId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Pet"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "Pet": {
        "type": "object",
        "required": ["id", "name"],
        "properties": {
          "id": {
            "type": "string",
            "example": "{{uuid}}"
          },
          "name": {
            "type": "string",
            "example": "Fluffy"
          },
          "species": {
            "type": "string",
            "example": "cat"
          },
          "age": {
            "type": "integer",
            "example": 3
          }
        }
      }
    }
  }
}

Step 2: Start MockForge with Your Spec

mockforge serve --spec petstore-api.json --http-port 3000

What happened? MockForge:

  • Parsed your OpenAPI spec
  • Created mock endpoints for all defined paths
  • Generated example responses from schemas

Step 3: Test the Auto-Generated Endpoints

# List all pets
curl http://localhost:3000/pets

# Create a pet
curl -X POST http://localhost:3000/pets \
  -H "Content-Type: application/json" \
  -d '{"name": "Rex", "species": "dog", "age": 5}'

# Get a specific pet
curl http://localhost:3000/pets/123

Step 4: Enable Dynamic Template Expansion

To get unique IDs and dynamic data on each request:

# Stop the server (Ctrl+C), then restart with templates enabled:
MOCKFORGE_RESPONSE_TEMPLATE_EXPAND=true \
mockforge serve --spec petstore-api.json --http-port 3000

Now test again - the {{uuid}} in your schema examples will generate unique IDs!

Step 5: Add Request Validation

MockForge can validate requests against your OpenAPI schema:

MOCKFORGE_RESPONSE_TEMPLATE_EXPAND=true \
MOCKFORGE_REQUEST_VALIDATION=enforce \
mockforge serve --spec petstore-api.json --http-port 3000

Try sending an invalid request:

# This will fail validation (missing required 'name' field)
curl -X POST http://localhost:3000/pets \
  -H "Content-Type: application/json" \
  -d '{"species": "dog"}'

Response:

{
  "error": "request validation failed",
  "details": [
    {
      "path": "body.name",
      "code": "required",
      "message": "Missing required field: name"
    }
  ]
}

Step 6: Use a Configuration File (Optional)

For more control, create a config file:

petstore-config.yaml:

server:
  http_port: 3000

spec: petstore-api.json

validation:
  mode: enforce

response:
  template_expand: true

admin:
  enabled: true
  port: 9080

Start with config:

mockforge serve --config petstore-config.yaml

Advanced: Override Specific Responses

You can override auto-generated responses for specific endpoints:

petstore-config.yaml:

http:
  port: 3000
  openapi_spec: petstore-api.json
  response_template_expand: true

  # Override the GET /pets endpoint
  routes:
    - path: /pets
      method: GET
      response:
        status: 200
        body: |
          [
            {
              "id": "{{uuid}}",
              "name": "{{faker.name}}",
              "species": "cat",
              "age": {{randInt 1 15}}
            },
            {
              "id": "{{uuid}}",
              "name": "{{faker.name}}",
              "species": "dog",
              "age": {{randInt 1 15}}
            }
          ]

Step 7: Configure Request Validation

MockForge supports comprehensive OpenAPI request validation. Update your config to enable validation:

validation:
  mode: enforce          # Reject invalid requests
  aggregate_errors: true # Combine multiple validation errors
  status_code: 422       # Use 422 for validation errors

# Optional: Skip validation for specific routes
validation:
  overrides:
    "GET /health": "off"  # Health checks don't need validation

Test validation by sending an invalid request:

# This will fail validation (missing required fields)
curl -X POST http://localhost:3000/pets \
  -H "Content-Type: application/json" \
  -d '{"species": "dog"}'

Response:

{
  "error": "request validation failed",
  "status": 422,
  "details": [
    {
      "path": "body.name",
      "code": "required",
      "message": "Missing required field: name"
    }
  ]
}

Validation Modes

  • off: Disable validation completely
  • warn: Log warnings but allow invalid requests
  • enforce: Reject invalid requests with error responses

Common Use Cases

Use CaseConfiguration
Frontend developmentEnable CORS, template expansion
API contract testingEnable request validation (enforce mode)
Demo environmentsUse faker functions for realistic data
Integration testsDisable template expansion for deterministic responses

Troubleshooting

Spec not loading?

  • Verify the file path is correct
  • Check that the spec is valid OpenAPI 3.0 or Swagger 2.0
  • Use a validator like Swagger Editor

Validation too strict?

# Use 'warn' mode instead of 'enforce'
MOCKFORGE_REQUEST_VALIDATION=warn mockforge serve --spec petstore-api.json

Need custom responses?

Complete Workflow Example

Here’s a complete workflow for generating mocks from an OpenAPI spec and using them in development:

1. Start with OpenAPI Spec

# Your API team provides this spec
cat petstore-api.json

2. Generate Mock Server

# Start MockForge with the spec
MOCKFORGE_RESPONSE_TEMPLATE_EXPAND=true \
  mockforge serve --spec petstore-api.json --http-port 3000 --admin

3. Test Generated Endpoints

# All endpoints from the spec are now available
curl http://localhost:3000/pets
curl http://localhost:3000/pets/123
curl -X POST http://localhost:3000/pets -d '{"name": "Fluffy", "species": "cat"}'

4. Monitor in Admin UI

Visit http://localhost:9080 to see:

  • All requests in real-time
  • Request/response bodies
  • Response times
  • Error rates

5. Use in Frontend Development

Point your frontend app to the mock server:

// In your React/Vue/Angular app
const API_URL = 'http://localhost:3000';

fetch(`${API_URL}/pets`)
  .then(res => res.json())
  .then(data => console.log('Pets:', data));

6. Iterate as API Evolves

When the API spec changes:

# 1. Update the OpenAPI spec file
vim petstore-api.json

# 2. Restart MockForge (it auto-reloads from spec)
# Or use watch mode if available

# 3. Regenerate client code (if using code generation)
mockforge client generate --spec petstore-api.json --framework react

Best Practices

Organization

  1. Keep specs in version control

    git add petstore-api.json
    git commit -m "Add Pet Store API spec v1.2"
    
  2. Use environment-specific configs

    # mockforge.dev.yaml
    http:
      port: 3000
      response_template_expand: true
      cors:
        enabled: true
    
  3. Document any custom overrides

    # Custom route overrides
    http:
      routes:
        - path: /pets/{petId}
          method: GET
          response:
            # Override default response
            status: 200
            body: |
              {
                "id": "{{request.path.petId}}",
                "name": "Custom Pet",
                "species": "custom"
              }
    

Testing

  1. Use deterministic data for tests

    # Disable template expansion for consistent test data
    response:
      template_expand: false
    
  2. Enable validation for contract testing

    mockforge serve --spec api.json --validation enforce
    
  3. Record test scenarios

    • Use Admin UI to record request/response pairs
    • Export as fixtures for automated tests

What’s Next?


Pro Tip: Keep your OpenAPI spec in version control alongside your mock configuration. As the real API evolves, update the spec and your frontend automatically benefits from the changes.