MockAPI-PHP

OpenAPI Schema Auto-Generation

Starting from version 1.2, this project includes a feature to automatically generate OpenAPI 3.0 schemas based on the JSON response files located under responses/{endpoint_path}/{method}/{status_name}.json.

How to Run

CLI (Command Line):

php generate-schema.php [format] [title] [version]

Example:

php generate-schema.php yaml "My Awesome API" "2.0.0"

Web (via Browser):

GET /generate-schema.php?format=json&title=My+Awesome+API&version=2.0.0

Output File

The generated schema will be saved as either schema/openapi.yaml or schema/openapi.json.

Validation

Each JSON response file will be validated against its automatically generated JSON Schema. If the structure is invalid, the process will be aborted and the error message will be written to logs/validation-error.log.

Automatic example Embedding

Each schema includes an example field derived from the original JSON response:

Environment Variables (.env)

You can customize default behavior by setting the following environment variables in .env:

LOG_DIR=./logs
SCHEMA_DIR=./schema
SCHEMA_FORMAT=yaml
SCHEMA_TITLE=MockAPI-PHP Auto Schema
SCHEMA_VERSION=1.0.0

Note: if parameters are passed directly when executing the script, they take precedence over the environment variables.

Use Cases for Auto Schema Generation

Example: Auto-Generating Schema via CI/CD (GitHub Actions)

.github/workflows/generate-schema.yml:

name: Generate OpenAPI Schema

on:
  push:
    paths:
      - 'responses/**'
      - 'generate-schema.php'

jobs:
  generate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Set up PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.4'
      - run: composer install --no-dev
      - run: php generate-schema.php yaml
      - name: Upload schema
        if: hashFiles('schema/openapi.yaml') != ''
        uses: actions/upload-artifact@v4
        with:
          name: openapi-schema
          path: schema/openapi.json

With this setup, a fresh OpenAPI schema will be automatically generated and saved whenever response files are updated.