定制 jeandormehl/openapi-gen 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

jeandormehl/openapi-gen

Composer 安装命令:

composer require jeandormehl/openapi-gen

包简介

Generates OpenApi specification for Laravel, Lumen or Dingo using a configuration array and cebe/php-openapi

README 文档

README

About

The openapi-gen package provides a convenient way to create OpenApi specifications for Laravel, Lumen or Dingo using a single configuration file. It is aimed at lightweight microservices and can be parsed by various packages to enable functionality such as gateway and relay routing.

The idea came from the lack of such packages and to stay away from polluting Controllers, Models and such with millions of lines of annotations. Annotations also lack the ability to use variables as values.

This package uses cebe/php-openapi for most of the heavy lifting, including validation of the specification. Thanks for the great package!

Table of Contents

Features

  • Auto generate basic schema definitions from model classes.
  • Auto generate common HTTP responses used by most REST API's.
  • Entire specification is stored nicely and neatly in one configuration file.
  • Create any OpenApi object using simple arrays.

Installation

Require jeandormehl/openapi-gen package in your composer.json and update your dependencies:

$ composer require jeandormehl/openapi-gen

Laravel

Add Rapid\OAS\Providers\ServiceProvider to your config/app.php providers array.

Publish the minimum configuration:

$ php artisan vendor:publish --provider="Rapid\OAS\Providers\ServiceProvider"

Note: Package autodiscovery is not used because Dingo uses a different service provider to Laravel/Lumen. Will find a way to combine them all into one provider at some point.

Lumen

Copy the config file:

$ mkdir -p config
$ cp -R vendor/jeandormehl/openapi-gen/config/oas.php config/oas.php

Load the configuration into bootstrap/app.php:

$app->configure('oas');

Register the service provider:

$app->register(Rapid\OAS\Providers\ServiceProvider::class);

Dingo

Follow the instructions for either Laravel or Lumen, depending on what you're using.

When registering the service provider, replace with Rapid\OAS\Providers\DingoServiceProvider::class

Note: When using Dingo, your API_PREFIX will be prepended to the route that is registered.

Configuration

The oas.php file contains your entire specification and depending on its contents, the specification will be generated. Basic validation is also provided so if you make a mistake in your config file, the package should give you an idea of where and how to correct the issue.

The file consists of arrays matching the OpenApi specification. When I created this package, OpenApi was currently on version 3.0.2.

Here are useful links to ensure validity of your configuration:

route

The route key controls the route that is registered to access the specification. Here you enable/disable the route, set the path and prefix and add middleware if necessary.

  ...

  'route' => [
      'enabled'    => true,
      'prefix'     => '',
      'path'       => 'docs',
      'middleware' => [],
  ],

  ...

Note: When using Dingo, your API_PREFIX will be prepended to the route that is registered.

yaml

The yaml key defines the path to output the specification as a .yml file. By default, the file is placed in storage/app/oas.yml. To generate the yaml file, run the following artisan command:

$ php artisan oas:yaml

openapi

The openapi key specifies the OAS version. This defaults to 3.0.2.

  ...

  'openapi' => \Rapid\OAS\OpenApi::VERSION,

  ...

Please see the oasObject for more information.

info

The info key represent an OAS info object.

Minimum configuration:

  ...

  'info' => [
      'title'   => 'OpenApi',
      'version' => env('API_VERSION') ?? env('APP_VERSION', 'v1'),
  ],

  ...

Full configuration:

  ...

  'info' => [
      'title'          => 'OpenApi',
      'description'    => 'This is the OpenApi specification package.',
      'termsOfService' => 'http://localhost/termsOfService',
      'contact'        => [
          'name'  => 'John Smith',
          'url'   => 'http://localhost/me',
          'email' => 'john.smith@company.com',
      ],
      'license' => [
          'name' => 'Apache-2.0',
          'url'  => 'http://www.apache.org/licenses/LICENSE-2.0',
      ],
      'version' => env('API_VERSION') ?? env('APP_VERSION', 'v1'),
  ],

  ...

Please see the infoObject for more information.

servers

The servers key contains arrays of OAS server objects.

Mimimum configuration:

  ...

  'servers' => [
      [
          'url' => 'http://localhost:8080/v1',
      ],
  ],

  ...

Full configuration:

  ...

  'servers' => [
      [
          'url'         => 'http://localhost:8080/v1',
          'description' => 'OpenApi HTTP Server',
          // server variables
          'variables'   => [
              'scheme' => [
                  'enum'        => ['http', 'https'],
                  'default'     => 'http',
                  'description' => 'The Transfer Protocol',
              ],
          ],
      ],
  ],

  ...

