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

相关推荐
云游云记2 天前
FastAdmin 路由完全开启教程:去掉 index 前缀 + 优雅路由配置
thinkphp
kertag6 天前
ThinkPHP 8 多应用入口绑定:BIND_MODULE vs $http->name() 全面解析
php·thinkphp
妙码生花18 天前
全新的 TP8+Workerman+BuildAdmin 整合方案,已有近 2000 次下载使用。
websocket·php·thinkphp
quweiie19 天前
在php8.3下签到、签退打卡的实现
thinkphp·签到·nesbot/carbon
天宁2 个月前
Workerman + ThinkPHP 8 结合使用
php·thinkphp
云游云记2 个月前
ThinkPHP 队列扩展 (topthink/think-queue) 使用笔记
php·thinkphp·think-queue
用户14644605033793 个月前
PHP 多维数组处理利器:array_column() 用法详解
php·thinkphp
用户3074596982073 个月前
ThinkPHP 6.0 多应用模式下的中间件机制详解
后端·thinkphp
行思理4 个月前
小游戏系统提供二开服务
layui·游戏程序·小游戏·thinkphp
xmode4 个月前
常用自定义函数laravel版+thinkphp版
后端·php·laravel·thinkphp