ovac / idoc

从您的Laravel应用程序生成美观的API文档

v1.7.0 2024-07-24 20:33 UTC

This package is auto-updated.

Last update: 2024-09-24 23:29:35 UTC


README



Latest Stable Version Total Downloads License

              Follow me anywhere @ovac4u                         | GitHub
              _________                          _________       | Twitter
             |   ___   |.-----.--.--.---.-.----.|  |  |.--.--.   | Facboook
             |  |  _   ||  _  |  |  |  _  |  __||__    |  |  |   | Instagram
             |  |______||_____|\___/|___._|____|   |__||_____|   | Github + @ovac
             |_________|                        www.ovac4u.com   | Facebook + @ovacposts


Laravel IDoc - API文档生成器

自动从现有的Laravel路由生成交互式API文档。看看示例文档。受Laravel Api Documentation Generator启发



简介。

Laravel IDoc生成器(交互式文档生成器)是从您的Laravel代码库生成API文档的完整插件。它受到laravel-apidoc-generator、ReDoc和Swagger的Open API倡议的启发。IDoc设计得易于扩展,以便它能够轻松适应您的用例。

Demo

特性

  • 极简部署
  • 服务器端渲染就绪
  • 最广泛支持的OpenAPI v2.0特性
    {.inline}
  • 支持OpenAPI 3.0
  • 整洁的强交互式文档,用于嵌套对象
    {.inline}
  • 自动代码示例支持
    {.inline}
  • 响应式三面板设计,菜单/滚动同步
  • 将API简介集成到侧边菜单。
  • 侧边菜单中的高级分组。
  • 品牌/定制。

安装

注意:PHP 7和Laravel 5.5或更高版本是最低依赖。

$ composer require ovac/idoc

Laravel

运行以下命令发布配置文件:

php artisan vendor:publish --tag=idoc-config

这将创建一个位于您的config文件夹中的idoc.php文件。

Lumen

  • 在您的bootstrap/app.php中注册服务提供者
$app->bind('path.public', function ($app) { return $app->basePath('../your-public-path'); });
$app->register(\OVAC\IDoc\IDocLumenServiceProvider::class);
  • 将配置文件从vendor/ovac/idoc/config/idoc.php复制到您的项目作为config/idoc.php。然后将其添加到您的bootstrap/app.php
$app->configure('idoc');

用法

$ php artisan idoc:generate

配置

在您生成文档之前,您需要在config/idoc.php中配置一些事情。

  • path 这将用于注册包所需的必要路由。
'path' => 'idoc',
  • logo 您可以指定要用于生成的文档的自定义logo。logo图片的相对或绝对URL。
'logo' => 'https://res.cloudinary.com/ovac/image/upload/h_300,w_380,c_fill,r_30,bo_20px_solid_white/aboust_ey5v1v.jpg',
  • title 在此处,您可以指定要在文档页面上放置的标题。
'title' => 'iDoc API Reference',
  • description 这将在文档顶部放置一个描述。
'description' => 'iDoc Api secification and documentation.',
  • version 文档版本号。

  • terms_of_service 这是使用您的API的使用条款和条件的URL。

  • contact 在此处,您可以配置支持的联系信息。

'contact' => [
        'name' => 'API Support',
        'email' => 'iamovac@gmail.com',
        'url' => 'http://www.ovac4u.com'
],
  • license 简短且简单的许可协议,仅要求保留版权和许可通知
