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]
format
(optional): Output format (json
oryaml
). Default:yaml
title
(optional): Title for the OpenAPI schemaversion
(optional): Version number for the OpenAPI schema
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:
- If the response is an array, only the first element will be included in the example (to avoid oversized outputs).
- This rule is recursively applied to nested arrays and objects as well.
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
- When you want to avoid writing OpenAPI schemas manually.
- For API-first development where mocks are created before implementation.
- To integrate with other tools like Prism or SwaggerUI.
- For ensuring schema consistency through automated testing.
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.