Please see the serverObject and serverVariableObject for more information.

security

The security key defines security requirement objects. The name used for each property MUST correspond to a securityScheme declared in the securitySchemes under the components object. These are required globally for use of the API. If the security scheme is of type oauth2 or openIdConnect, then the value is a list of scope names required for the execution. For other security scheme types, the array MUST be empty.

Minimum configuration:

  ...

  'security' => [
      'apiKey' => [],
      // if using oauth
      'oauth2' => [
          'view:users',
          'create:users',
      ],
  ],

  ...

Full configuration:

  ...

  'security' => [
      'apiKey' => [],
      'http'   => [],
      'bearer' => [],
      'oauth2' => [
          'view:users',
          'create:users',
      ],
      'openIdConnect' => [
          'view:users',
          'create:users',
      ],
  ],

  ...

Please see the securityRequirementObject for more information.

tags

The tags key contains arrays of OAS tag objects.

Minimum configuration:

  ...

  'tags' => [
      [
          'name' => 'User',
      ],
  ],

  ...

Full configuration:

  ...
  'tags' => [
      [
          'name'         => 'User',
          'description'  => 'API user models.',
          // see externalDocs section
          'externalDocs' => [
              'url'         => 'http://localhost/tags/users/externalDocs',
              'description' => 'User docs.',
          ],
      ],
  ],
  ...

Please see the tagObject for more information.

externalDocs

The externalDocs key contains the external documentation OAS object.

Minimum configuration:

  ...

  'externalDocs' => [
      'url' => 'http://localhost/externalDocs',
  ],

  ...

Full configuration:

  ...

  'externalDocs' => [
      'url'         => 'http://localhost/externalDocs',
      'description' => 'External docs for OpenApi.',
  ],

  ...

Please see the externalDocumentationObject for more information.

components

The components key. Refer to componentsObject.

Schemas

The schemas key. Refer to schemaObject.

Auto generated model schemas.

This packages allows you to automatically generate basic schemas based on your Eloquent models. Providing an array of Fully Qualified Class Names (FQCN) inside a models array, the package will attempt to create the schemas for you which can later be referenced in other keys.

Note: Currently supports MySQL, SQLite, PostgreSQL and Oracle.

Note: These schema definitions are very basic, containing only the following values:

  • Title
  • Description
  • Required
  • Properties

Properties will only contain the following attributes:

  • Description
  • Type
  • Format
  • Nullable
  • Default

Properties defined inside the models hidden array and inside the configuration hidden tag will be excluded from the schema.

Minimum configuration:

  ...

  'components' => [
      'schemas' => [
            ...

            'models' => ['App\\User' => []],

            ...
      ],
  ],

  ...

Full configuration:

  ...

  'components' => [
      'schemas' => [
            ...

            'models' => [
                'App\\User' => [
                    'hidden' => ['password', 'updated_at', 'deleted_at']
                ],
            ],

            ...
      ],
  ],

  ...
Standard schema objects

The schemas key represent an array of OAS schema objects. Here you can define your custom schemas and reference them later in your configuration. It is highly recommended to define all your schemas here and simply reference them in the configuration as opposed to creating inline schemas, although the functionality does exist.

Example Enum schema:

  ...

  'components' => [
      'schemas' => [
          ...

          'Status' => [
              'title'       => 'Status',
              'description' => 'Current status of the user.',
              'enum'        => ['Active', 'Pending', 'Disabled'],
              'default'     => 'Pending',
              'type'        => \cebe\openapi\spec\Type::STRING,
          ],

          ...
      ],
  ],

  ...

Example Object schema:

  ...

  'components' => [
      'schemas' => [
          ...

          'User' => [
              'title'       => 'User',
              'description' => 'The User object.',
              'type'        => \cebe\openapi\spec\Type::OBJECT,
              'required'   => ['email', 'status'],
              'properties' => [
                  'email' => [
                      'type' => \cebe\openapi\spec\Type::STRING,
                      'title' => 'Email',
                      'description' => 'The users email address.',
                      // pattern => '',
                  ],
                  'first_name' => [
                      'type' => \cebe\openapi\spec\Type::STRING,
                      'title' => 'FirstName',
                      'description' => 'The users first name.',
                  ],
                  // $refs should always be an array as seen here
                  'status' => ['$ref' => '#/components/schemas/Status']
              ],
              'maxProperties' => 3,
              'minProperties' => 3,
          ],

          ...
      ],
  ],

  ...

