wapmorgan / openapi-generator
OpenApi configuration generator directly from PHP code (PhpDoc, functions signature and type hints) and projects (for yii2, slim, laravel). Can be used with a large monolithic backend to maintain big API documentation
Requires
- php: >=7.4
- doctrine/annotations: ^1.6
- phpdocumentor/reflection-docblock: ^4.3|^5.1
- symfony/console: ^5.0|^6.0
- zircote/swagger-php: ^3.0
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
It is OpenApi configuration generator that works with origin source code + phpdoc.
Main purpose of this library is to automatize generation of OpenApi-specification for existing JSON-API with a lot of methods. Idea by @maxonrock.
OpenApiGenerator
What it does?
It generates OpenApi 3.0 specification files for your REST JSON-based API written in PHP from source code directly. You do not need to write OpenApi-specification manually.
Laravel Example
-
Routes:
Route::get('/selector/lists', [\App\Http\Controllers\SelectorController::class, 'lists']); Route::post('/selector/select', [\App\Http\Controllers\SelectorController::class, 'select']); Route::get('/selector/goTo', [\App\Http\Controllers\SelectorController::class, 'goTo']); Route::get('/geo/detect', [\App\Http\Controllers\GeoController::class, 'detect']); Route::get('/geo/select', [\App\Http\Controllers\GeoController::class, 'select']);
-
One controller:
/** * Returns lists of filters * @param Request $request * @return ListsResponse */ public function lists(Request $request) { return new ListsResponse([ // 'persons' => range(1, 15), 'persons' => array_keys(Menu::$personsList), 'tastes' => Menu::$tastes, 'meat' => Menu::$meat, 'pizzas' => Menu::$pizzas, ]); } /** * Makes a selection of pizzas according to criteria * @param \App\Http\Requests\SelectPizzas $request * @return PizzaListItem[] */ public function select(\App\Http\Requests\SelectPizzas $request) { $validated = $request->validated(); return (new Selector())->select( $validated['city'], $validated['persons'], $validated['tastes'] ?? null, $validated['meat'] ?? null, $validated['vegetarian'] ?? false, $validated['maxPrice'] ?? null); }
-
One request and two responses:
class SelectPizzas extends FormRequest { public function rules() { // ... return array_merge([ 'city' => ['required', 'string'], 'persons' => ['required', Rule::in(array_keys(Menu::$personsList))], 'vegetarian' => ['boolean'], 'maxPrice' => ['numeric'], 'pizzas' => ['array', Rule::in(array_keys(Menu::$pizzas))], ], $tastes, $meat); } } class ListsResponse extends BaseResponse { /** @var string[] */ public $persons; /** @var string[] */ public $tastes; /** @var string[] */ public $meat; /** @var string[] */ public $pizzas; } class PizzaListItem extends BaseResponse { public string $pizzeria; public string $id; public int $sizeId; public string $name; public float $size; public array $tastes; public array $meat; public float $price; public float $pizzaArea; public float $pizzaCmPrice; public string $thumbnail; public array $ingredients; public int $dough; }
-
Result of generation from code: two endpoints with description and arguments for
select.┌─────────┬─────────────────┬──────────────────────────┐ │ get │ /selector/lists │ Returns lists of filters │ ├─────────┼─────────────────┼──────────────────────────┤ │ Result (4) │ │ persons │ array of string │ │ │ tastes │ array of string │ │ │ meat │ array of string │ │ │ pizzas │ array of string │ │ └─────────┴─────────────────┴──────────────────────────┘ ┌──────────────────┬──────────────────┬───────────────────────────────────────────────────┐ │ post │ /selector/select │ Makes a selection of pizzas according to criteria │ ├──────────────────┼──────────────────┼───────────────────────────────────────────────────┤ │ Parameters (15) │ │ string │ city │ │ │ string │ persons │ │ │ boolean │ vegetarian │ │ │ number │ maxPrice │ │ │ array │ pizzas │ │ │ boolean │ tastes.cheese │ │ │ boolean │ tastes.sausage │ │ │ boolean │ tastes.spicy │ │ │ boolean │ tastes.mushroom │ │ │ boolean │ tastes.exotic │ │ │ boolean │ meat.chicken │ │ │ boolean │ meat.pork │ │ │ boolean │ meat.beef │ │ │ boolean │ meat.fish │ │ │ boolean │ meat.sauce_meat │ │ ├──────────────────┼──────────────────┼───────────────────────────────────────────────────┤ │ Result (14) │ │ │ array of │ │ │ [*].pizzeria │ string │ │ │ [*].id │ string │ │ │ [*].sizeId │ integer │ │ │ [*].name │ string │ │ │ [*].size │ integer │ │ │ [*].tastes │ array of │ │ │ [*].meat │ array of │ │ │ [*].price │ integer │ │ │ [*].pizzaArea │ integer │ │ │ [*].pizzaCmPrice │ integer │ │ │ [*].thumbnail │ string │ │ │ [*].ingredients │ array of │ │ │ [*].dough │ integer │ │ └──────────────────┴──────────────────┴───────────────────────────────────────────────────┘
How it works
- Scraper collects info about API (tags, security schemes and servers, all endpoints) and contains settings for Generator. Scraper is framework-dependent.
- Generator fulfills openapi-specification with endpoints information by analyzing source code:
- summary and description of actions
- parameters and result of actions Generator is common. It just receives information from Scraper and analyzes code by Scraper rules.
More detailed process description is in How it works document.
How to use
Invoke console script to generate openapi for your project (with help of integrations):
For example, for yii2-project:
- Run parser on project to analyze files and retrieve info about endpoints
./vendor/bin/openapi-generator scrape --scraper yii2 ./ # And more deeper scan ./vendor/bin/openapi-generator generate --scraper yii2 --inspect ./ - Generate specification(s) into yaml-files in
api_docsfolder by specification_name.yml./vendor/bin/openapi-generator generate --scraper yii2 ./ ./api_docs/ # Or with your own scraper (child of one of basic scrapers) ./vendor/bin/openapi-generator generate --scraper components/api/OpenApiScraper.php ./ ./api_docs/ - Deploy swagger with specification (e.g. api_docs/main.yml on port 8091)
docker run -p 8091:8080 --rm -e URL=./apis/main.yaml -v $(pwd):/usr/share/nginx/html/apis/ swaggerapi/swagger-ui:v4.15.2
More detailed description is in How to use document.
Integrations
There's few integrations: Yii2, Laravel, Slim. Details is in Integrations document. You can write your own integration for framework or your project.
Extending
New scraper
You use (or extend) a predefined scraper (see Integrations) or create your own scraper from scratch (extend DefaultScraper), which should return a result with list of your API endpoints. Also, your scraper should provide tags, security schemes and so on.
Scraper should return list of specifications (for example, list of api versions) with:
- meta - version/description/externalDocs - of specification.
- servers - list of servers (base urls).
- tags - list of tags with description and other properties (categories for endpoints).
- securitySchemes - list of security schemes (authorization types).
- endpoints - list of API endpoints (separate callbacks).
Detailed information about Scraper result: in another document.
Settings
DefaultGenerator provides list of settings to tune generator.
| Parameter | type | default | description |
|---|---|---|---|
| CHANGE_GET_TO_POST_FOR_COMPLEX_PARAMETERS | bool | false | if callback has arguments with object , array , stdclass , mixed type or class-typed, method of argument will be changed to POST and these arguments will be placed as body data in json-format |
| TREAT_COMPLEX_ARGUMENTS_AS_BODY | bool | false | move complex arguments to request body |
| PARSE_PARAMETERS_FROM_ENDPOINT | bool | false | if callback id has macroses (users/{id}), these arguments will be parsed as normal callback arguments |
| PARSE_PARAMETERS_FORMAT_FORMAT_DESCRIPTION | bool | false | if php-doc for callback argument in first word after argument variable has one of predefined sub-types (@param string $arg SUBTYPE Full parameter description ), this will change sub-type in resulting specification. For example, for string format there are subtypes: date, date-time, password, byte, binary, for integer there are: float, double, int32, int64. Also, you can defined custom format with DefaultGenerator::setCustomFormat($format, $formatConfig) |
Usage:
$generator->changeSetting(DefaultGenerator::CHANGE_GET_TO_POST_FOR_COMPLEX_PARAMETERS, true);
By default, they all are disabled.
Limitations
- Only query parameters supported (
url?param1=...¶m2=...) or body json parameters ({data: 123). - Only one response type supported - HTTP 200 response.
- No support for parameters' / fields' / properties'
format,exampleand other validators. - PHPDoc array maps (
array<K, V>) and shapes (array{...}) are supported for endpoint parameters and responses. List-shape semantics and the rest of the Psalm/PHPStan type syntax are not fully supported yet.
Tests
Type-to-schema regression tests run in a Docker Composer container. Only Docker and Make are required on the host:
make test
When the library is inside the AG project, the target reuses its installed dependencies but runs PHPUnit in a container. For a standalone checkout, the target installs dependencies with Composer inside the container. See the development roadmap for planned parser, schema, diagnostics, and integration improvements.
Input parameter location
Use a location-specific tag to describe where a method argument comes from:
/** * @param int $id Resource identifier. * @pathParam $id * @param string|null $filter Filter. * @queryParam $filter * @headerParam string $request_id name=X-Request-Id format=uuid optional Request identifier. * @cookieParam string $locale optional Interface locale. * @bodyParam CreateRequest $request required Creation payload. */
Use @pathParam, @queryParam, @headerParam, @cookieParam, and @bodyParam. For a tag referring to a method argument, $name alone is enough; its type is taken from @param or the PHP signature. For an external value that is not a method argument, include its type in the location tag. Set the wire name with name= and the format with format=. Requiredness for bound arguments is inferred from the PHP signature; external parameters are optional by default, while path parameters are always required.
Use the same tags for values read directly from the Request that are not run() arguments:
/** * @headerParam string $request_id name=X-Request-Id format=uuid optional Request identifier. * @cookieParam string $locale optional Interface locale. * @queryParam int $tenant required Organization ID. * @bodyParam array<string, int> $payload required Request payload. */ public function run(): array
Syntax: @<location>Param [<type>] $<name> [name=<wire-name>] [format=<format>] [required|optional] <description>, where <location> is query, path, header, cookie, or body. Path parameters are always required. Each @bodyParam describes a property in a JSON object; use @requestBody <type> required|optional <description> to describe the entire request body schema. Do not combine @requestBody with @bodyParam fields. Request bodies currently use application/json only. The legacy @apiParameter tag remains supported for compatibility, but new PHPDoc should use the location-specific tags.
If no location is specified, the backward-compatible behavior is retained: primitive types are treated as query parameters, while complex types go into the JSON body when the corresponding scraper setting is enabled. Route placeholders such as {id} are treated as path parameters when PARSE_PARAMETERS_FROM_ENDPOINT is enabled. When CHANGE_GET_TO_POST_FOR_COMPLEX_PARAMETERS is enabled, an endpoint declared as GET is generated as POST if it has a request body. Explicit locations document the contract but do not change runtime parameter binding: the application must still read header and cookie values from the appropriate request source.
ToDo
- Support for few operations on one endpoint (GET/POST/PUT/DELETE/...).
- Support for body parameters (when parameters are complex objects) - partially.
- Support for few responses (with different HTTP codes).
- Extracting class types into separate components (into openapi components).
- Support for other request/response types besides JSON
- Add
@paramFormatfor specifying parameter format - partially. - Support for dynamic action arguments in dynamic model
- Switch 3.0/3.1 (https://www.openapis.org/blog/2021/02/16/migrating-from-openapi-3-0-to-3-1-0)