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

相关推荐
qq3186929963 天前
ThinkPHP + Supervisor 队列任务丢失:僵尸 Worker 排查全记录
服务器·thinkphp·宝塔
linlinlove23 天前
前端uniapp、后端thinkphp股票系统开发功能展示、代码披露、HQChart
前端·uni-app·echarts·thinkphp·hqchart·配资·deepseek选股票
SuperherRo23 天前
服务攻防-开发框架安全&ThinkPHP&Laravel&SpringBoot&Struts2&SpringCloud&复现
spring boot·laravel·thinkphp·struts2·框架安全
quweiie25 天前
thinkphp8生成海报
thinkphp·海报
云游云记2 个月前
FastAdmin 路由完全开启教程:去掉 index 前缀 + 优雅路由配置
thinkphp
kertag2 个月前
ThinkPHP 8 多应用入口绑定:BIND_MODULE vs $http->name() 全面解析
php·thinkphp
妙码生花2 个月前
全新的 TP8+Workerman+BuildAdmin 整合方案,已有近 2000 次下载使用。
websocket·php·thinkphp
quweiie2 个月前
在php8.3下签到、签退打卡的实现
thinkphp·签到·nesbot/carbon
天宁4 个月前
Workerman + ThinkPHP 8 结合使用
php·thinkphp
云游云记4 个月前
ThinkPHP 队列扩展 (topthink/think-queue) 使用笔记
php·thinkphp·think-queue