ThinkPHP8 配置 Swagger

网上找了一圈 ThinPHP 的 Swagger 文档配置发现都不是很完善,故重新整理一篇

先安装 zircote/swagger-php 依赖

shell 复制代码
composer require zircote/swagger-php

再安装 doctrine/annotations 声明文件

shell 复制代码
composer require doctrine/annotations

编写一个自定义 command 命令,使其可以自动生成 swagger.json 到 public 目录下

shell 复制代码
php think make:command Swagger

在 app/command/Swagger.php 文件下写入自定义方法

php 复制代码
<?php

declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use OpenApi\Generator;

class Swagger extends Command
{
    protected function configure(): void
    {
        $this->setName('swagger')
            ->setDescription('生成Swagger API文档');
    }

    protected function execute(Input $input, Output $output): void
    {
        // 确保扫描路径正确
        $openapi = (new Generator())->generate([app_path() . 'controller']);
        // 生成swagger.json文件
        $openapi->saveAs(public_path() . 'ant123.json');
        $output->writeln('Swagger文档生成成功!');
    }
}

在 app/controller/Index.php 文件下测试使用

ini 复制代码
<?php

namespace app\controller;

use app\BaseController;
use OpenApi\Attributes as OA;

/**
 * @OA\Info(
 *     title="ThinkPHP API文档",
 *     version="1.0.0",
 *     description="API接口文档"
 * )
 * @OA\OpenApi(
 *     @OA\Server(
 *         url="http://localhost:8000",
 *         description="本地开发服务器"
 *     )
 * )
 */
class Index extends BaseController
{
    /**
     * @OA\Get(
     *     path="/",
     *     summary="首页接口",
     *     tags={"基础接口"},
     *     @OA\Response(
     *         response=200,
     *         description="成功返回首页内容",
     *         @OA\MediaType(
     *             mediaType="text/html"
     *         )
     *     )
     * )
     */
    public function index()
    {
        return '<style>*{ padding: 0; margin: 0; }</style><iframe src="https://www.thinkphp.cn/welcome?version=' . \think\facade\App::version() . '" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>';
    }
}

生成 swagger.json

shell 复制代码
 php think swagger

即可自动在 public 目录下新增 swagger.json 文件了,可以搭配 ApiFox 类的在线文档工具使用。

生产环境建议

该文档应该只放在开发环境,而不应该配置在生产环境中。

参考文章

# Swagger PHP Thinkphp 接口文档

相关推荐
xmode8 天前
常用自定义函数laravel版+thinkphp版
后端·php·laravel·thinkphp
mooyuan天天9 天前
内网渗透之Thinkphp5提权实战+reGeorg代理横向移动(CVE-2018-20062)
内网渗透·横向移动·thinkphp·regeorg·cve-2018-20062·thinkphp代码执行漏洞
蹦极的考拉11 天前
夜间无法登录:ThinkPHP api接口 23:00 准时罢工的排查全纪录
小程序·thinkphp·api接口·无法登陆
青茶36011 天前
ThinkCMF是一个开源的内容管理框架
php·cms·thinkphp
quweiie12 天前
thinkphp8.0链接SQL SERVER2022数据库
数据库·sqlserver·thinkphp
ghie909019 天前
基于ThinkPHP实现动态ZIP压缩包的生成
thinkphp
用户3074596982071 个月前
容器(Container)—— 对象的“智能工厂+调度官”
后端·thinkphp
非凡的世界1 个月前
ThinkPHP6 集成TCP长连接 GatewayWorker
网络·网络协议·tcp/ip·gateway·thinkphp·worker·workman
非凡的世界2 个月前
Thinkphp8 Redis队列与消息队列topthink/think-queue 原创
数据库·redis·bootstrap·thinkphp