PHPackages                             avrilko/apidocs - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. avrilko/apidocs

ActiveLibrary[API Development](/categories/api)

avrilko/apidocs
===============

A swagger library for Hyperf.

v1.1.2(3y ago)027MITPHPPHP &gt;=8.0

Since Mar 22Pushed 3y agoCompare

[ Source](https://github.com/avrilko-go/api-docs)[ Packagist](https://packagist.org/packages/avrilko/apidocs)[ RSS](/packages/avrilko-apidocs/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (8)Versions (5)Used By (0)

PHP Swagger Api Docs
--------------------

[](#php-swagger-api-docs)

基于 [Hyperf](https://github.com/hyperf/hyperf) 框架的 swagger 文档生成组件，支持swoole/swow驱动

##### 优点

[](#优点)

- 声明参数类型完成自动注入，参数映射到PHP类，根据类和注解自动生成Swagger文档
- 代码DTO模式，可维护性好，扩展性好
- 支持数组(类/简单类型)，递归，嵌套
- 支持注解数据校验
- 支持api token
- 支持PHP8原生注解，PHP8.1枚举
- 支持openapi 3.0

使用须知
----

[](#使用须知)

- php版本 &gt;= 8.0
- 控制器中方法尽可能返回类,这样会更好的生成文档
- 当返回类的结果满足不了时,可以使用 #\[ApiResponse\] 注解

例子
--

[](#例子)

> 请参考[example目录](https://github.com/tw2066/api-docs/tree/master/example)

安装
--

[](#安装)

```
composer require tangwei/apidocs

```

使用
--

[](#使用)

#### 1. 发布配置文件

[](#1-发布配置文件)

```
php bin/hyperf.php vendor:publish tangwei/apidocs
```

##### 1.1 配置信息

[](#11-配置信息)

> config/autoload/api\_docs.php

```
return [
    // enable false 将不会启动 swagger 服务
    'enable' => env('APP_ENV') !== 'prod',
    'format' => 'json',
    'output_dir' => BASE_PATH . '/runtime/swagger',
    'prefix_url' => env('API_DOCS_PREFIX_URL', '/swagger'),
    // 替换验证属性
    'validation_custom_attributes' => true,
    // 全局responses
    'responses' => [
        ['response' => 401, 'description' => 'Unauthorized'],
        ['response' => 500, 'description' => 'System error'],
    ],
    // swagger 的基础配置  OpenAPI 对象
    'swagger' => [
        'info' => [
            'title' => 'API DOC',
            'version' => '0.1',
            'description' => 'swagger api desc',
        ],
        'servers' => [
            [
                'url' => 'http://127.0.0.1:9501',
                'description' => 'OpenApi host',
            ],
        ],
        'components' => [
            'securitySchemes' => [
                [
                    'securityScheme' => 'Authorization',
                    'type' => 'apiKey',
                    'in' => 'header',
                    'name' => 'Authorization',
                ],
            ],
        ],
        'security' => [
            ['Authorization' => []],
        ],
        'externalDocs' => [
            'description' => 'Find out more about Swagger',
            'url' => 'https://github.com/tw2066/api-docs',
        ],
    ],
];
```

### 2. 直接启动框架(需要有http服务)

[](#2-直接启动框架需要有http服务)

```
php bin/hyperf.php start

[INFO] Swagger docs url at http://0.0.0.0:9501/swagger
[INFO] TaskWorker#1 started.
[INFO] Worker#0 started.
[INFO] HTTP Server listening at 0.0.0.0:9501
```

> 看到`Swagger Url`显示，表示文档生成成功，访问`/swagger`即可以看到swagger页面

### 3. 使用

[](#3-使用)

注解
--

[](#注解)

> 命名空间:`Hyperf\DTO\Annotation\Contracts`

#### \#\[RequestBody\]

[](#requestbody)

- 获取Body参数

```
public function add(#[RequestBody] DemoBodyRequest $request){}
```

#### \#\[RequestQuery\]

[](#requestquery)

- 获取GET参数

```
public function add(#[RequestQuery] DemoQuery $request){}
```

#### \#\[RequestFormData\]

[](#requestformdata)

- 获取表单请求

```
public function fromData(#[RequestFormData] DemoFormData $formData){}
```

- 获取文件(和表单一起使用)

```
#[ApiFormData(name: 'photo', format: 'binary')]
```

- 获取Body参数和GET参数

```
public function add(#[RequestBody] DemoBodyRequest $request, #[RequestQuery] DemoQuery $query){}
```

#### \#\[ApiSecurity\] 注解

[](#apisecurity-注解)

- 优先级: 方法 &gt; 类 &gt; 全局

```
#[ApiSecurity('Authorization')]
public function getUserInfo(DemoToken $header){}
```

> 注意: 一个方法，不能同时注入RequestBody和RequestFormData

示例
--

[](#示例)

### 控制器

[](#控制器)

```
#[Controller(prefix: '/demo')]
#[Api(tags: 'demo管理', position: 1)]
class DemoController extends AbstractController
{
    #[ApiOperation(summary: '查询')]
    #[PostMapping(path: 'index')]
    public function index(#[RequestQuery] #[Valid] DemoQuery $request): Contact
    {
        $contact = new Contact();
        $contact->name = $request->name;
        var_dump($request);
        return $contact;
    }

    #[PutMapping(path: 'add')]
    #[ApiOperation(summary: '提交body数据和get参数')]
    public function add(#[RequestBody] DemoBodyRequest $request, #[RequestQuery] DemoQuery $query)
    {
        var_dump($query);
        return json_encode($request, JSON_UNESCAPED_UNICODE);
    }

    #[PostMapping(path: 'fromData')]
    #[ApiOperation(summary: '表单提交')]
    #[ApiFormData(name: 'photo', type: 'file')]
    #[ApiResponse(code: '200', description: 'success', className: Address::class, type: 'array')]
    public function fromData(#[RequestFormData] DemoFormData $formData): bool
    {
        $file = $this->request->file('photo');
        var_dump($file);
        var_dump($formData);
        return true;
    }

    #[GetMapping(path: 'find/{id}/and/{in}')]
    #[ApiOperation('查询单体记录')]
    #[ApiHeader(name: 'test')]
    public function find(int $id, float $in): array
    {
        return ['$id' => $id, '$in' => $in];
    }

}
```

验证器
---

[](#验证器)

### 基于框架的验证

[](#基于框架的验证)

> 安装hyperf框架验证器[hyperf/validation](https://github.com/hyperf/validation), 并配置(已安装忽略)

- 注解 `Required` `Between` `Date` `Email` `Image` `Integer` `Nullable` `Numeric` `Url` `Validation` `...`
- 校验生效

> 只需在控制器方法中加上 #\[Valid\] 注解

```
public function index(#[RequestQuery] #[Valid] DemoQuery $request){}
```

```
class DemoQuery
{
    #[ApiModelProperty('名称')]
    #[Required]
    #[Max(5)]
    #[In(['qq','aa'])]
    public string $name;

    #[ApiModelProperty('正则')]
    #[Str]
    #[Regex('/^.+@.+$/i')]
    #[StartsWith('aa,bb')]
    #[Max(10)]
    public string $email;

    #[ApiModelProperty('数量')]
    #[Required]
    #[Integer]
    #[Between(1,5)]
    public int $num;
}
```

### 自定义注解验证

[](#自定义注解验证)

> 注解的验证支持框架所有验证, 组件提供了常用的注解用于验证

1. 使用自定义验证注解, 创建注解类继承`Hyperf\DTO\Annotation\Validation\BaseValidation`
2. 重写`$rule`属性或`getRule`方法

```
//示例
#[Attribute(Attribute::TARGET_PROPERTY)]
class Image extends BaseValidation
{
    protected $rule = 'image';
}
```

注意
--

[](#注意)

### 数组类型的问题

[](#数组类型的问题)

> PHP原生暂不支持`int[]`或`Class[]`类型, 使用示例

```
    /**
     * class类型映射数组.
     * @var \App\DTO\Address[]
     */
    #[ApiModelProperty('地址')]
    public array $addressArr;

    /**
     * 简单类型映射数组.
     * @var int[]
     */
    #[ApiModelProperty('int类型的数组')]
    public array $intArr;

    /**
     * 通过注解映射数组.
     */
    #[ApiModelProperty('string类型的数组')]
    #[ArrayType('string')]
    public array $stringArr;
```

### hyperf 2.2版本报错

[](#hyperf-22版本报错)

> @required注解会提示报错,请忽略required
>
> 修改文件config/autoload/annotations.php

```
return [
    'scan' => [
        //...
        'ignore_annotations' => [
            //...
           'required'
        ],
    ],
];
```

### `AutoController`注解

[](#autocontroller注解)

> 控制器中使用`AutoController`注解,只收集了`POST`方法

Swagger界面
---------

[](#swagger界面)

[![hMvJnQ](https://camo.githubusercontent.com/bffb31f2d24ce000c5d063e9f2f4ab3b3aa9c6c3a1bcf2a50d44f8def417461e/68747470733a2f2f67697465652e636f6d2f74773636362f736f757263652f7261772f6d61737465722f696d672f737761676765722e706e67)](https://camo.githubusercontent.com/bffb31f2d24ce000c5d063e9f2f4ab3b3aa9c6c3a1bcf2a50d44f8def417461e/68747470733a2f2f67697465652e636f6d2f74773636362f736f757263652f7261772f6d61737465722f696d672f737761676765722e706e67)

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

4

Last Release

1145d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0bf5907dbcfa743f21173fc5781376404cf057aa70bb83539e7a8607e5e42656?d=identicon)[avrilko](/maintainers/avrilko)

---

Top Contributors

[![tw2066](https://avatars.githubusercontent.com/u/24579418?v=4)](https://github.com/tw2066 "tw2066 (99 commits)")

---

Tags

phpswaggerdocshyperfhyperf swagger

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/avrilko-apidocs/health.svg)

```
[![Health](https://phpackages.com/badges/avrilko-apidocs/health.svg)](https://phpackages.com/packages/avrilko-apidocs)
```

###  Alternatives

[tangwei/apidocs

A swagger library for Hyperf.

51130.4k8](/packages/tangwei-apidocs)[hyperf/swagger

A swagger library for Hyperf.

19338.7k6](/packages/hyperf-swagger)[daodao97/apidog

A swagger library for Hyperf.

15040.1k1](/packages/daodao97-apidog)[kakuilan/hyperf-apihelper

hyperf api swagger helper

443.0k](/packages/kakuilan-hyperf-apihelper)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