Note: The schema OAS object contains many properties depending on the type of schema definition you are using.

Refer to schemaObject for all additional properties and types.

Responses

Auto generated common HTTP responses

The responses key contains a key called statusCodes which defines common HTTP responses used in almost all REST APIs. This key is simply an array of HTTP status codes which will generate the responses. At this time, all the responses generated are application/json and can be referenced anywhere in your specification.

Note: Do not define a 200 OK response here unless that is all you wish to return to services consuming your API. 200 responses should generally be defined within paths or operations using schema and requestBodies $refs.

Configuration:

  ...

  'components' => [
      ...

      'responses' => [
          ...

          // common responses use application/json content types.
          'statusCodes' => [400, 401, 403, 404, 405, 418, 422, 500, 502, 503],

          ...
      ],
  ],

  ...
Standard response objects

The responses key represent an array of OAS response objects. Here you can define your custom responses and reference them later in your configuration. It is highly recommended to define all your responses here and simply reference them in the configuration as opposed to creating inline responses, although the functionality does exist.

Configuration:

  ...

  'components' => [
      ...

      'responses' => [
          ...

          'TokenResponse' => [
              'description' => 'The oauth2 token response.',
              'content'     => [
                  // mediaType object
                  'application/json' => [
                      // using schemas $ref. Try to stick to $refs but inline can also be used
                      'schema' => ['$ref' => '#/components/schemas/TokenResponse'],
                  ],
              ],
          ],

          ...
      ],
  ],

  ...

Parameters

The parameters key is used to specify parameters and can be referenced anywhere in your specification. It is highly recommended that you define all parameters in this key and reference them throughout your specification.

Configuration:

  ...

  'components' => [
      ...

      'parameters' => [
          ...

          'Identifier' => [
              'name'            => 'Identifier',
              'in'              => 'path',
              'description'     => 'The model identifier',
              'required'        => true,
              'deprecated'      => false,
              'allowEmptyValue' => false,

              // you can use inline schema objects here but its highly recommended to use $refs to schema objects
              'schema' => ['$ref' => '#components/schemas/Identifier'],
              // 'schema' => [
              //     'type'    => \cebe\openapi\spec\Type::INTEGER,
              //     'format'  => \Rapid\OAS\Spec\Format::INT32,
              //     'example' => 1,
              // ],
          ],

          ...
      ],
  ],

  ...

Please refer to parameterObject for more information.

RequestBodies

The requestBodies key represent an array of OAS requestBody objects. Its is recommended that all requestBodies are defined and simply referenced where needed within the specification.

Configuration:

  ...

  'components' => [
      ...

      'requestBodies' => [
          ...

          'User' => [
              'description' => 'User request body.',
              'required'    => true,
              'content'     => [
                  'application/json' => [
                      // using schema $ref. Inline can also be specified.
                      'schema'  => ['$ref' => '#/components/schemas/User'],
                  ],
              ],
          ],

          ...
      ],

      ...
  ],

Headers

The headers key represent an array of OAS header objects. Its is recommended that all headers are defined and simply referenced where needed within the specification.

Minimum configuration:

  ...

  'components' => [
      ...

      'headers' => [
          ...

          'X-User-Id' => [
              'description' => 'The User Identifier passed between microservices.',
              'required'   => true,
              'deprecated' => false,
              // use $ref wherever possible
              'schema' => ['$ref' => '#/components/schemas/Identifier'],
          ],

          ...
      ],

      ...
  ],

Full configuration:

  ...

  'components' => [
      ...

      'headers' => [
          ...

          'Accept' => [
              'description' => 'The Accept header to pass to all requests.',
              'required'    => true,
              'deprecated'  => false,
              'content'     => [
                  // mediaType object
                  'application/json' => [
                      // using an inline schemas. Try to stick to $refs
                      'schema' => ['type' => \cebe\openapi\spec\Type::STRING],
                      'examples' => [
                          'application/json' => ['value' => 'application/json'],
                          'application/vnd.github.v3+json' => ['value' => 'application/vnd.github.v3+json'],
                      ],
                  ],
              ],
          ],

          ...
      ],

      ...
  ],

Please refer to the headerObject and the mediaTypeObject for more info on how these are created.

SecuritySchemes

The securityScheme key. These link directly to the security key and should be defined before being using in the security or operation objects.