'license' => [
        'name' => 'MIT',
        'url' => 'https://github.com/ovac/idoc/blob/master/LICENSE.md'
],
  • output 此包可以自动为您路由生成Open-API 3.0规范文件,以及文档。这是生成文档将被写入的文件路径。默认:public/docs

  • hide_download_button 此部分是您配置是否要在文档上显示下载按钮的地方。

  • router 处理路由时使用的路由器(可以是Laravel或Dingo。默认为Laravel

  • servers 服务器数组可用于在文档中添加多个端点,以便用户可以在端点之间切换。例如,这可以是测试服务器和实时服务器。

'servers' => [
   [
       'url' => 'https://www.ovac4u.com',
       'description' => 'App live server.',
   ],
   [
       'url' => 'https://test.ovac4u.com',
       'description' => 'App test server.',
   ],
],
  • tag_groups 此数组用于在侧菜单的细小部分中分离您已定义的组。如果您想使用它,请确保添加所有组,因为未添加的组将不会显示。

  • external_description 此选项允许您指定用于文档中的外部描述的路由名称。如果未提供,则默认为路由 idoc.info。默认设置为 idoc.info

'external_description' => 'idoc.info', // Route name for external description, leave empty to use default description

示例用法

'external_description' => 'idoc.info',
  • language-tabs 您可以在此处设置用于编写请求样本的语言。数组中的每个项目都用于为给定语言生成请求模板。可以在之后添加新语言并修改现有语言。您可以通过发布视图文件并编辑它们或添加自定义视图文件来添加或编辑新的语言选项卡。
'resources/views/vendor/idoc/languages/LANGUAGE.blade.php',
  • security 您可以在此处指定身份验证和授权方案。默认情况下,使用Bearer的HTTP身份验证方案已设置,但您可以修改它、添加其他方案或根据项目需求将其设置为null。有关更多信息,请访问 Swagger身份验证
'security' => [
       'BearerAuth' => [
           'type' => 'http',
           'scheme' => 'bearer',
           'bearerFormat' => 'JWT',
       ],
   ],
  • routes 您可以在此处指定应生成哪些规则的文档。您通过定义路由应满足的条件以及生成文档时应应用的规则来指定要解析的路由。这些条件和规则在组中指定,允许您对不同路由应用不同的规则。

例如,假设您的配置如下

return [
     //...,
  
     /*
     * The routes for which documentation should be generated.
     * Each group contains rules defining what routes should be included ('match', 'include' and 'exclude' sections)
     * and rules which should be applied to them ('apply' section).
     */
    'routes' => [
        [
            /*
             * Specify conditions to determine what routes will be parsed in this group.
             * A route must fulfill ALL conditions to pass.
             */
            'match' => [

                /*
                 * Match only routes whose domains match this pattern (use * as a wildcard to match any characters).
                 */
                'domains' => [
                    '*',
                    // 'domain1.*',
                ],

                /*
                 * Match only routes whose paths match this pattern (use * as a wildcard to match any characters).
                 */
                'prefixes' => [
                    'api/*',
                ],

                /*
                 * Match only routes registered under this version. This option is ignored for Laravel router.
                 * Note that wildcards are not supported.
                 */
                'versions' => [
                    'v1',
                ],
            ],

            //...
        ],
    ],

这意味着将为所有域名('*'是通配符,表示“任何字符”)中的路由生成文档,这些路由匹配以下任何模式之一“api/*”或“v2-api/*”,排除“users.create”路由以及任何以admin.开头的路由,包括“users.index”路由以及任何以healthcheck.开头的路由。(除非您使用Dingo路由器,否则忽略versions键)。此外,在生成的文档中,这些路由将在示例请求中添加标题“Authorization: Bearer: {token}”。

您还可以将路由分开到组中,为它们应用不同的规则

<?php
return [
     //...,
  
     'routes' => [
          [
              'match' => [
                  'domains' => ['v1.*'],
                  'prefixes' => ['*'],
              ],
              'include' => [],
              'exclude' => [],
              'apply' => [
                  'headers' => [
                      'Token' => '{token}',
                      'Version' => 'v1',
                  ],
              ],
          ],
          [
              'match' => [
                  'domains' => ['v2.*'],
                  'prefixes' => ['*'],
              ],
              'include' => [],
              'exclude' => [],
              'apply' => [
                  'headers' => [
                      'Authorization' => 'Bearer: {token}',
                      'Api-Version' => 'v2',
                  ],
              ],
          ],
];

使用上述配置,v1.*域上的路由将应用TokenVersion标题,而v2.*域上的路由将应用AuthorizationApi-Version标题。

注意:includeexclude项是路由名称的数组。支持通配符*。注意:如果您使用DIngo路由器,则每个路由组中都需要versions参数。此参数不支持通配符。必须明确列出每个版本。

要生成您的API文档,请使用idoc:generate artisan命令。

$ php artisan idoc:generate

它将使用您指定的配置生成文档。

记录您的API

此包使用这些资源来生成API文档

分组端点

此包使用HTTP控制器文档块来创建目录表并显示API方法的描述。

在控制器文档块中使用@group创建API文档中的组。该控制器处理的所有路由都将分组在侧边栏的此组中。@group后的简短描述应该是唯一的,以便允许锚点标签导航到此部分。可以包括更长的描述。还支持自定义格式化和<aside>标签。(见Documentarian文档

注意:使用 @group 是可选的。未分组的路由将被放置在“通用”组中。

您希望将其包含在API文档中的每个控制器方法上方都应该有一个文档块。这应包括一个独特的简短描述作为第一条记录。可以添加一个可选的第二条记录,其中包含更多信息。这两个描述将以不同的格式出现在API文档中,如下所示。您还可以在单个方法上指定 @group 以覆盖控制器级别的组。

/**
 * @group User management
 *
 * APIs for managing users
 */
class UserController extends Controller
{

	/**
	 * Create a user
	 *
	 * [Insert optional longer description of the API endpoint here.]
	 *
	 */
	 public function createUser()
	 {

	 }
	 
	/**
	 * @group Account management
	 *
	 */
	 public function changePassword()
	 {

	 }
}

指定请求参数

要指定API路由接受的参数列表,请使用 @bodyParam@queryParam@pathParam 注解。

  • @bodyParam 注解接受参数名称、其类型、可选的“必需”标签以及其描述。
  • @queryParam 注解接受参数名称、可选的“必需”标签以及其描述。
  • @pathParam 注解接受参数名称、可选的“必需”标签以及其描述。
/**
 * @group Items
 */
class ItemController extends Controller
{

    /**
     * List items
     *
     * Get a list of items.
     *
     * @authenticated
     * @responseFile responses/items.index.json
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //...
    }

    /**
     * Store item
     *
     * Add a new item to the items collection.
     *
     * @bodyParam name string required
     * The name of the item. Example: Samsung Galaxy s10
     *
     * @bodyParam price number required
     * The price of the item. Example: 100.00
     *
     * @authenticated
     * @response {
     *      "status": 200,
     *      "success": true,
     *      "data": {
     *          "id": 10,
     *          "price": 100.00,
     *          "name": "Samsung Galaxy s10"
     *      }
     * }
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //...
    }


    /**
     * Get item
     *
     * Get item by it's unique ID.
     *
     * @pathParam item integer required
     * The ID of the item to retrieve. Example: 10
     *
     * @response {
     *      "status": 200,
     *      "success": true,
     *      "data": {
     *          "id": 10,
     *          "price": 100.00,
     *          "name": "Samsung Galaxy s10"
     *      }
     * }
     * @authenticated
     *
     * @param  \App\Item  $item
     * @return \Illuminate\Http\Response
     */
    public function show(Item $item)
    {
        //...
    }

它们将包含在生成的文档文本和示例请求中。

结果: 结果

注意:示例请求中每个参数的值将使用随机值。如果您想指定示例值,可以在描述的末尾添加 示例:your-example。例如

    /**
     * @pathParam location_id required The id of the location.
     * @queryParam user_id required The id of the user. Example: me
     * @queryParam page required The page number. Example: 4
     * @bodyParam user_id int required The id of the user. Example: 9
     * @bodyParam room_id string The id of the room.
     * @bodyParam forever boolean Whether to ban the user forever. Example: false
     */

注意:您还可以将 @bodyParam 注解添加到 \Illuminate\Foundation\Http\FormRequest 子类

/**
 * @bodyParam title string required The title of the post.
 * @bodyParam body string required The title of the post.
 * @bodyParam type string The type of post to create. Defaults to 'textophonious'.
 * @bodyParam author_id int the ID of the author
 * @bodyParam thumbnail image This is required if the post type is 'imagelicious'.
 */
class MyRequest extends \Illuminate\Foundation\Http\FormRequest
{

}

public function createPost(MyRequest $request)
{
    // ...
}

指示认证状态

您可以使用 @authenticated 注解在方法上指示端点是已认证的。将在交互式文档中提供一个用于认证令牌的字段,并将其标记为必需。

提供示例响应

您可以为路由提供一个示例响应。这将在示例部分显示。有几种方法可以实现这一点。

@response

您可以使用带有有效JSON的 @response 注解为路由提供示例响应。

/**
 * @response {
 *  "id": 4,
 *  "name": "Jessica Jones",
 *  "roles": ["admin"]
 * }
 */
public function show($id)
{
    return User::find($id);
}

此外,您还可以定义多个 @response 标签以及与特定响应相关的HTTP状态码(如果没有设置状态码,将返回 200

/**
 * @response {
 *  "id": 4,
 *  "name": "Jessica Jones",
 *  "roles": ["admin"]
 * }
 * @response 404 {
 *  "message": "No query results for model [\App\User]"
 * }
 */
public function show($id)
{
    return User::findOrFail($id);
}

@transformer, @transformerCollection, 和 @transformerModel

您可以使用 @transformer 标签(如果路由返回列表,则为 @transformerCollection)来定义用于路由结果的转换器。该包将尝试使用以下步骤生成要转换的模型实例,并在第一个成功的步骤停止

  1. 检查是否存在 @transformerModel 标签以定义要转换的模型。如果没有,则使用转换器的 transform() 方法的第一个参数的类。
  2. 从Eloquent模型工厂获取模型实例
  3. 如果参数是Eloquent模型,则从数据库中加载第一个。
  4. 使用 new 创建实例。

最后,它将模型传递给转换器,并显示该转换的结果作为示例响应。

例如

/**
 * @transformercollection \App\Transformers\UserTransformer
 * @transformerModel \App\User
 */
public function listUsers()
{
    //...
}

/**
 * @transformer \App\Transformers\UserTransformer
 */
public function showUser(User $user)
{
    //...
}

/**
 * @transformer \App\Transformers\UserTransformer
 * @transformerModel \App\User
 */
public function showUser(int $id)
{
    // ...
}

对于上面的第一个路由,此包将生成一组两个用户,然后通过转换器传递。对于最后两个,它将生成单个用户,然后通过转换器传递。

注意:为了支持变压器,您需要安装league/fractal包

composer require league/fractal

@responseFile

对于大的响应体,您可能希望使用实际响应的转储。您可以将此响应放入您的Laravel存储目录中的一个文件(作为JSON字符串)并链接到它。例如,我们可以将此响应放入名为users.get.json的文件中,位于storage/responses

{"id":5,"name":"Jessica Jones","gender":"female"}

然后在您的控制器中,通过以下方式链接到它:

/**
 * @responseFile responses/users.get.json
 */
public function getUser(int $id)
{
  // ...
}

该包将解析此响应并在该路由的示例中显示。

类似于@response标签,您可以提供多个@responseFile标签以及响应的HTTP状态码

/**
 * @responseFile responses/users.get.json
 * @responseFile 404 responses/model.not.found.json
 */
public function getUser(int $id)
{
  // ...
}

自动生成响应

如果您没有使用上述任何方式指定示例响应,此包将尝试通过向路由(一个“响应调用”)发出请求来获取响应。

关于响应调用的一些注意事项

  • 它们是在数据库事务中完成的,并且在之后回滚更改。
  • 响应调用的配置位于config/idoc.php中。它们在每个路由组的['apply']['response_calls']部分中进行配置,允许您为不同的路由组应用不同的设置。
  • 默认情况下,响应调用仅针对GET路由进行,但您可以进行配置。将methods键设置为方法数组或'*'表示所有方法。将其留为空数组以关闭该路由组的响应调用。
  • URL中的参数(例如:/users/{user}/orders/{id?})默认将替换为'1'。然而,您可以进行配置。将参数名称(包括花括号和问号)作为键,将其替换作为值放在bindings键中。
  • 您可以配置环境变量(这很有用,可以防止触发外部服务,如通知)。默认情况下,APP_ENV设置为'documentation'。您可以在env键中添加更多变量。
  • 默认情况下,该包将为您记录的主体和查询参数生成假值并在请求中发送。(如果您使用@bodyParam@queryParam指定了示例值,则将使用这些值。)您可以在请求发送时配置应发送的标头和附加查询参数(分别使用headersquerybody键)。
  • 默认情况下,所有中间件都是启用的,但您可以设置without_middleware数组以指定您希望禁用的中间件,您甚至可以使用['*']来禁用所有中间件。

Open-API 3.0规范文件

生成器会自动创建一个Open-API 3.0规范文件,您可以将它导入到任何外部API应用程序中使用。

规范文件中添加的默认基本URL将是在您的Laravel config/app.php文件中找到的。这可能是https://。如果您想更改此设置,可以直接更新URL或将此配置值链接到您的环境文件以使其更灵活(如下所示)

'url' => env('APP_URL', 'http://yourappdefault.app'),

如果您引用的是上面的环境设置,那么您应该确保您已更新了您的.env文件以设置适当的APP_URL值。否则,您的规范文件将使用默认值(http://yourappdefault.app)。

APP_URL=http://yourapp.app

使用@responseResource记录复杂响应

@responseResource注释允许您使用Laravel API资源轻松地记录复杂响应结构。此功能简化了生成完整API文档的过程,包括自动生成示例响应,用于嵌套和复杂的数据结构。

用法

要使用@responseResource注释,将其添加到控制器方法的PHPDoc块中

/**
 * @responseResource App\Http\Resources\OrderResource
 */
public function show($id)
{
    return new OrderResource(Order::findOrFail($id));
}

您还可以指定状态码

/**
 * @responseResource 201 App\Http\Resources\OrderResource
 */
public function store(Request $request)
{
    $order = Order::create($request->all());
    return new OrderResource($order);
}

记录资源类

在您的API资源类中,请在类级别的DocBlock中使用以下标签来提供资源元数据

  • @resourceName:指定文档中资源的自定义名称。
  • @resourceDescription:提供资源的描述。
  • @resourceStatus:为资源设置默认的HTTP状态码。

示例

/**
 * @resourceName Order
 * @resourceDescription Represents an order in the system
 * @resourceStatus 200
 */
class OrderResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            /**
             * @responseParam id integer required The ID of the order. Example: 1
             */
            'id' => $this->id,
            /**
             * @responseParam status string required The status of the order. Enum: [pending, processing, shipped, delivered]. Example: processing
             */
            'status' => $this->status,
            /**
             * @responseParam items array required The items in the order.
             */
            'items' => $this->items->map(function ($item) {
                return [
                    /**
                     * @responseParam id integer required The ID of the item. Example: 101
                     */
                    'id' => $item->id,
                    /**
                     * @responseParam name string required The name of the item. Example: Ergonomic Keyboard
                     */
                    'name' => $item->name,
                    /**
                     * @responseParam price float required The price of the item. Example: 129.99
                     */
                    'price' => $item->price,
                ];
            }),
        ];
    }
}

toArray方法中使用@responseParam注释来记录资源单独的字段。您可以针对每个字段指定以下内容

  • 类型(例如,整数,字符串,数组)
  • 是否必填
  • 描述
  • 示例值
  • 枚举值(如果适用)

@responseResource注释自动解析您的API资源类,生成详细的结构化响应模式,包括嵌套关系和复杂的数据类型。此外,它还根据提供的示例值或每个字段类型的默认值自动生成示例响应。

进一步修改

视图文件夹中的info文件可以进一步修改以添加介绍和进一步文档。

使用自定义配置生成器

idoc:custom命令允许您使用自定义配置文件生成API文档。这在您需要使用不同设置生成文档而不修改默认配置时非常有用。

命令签名

命令签名是

php artisan idoc:custom {config?}
  • config(可选):位于config目录中的自定义配置文件名称(不带.php扩展名)。

如何使用

  1. 创建自定义配置文件

    config目录中创建一个自定义配置文件。文件应遵循命名约定idoc.{config}.php,其中{config}是您在运行命令时将使用的名称。

    config/idoc.ecommerce.php的示例

    // config/idoc.ecommerce.php
    return [
        'title' => 'E-commerce API Documentation',
        'version' => '1.0.0',
        'description' => 'API documentation for e-commerce.',
        'terms_of_service' => 'https://example.com/terms',
        'contact' => [
            'name' => 'E-commerce API Support',
            'email' => 'support@example.com',
            'url' => 'https://example.com',
        ],
        'license' => [
            'name' => 'MIT',
            'url' => 'https://open-source.org.cn/licenses/MIT',
        ],
        'output' => '/docs/ecommerce', // Ensure this path is unique
        'hide_download_button' => false,
        'external_description' => route('ecommerce-doc-description'),
        'routes' => [
            [
                'match' => [
                    'domains' => ['*'],
                    'prefixes' => ['api/ecommerce/*'],
                    'versions' => ['v1'],
                ],
                'include' => [],
                'exclude' => [],
                'apply' => [
                    'headers' => [
                        'Authorization' => 'Bearer {token}',
                    ],
                    'response_calls' => [
                        'methods' => ['*'],
                        'bindings' => [],
                        'env' => [
                            'APP_ENV' => 'documentation',
                            'APP_DEBUG' => false,
                        ],
                        'headers' => [
                            'Content-Type' => 'application/json',
                            'Accept' => 'application/json',
                        ],
                        'query' => [],
                        'body' => [],
                        'without_middleware' => [],
                    ],
                ],
            ],
        ],
    ];
    
  2. 运行命令

    使用您的自定义配置文件名称(不带.php扩展名)运行命令。

    示例

    php artisan idoc:custom ecommerce
    

    如果自定义配置文件存在,它将被加载并与默认配置合并。然后,命令将使用合并后的配置生成API文档。

  3. 检查输出

    生成的文档将保存到您的自定义配置文件的output配置选项中指定的路径。请确保输出路径对于每份自定义文档都是唯一的,以避免冲突。这是相对于public目录的。

    • 电子商务API文档:/docs/ecommerce,将open-api规范文件保存到public/docs/ecommerce/openapi.json,并将文档保存到public/docs/ecommerce/index.html
    • 用户管理API文档:/docs/user将open-api规范文件保存到public/docs/user/openapi.json,并将文档保存到public/docs/user/index.html

通过使用自定义配置生成器,您可以轻松地在同一Laravel应用程序中管理并生成针对不同应用程序的多个API文档集合。这种方法允许您为每个API维护独立的配置和文档输出,确保清晰和组织。

管理多个API文档集合

自定义配置生成器还可以帮助您在同一Laravel应用程序中管理针对不同应用程序的多个API文档集合。如果您有不同的API集合用于不同的应用程序或模块,这将特别有用。

示例场景

假设您有一个Laravel应用程序,它为不同的应用程序提供多个API,例如用户管理API和电子商务API。您可以为每个API创建单独的配置文件,并使用自定义配置生成器相应地生成文档。

  1. 创建配置文件

    • config/idoc.ecommerce.php
    • config/idoc.user.php
  2. 为每个API运行命令

    php artisan idoc:custom ecommerce
    php artisan idoc:custom user
    

    这将使用各自的配置文件为每个应用程序生成API文档。

  3. 检查输出

    生成的文档将保存到您的自定义配置文件的output配置选项中指定的路径。请确保每个输出路径是唯一的,以避免冲突。这是相对于public目录的。

    • 电子商务API文档:/docs/ecommerce,将open-api规范文件保存到public/docs/ecommerce/openapi.json,并将文档保存到public/docs/ecommerce/index.html
    • 用户管理API文档:/docs/user将open-api规范文件保存到public/docs/user/openapi.json,并将文档保存到public/docs/user/index.html

通过使用自定义配置生成器,您可以轻松地在同一Laravel应用程序中管理并生成针对不同应用程序的多个API文档集合。这种方法允许您为每个API维护独立的配置和文档输出,确保清晰和组织。

定义自定义文档路由

为了为每个自定义配置提供生成的文档,您需要在您的 routes/web.php 或类似的路由文件中定义路由。这确保了每套文档都可以通过唯一的URL访问。

idoc.ecommerce.php 配置示例

1. **Create a Custom Configuration File:**

   Create a custom configuration file in the `config` directory. The file should follow the naming convention `idoc.{config}.php`, where `{config}` is the name you will use when running the command.

   Example for `config/idoc.ecommerce.php`:
   ```php
   // config/idoc.ecommerce.php
   return [
       'title' => 'E-commerce API Documentation',
       'version' => '1.0.0',
       'description' => 'API documentation for e-commerce.',
       'terms_of_service' => 'https://example.com/terms',
       'contact' => [
           'name' => 'E-commerce API Support',
           'email' => 'support@example.com',
           'url' => 'https://example.com',
       ],
       'license' => [
           'name' => 'MIT',
           'url' => 'https://open-source.org.cn/licenses/MIT',
       ],
       'output' => '/docs/ecommerce', // Ensure this path is unique
       'hide_download_button' => false,
       'external_description' => route('ecommerce-doc-description'),
       'routes' => [
           [
               'match' => [
                   'domains' => ['*'],
                   'prefixes' => ['api/ecommerce/*'],
                   'versions' => ['v1'],
               ],
               'include' => [],
               'exclude' => [],
               'apply' => [
                   'headers' => [
                       'Authorization' => 'Bearer {token}',
                   ],
                   'response_calls' => [
                       'methods' => ['*'],
                       'bindings' => [],
                       'env' => [
                           'APP_ENV' => 'documentation',
                           'APP_DEBUG' => false,
                       ],
                       'headers' => [
                           'Content-Type' => 'application/json',
                           'Accept' => 'application/json',
                       ],
                       'query' => [],
                       'body' => [],
                       'without_middleware' => [],
                   ],
               ],
           ],
       ],
   ];
  1. 运行命令

    使用您的自定义配置文件名称(不带.php扩展名)运行命令。

    示例

    php artisan idoc:custom ecommerce

    如果自定义配置文件存在,它将被加载并与默认配置合并。然后,命令将使用合并后的配置生成API文档。

  2. 检查输出

    生成的文档将被保存在您的自定义配置文件中指定的 output 配置选项指定的路径。请确保每个自定义文档的输出路径是唯一的,以避免冲突。

管理多个API文档集合

自定义配置生成器还可以帮助您在同一Laravel应用程序中管理针对不同应用程序的多个API文档集合。如果您有不同的API集合用于不同的应用程序或模块,这将特别有用。

示例场景

假设您有一个Laravel应用程序,它为不同的应用程序提供多个API,例如用户管理API和电子商务API。您可以为每个API创建单独的配置文件,并使用自定义配置生成器相应地生成文档。

  1. 创建配置文件

    • config/idoc.ecommerce.php
    • config/idoc.user.php
  2. 为每个API运行命令

    php artisan idoc:custom ecommerce
    php artisan idoc:custom user

    这将使用各自的配置文件为每个应用程序生成API文档。

  3. 检查输出

    生成的文档将保存到您的自定义配置文件的output配置选项中指定的路径。请确保每个输出路径是唯一的,以避免冲突。这是相对于public目录的。

    • 电子商务API文档:/docs/ecommerce,将open-api规范文件保存到public/docs/ecommerce/openapi.json,并将文档保存到public/docs/ecommerce/index.html
    • 用户管理API文档:/docs/user将open-api规范文件保存到public/docs/user/openapi.json,并将文档保存到public/docs/user/index.html

通过使用自定义配置生成器,您可以轻松地在同一Laravel应用程序中管理并生成针对不同应用程序的多个API文档集合。这种方法允许您为每个API维护独立的配置和文档输出,确保清晰和组织。

定义自定义文档路由

为了为每个自定义配置提供生成的文档,您需要在您的 routes/web.php 或类似的路由文件中定义路由。这确保了每套文档都可以通过唯一的URL访问。

idoc.ecommerce.php 配置示例

// routes/web.php

// Documentation for the ecommerce routes
Route::group([], function () {
    // Set the idoc config to the ecommerce config
    config(['idoc' => config('idoc.ecommerce')]);

    // Define the route for the user documentation
    Route::view(config('idoc.path'), 'idoc::documentation');
});

鸣谢

本软件使用了以下开源包

您可能也喜欢...

许可证

MIT