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 接口文档

相关推荐
非凡的世界12 天前
Thinkphp8 Redis队列与消息队列topthink/think-queue 原创
数据库·redis·bootstrap·thinkphp
非凡的世界12 天前
ThinkPHP8集成RabbitMQ的完整案例实现 原创
rabbitmq·thinkphp
未来之窗软件服务14 天前
UI设计(三)按实际输出内容递增的序号效果——东方仙盟筑基期
ui·thinkphp·仙盟创梦ide·东方仙盟sdk
王嘉俊9251 个月前
ThinkPHP 入门:快速构建 PHP Web 应用的强大框架
开发语言·前端·后端·php·框架·thinkphp
蓝黑20202 个月前
阿里云ECS服务器搭建ThinkPHP环境
服务器·阿里云·thinkphp
奔跑吧邓邓子3 个月前
从0到1学PHP(十二):PHP 框架入门与项目实战
php·框架·laravel·项目实战·thinkphp·yii
奔跑吧邓邓子3 个月前
PHPStorm携手ThinkPHP8:开启高效开发之旅
phpstorm·php开发·thinkphp·thinkphp8
centaury323 个月前
使用FastAdmin框架开发二
uniapp·thinkphp·fastadmin
quweiie3 个月前
tp8.0\jwt接口安全验证
前端·安全·jwt·thinkphp