Full configuration:

  ...

  'components' => [
      ...

      'securitySchemes' => [
          ...

          // apiKey example
          'apiKey' => [
              'type'        => 'apiKey',
              'description' => 'Unique key used to authenticate against API.',
              'name'        => 'X-Application-Id',
              'in'          => 'header',
          ],

          // possible http schemes: basic, bearer
          // basic example
          'basic' => [
              'type'        => 'http',
              'description' => 'HTTP basic scheme to authenticate against API.',
              'scheme'      => 'basic',
          ],

          // bearer example
          'bearer' => [
              'type'         => 'http',
              'description'  => 'HTTP bearer scheme to authenticate against API.',
              'scheme'       => 'bearer',
              'bearerFormat' => 'bearer',
          ],

          // oauth2 example
          'oauth2' => [
              'type'        => 'oauth2',
              'description' => 'OAuth2 authentication flows to authenticate against API.',
              'flows' => [
                  // implicit
                  'implicit' => [
                      'authorizationUrl' => 'http://localhost/authorizationUrl',
                      'scopes'           => [
                          'view:users'   => 'View all user information',
                          'create:users' => 'Create a new user.',
                      ],
                  ],

                  // password
                  'password' => [
                      'tokenUrl'   => 'http://localhost/tokenUrl',
                      'refreshUrl' => 'http://localhost/refreshUrl',
                      'scopes'     => [
                          'view:users'   => 'View all user information',
                          'create:users' => 'Create a new user.',
                      ],
                  ],

                  // clientCredentials
                  'clientCredentials' => [
                      'tokenUrl'   => 'http://localhost/tokenUrl',
                      'refreshUrl' => 'http://localhost/refreshUrl',
                      'scopes'     => [
                          'view:users'   => 'View all user information',
                          'create:users' => 'Create a new user.',
                      ],
                  ],

                  // authorizationCode
                  'authorizationCode' => [
                      'authorizationUrl' => 'http://localhost/authorizationUrl',
                      'tokenUrl'         => 'http://localhost/tokenUrl',
                      'scopes'           => [
                          'view:users'   => 'View all user information',
                          'create:users' => 'Create a new user.',
                      ],
                  ],
              ],
          ],

          // openIdConnect example
          'openIdConnect' => [
              'type'             => 'openIdConnect',
              'description'      => 'OpenIdConnect authentication for API.',
              'openIdConnectUrl' => 'https://open.id/connect',
          ],

          ...
      ],

      ...
  ],

Please refer to securitySchemeObject, oauthFlowsObject and oauthFlowObject for more details.

paths

The paths key. Refer to pathsObject.

This is the most important key of the entire configuration. This will define your paths and operations. Where possible, try to only use $refs and keep this configuration as clean and neat as possible.

  ...

  'paths' => [
      // path item
      '/users' => [
          // operation (GET)
          'get' => [
              'tags'        => ['User'],
              'summary'     => 'Get Users',
              'description' => 'Get a paginated result set of User objects.',
              'operationId' => 'user.index',
              // try stick to $refs
              'responses'   => [
                  '200' => ['$ref' => '#/components/responses/UsersList'],
                  '400' => ['$ref' => '#/components/responses/400'],
                  '401' => ['$ref' => '#/components/responses/401'],
                  '403' => ['$ref' => '#/components/responses/403'],
              ],
          ],

          // operation (POST)
          'post' => [
              'tags'        => ['User'],
              'summary'     => 'Create User',
              'description' => 'Create a new user.',
              'operationId' => 'user.create',
              'requestBody' => ['$ref' => '#/components/requestBodies/User'],
              'responses' => [
                  '200' => ['$ref' => '#/components/responses/User'],
                  '400' => ['$ref' => '#/components/responses/400'],
                  '401' => ['$ref' => '#/components/responses/401'],
                  '403' => ['$ref' => '#/components/responses/403'],
                  '404' => ['$ref' => '#/components/responses/404'],
                  '418' => ['$ref' => '#/components/responses/418'],
                  '422' => ['$ref' => '#/components/responses/422'],
              ],
          ],
      ],
  ],

  ...

TODO

License

Released under the Apache-2.0 License, see LICENSE.

jeandormehl/openapi-gen 适用场景与选型建议

jeandormehl/openapi-gen 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 525 次下载、GitHub Stars 达 6, 最近一次更新时间为 2019 年 08 月 20 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「api」 「laravel」 「swagger」 「dingo」 「openapi」 「lumen」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 jeandormehl/openapi-gen 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 jeandormehl/openapi-gen 我们能提供哪些服务?
定制开发 / 二次开发

基于 jeandormehl/openapi-gen 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 525
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 6
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2019-08-20