ThinkPHP 使用 SwaggerUi 自动生成 api 文档
1、下载swagger-ui
GitHub地址:https://github.com/swagger-api/swagger-ui
2、修改 ThinkPHP 的 build.php ,执行命令生成需要创建的模块
- // 定义api模块的自动生成 (按照实际定义的文件名生成)
- 'api' => [
- '__file__' => ['common.php'],
- '__dir__' => ['controller'],
- 'controller' => ['Passport'],
- 'model' => [],
- 'view' => [],
- ],
命令: php think build
3、修改刚刚生成的模块下的 config.php 文件
- return [
- 'default_return_type' => 'json', // 修改控制器默认输出json对象
- 'url_param_type' => 1, // URL参数方式 0 按名称成对解析 1 按顺序解析
- ];
4、在刚刚生成的 application/api/contorller/Passport.php 下添加这几个方法
- <?php
- namespace app\api\controller;
- /**
- * swagger: 登录相关
- */
- class Passport
- {
- /**
- * post: 发送验证码
- * path: sendVerify/{phone}/{deviceType}
- * method: sendVerify
- * param: phone - {string} 手机号
- * param: deviceType - {int} = [0|1|2|3|4] 设备类型(0: android手机, 1: ios手机, 2: android平板, 3: ios平板, 4: pc)
- */
- public function sendVerify($phone, $deviceType) {
- return [
- 'code' => 200,
- 'message' => '发送验证码',
- 'data' => [
- 'phone' => $phone,
- 'deviceType' => $deviceType
- ]
- ];
- }
- /**
- * post: 登陆
- * path: login
- * method: login
- * param: phone - {string} 手机号
- * param: password - {string} 密码
- * param: deviceType - {int} = [0|1|2|3|4] 设备类型(0: android手机, 1: ios手机, 2: android平板, 3: ios平板, 4: pc)
- * param: verifyCode - {string} = 0 验证码
- */
- public function login($phone, $password, $deviceType, $verifyCode = '0') {
- return [
- 'code' => 200,
- 'message' => '登陆成功',
- 'data' => [
- 'phone' => $phone,
- 'password' => $password,
- 'deviceType' => $deviceType,
- 'verifyCode' => $verifyCode
- ]
- ];
- }
- /**
- * get: 获取配置
- * path: profile
- * method: profile
- * param: keys - {string[]} 需要获取配置的Key值数组
- */
- public function profile($keys) {
- return [
- 'code' => 200,
- 'message' => '获取成功',
- 'data' => $keys
- ];
- }
- }
5、把 swagger-ui 目录下的 dist 放到你的 public 目录下,然后更名为 swagger。
6、修改 swagger 下 index.html 的路径:
- window.onload = function() {
- // Begin Swagger UI call region
- const ui = SwaggerUIBundle({
- url : window.location.href.replace(window.location.hash, "").replace(/[^/]+$/, "swagger.json"),
- dom_id: '#swagger-ui',
- deepLinking: true,
- presets: [
- SwaggerUIBundle.presets.apis,
- SwaggerUIStandalonePreset
- ],
- plugins: [
- SwaggerUIBundle.plugins.DownloadUrl
- ],
- layout: "StandaloneLayout"
- })
- // End Swagger UI call region
- window.ui = ui
- }
7、整合ThinkPHP 和 swaggerUI:
在 public 目录下新建 api.php
- <?php
- // +----------------------------------------------------------------------
- // | ThinkPHP SWAGGER [ 够用就好 ]
- // +----------------------------------------------------------------------
- // | Copyright (c) 2016 http://jitlee.com All rights reserved.
- // +----------------------------------------------------------------------
- // | Licensed ( http://jitlee.com/licenses/LICENSE-1.0 )
- // +----------------------------------------------------------------------
- // | Author: Jitlee.Wan <www.wpj@163.com>
- // +----------------------------------------------------------------------
- // 定义应用目录
- define('APP_PATH', __DIR__ . '/../application');
- $tags = array(); // Tags对象
- $paths = array(); // Path数组
- $module_dir = opendir(APP_PATH);
- while (($module_name = readdir($module_dir)) !== false) {
- if ($module_name != 'api') continue; //可以自己设置需要哪些模块用作api输出页面
- $module_path = APP_PATH . DIRECTORY_SEPARATOR . $module_name; //构建子目录路径
- if (is_dir($module_path)) {
- $module = strtolower($module_name);
- $module_child_dir = opendir($module_path);
- while (($module_child_name = readdir($module_child_dir)) !== false) {
- $module_child_path = $module_path . DIRECTORY_SEPARATOR . $module_child_name; //构建子目录路径
- if (is_dir($module_child_path) && $module_child_name == 'controller') {
- $controller_dir = opendir($module_child_path);
- while (($controller_file = readdir($controller_dir)) !== false) {
- $controller_path = $module_child_path . DIRECTORY_SEPARATOR . $controller_file; //构建子目录路径
- $controller_name = strtolower(basename($controller_path, '.php'));
- $contents = file_get_contents($controller_path);
- if (preg_match_all('/swagger:\s*([^\n]+)/i', $contents, $swagger_matches)) {
- // 添加tag
- $found_tag = false;
- foreach ($tags as $tag) {
- if ($tag['name'] == $controller_name) {
- $found_tag = true;
- break;
- }
- }
- if (!$found_tag) {
- array_push($tags, array(
- 'name' => $controller_name,
- 'description' => $swagger_matches[1][0]
- ));
- }
- // 添加path
- if (preg_match_all('/\/\*((?!\*\/).)+\*\//s', $contents, $func_matches)) {
- $length = count($func_matches[0]);
- if ($length > 1) {
- for ($i = 1; $i < $length; $i++) {
- $func_array = array();
- // 解析每个方法
- $func_contents = $func_matches[0][$i];
- // 方法说明
- if (!preg_match_all('/(get|post|delete)\s*:\s*([^\n]+)/i', $func_contents, $matches)) {
- break;
- }
- $method = $matches[1][0];
- $summary = $matches[2][0];
- // 路径
- if (!preg_match_all('/path\s*:\s*([^\n]+)/i', $func_contents, $matches)) {
- break;
- }
- $path = $matches[1][0];
- // 方法名称
- $operations = explode('/', $path);
- $operationId = $operations[0];
- if (preg_match_all('/method\s*:\s*([^\n]+)/i', $func_contents, $matches)) {
- $operationId = $matches[1][0];
- }
- $paths[$path] = array();
- $parameters = array();
- $func = array(
- 'tags' => [$controller_name],
- 'summary' => $summary,
- 'description' => '',
- 'operationId' => $operationId,
- 'produces' => ['application/json']
- );
- // 参数
- $pattern = '/param\s*:\s*(?<name>\w+)\s*-\s*\{(?<type>\w+(?<array>\[\])?)\}\s*(=\s*((\[(?<enum>[^]]+)\])|(?<default>[^\s]+))\s*)?(?<summary>[^*]+)/i';
- if (preg_match_all($pattern, $func_contents, $matches)) {
- $names = $matches['name']; // 参数名称
- $types = $matches['type']; // 参数类型
- $enums = $matches['enum']; // 参数枚举
- $defaults = $matches['default']; // 默认值
- $summarys = $matches['summary']; // 参数说明
- $arrays = $matches['array']; // 参数说明
- $params_count = count($names);
- for ($j = 0; $j < $params_count; $j++) {
- $in = $method == 'get' ? 'query' : 'formData';
- if (strpos($path, '{' . $names[$j] . '}') !== false) {
- $in = 'path';
- }
- $parameter = array(
- 'name' => $names[$j],
- 'in' => $in,
- 'required' => true,
- 'description' => $summarys[$j]
- );
- if ($defaults[$j] !== '') {
- $parameter['required'] = false;
- $parameter['defaultValue'] = $defaults[$j];
- }
- $type = str_replace('[]', '', $types[$j]);
- if ($type == 'int') {
- $type = 'integer';
- }
- if ($arrays[$j] != '') { // 是否数据参数
- $parameter['type'] = 'array';
- $parameter['items'] = array(
- 'type' => str_replace('[]', '', $type)
- );
- $parameter['collectionFormat'] = 'brackets'; // url带中括号
- // $parameter['collectionFormat'] = 'multi'; // url不带中括号
- } else if ($enums[$j] != '') { // 是否枚举参数
- $enum = explode('|', $enums[$j]);
- $parameter['type'] = $type;
- $parameter['enum'] = $enum;
- } else {
- $parameter['type'] = $type;
- }
- array_push($parameters, $parameter);
- }
- }
- $func['parameters'] = $parameters;
- // 生成api访问路径
- $paths['/' . $module . '/' . $controller_name . '/' . $path][$method] = $func;
- }
- }
- }
- }
- }
- closedir($controller_dir);
- }
- }
- closedir($module_child_dir);
- }
- }
- closedir($module_dir);
- $swagger = array(
- 'swagger' => '2.0',
- 'info' => array(
- 'description' => 'APP 后台服务',
- 'version' => '1.0.0',
- 'title' => '[我的APP]Swagger',
- 'termsOfService' => 'http://www.ritacc.cn/',
- 'contact' => array(
- 'email' => 'www.wpj@163.com'
- ),
- 'license' => array(
- 'name' => 'Apache 2.0',
- 'url' => 'http://www.apache.org/licenses/LICENSE-2.0.html'
- )
- ),
- 'host' => $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'],
- 'basePath' => '',
- 'tags' => $tags,
- 'schemes' => [
- 'http'
- ],
- 'paths' => $paths,
- 'securityDefinitions' => array(),
- 'definitions' => array(),
- 'externalDocs' => array(
- 'description' => 'Find out more about Swagger',
- 'url' => 'http://swagger.io'
- )
- );
- $jsonFile = fopen("swagger/swagger.json", "w") or die("Unable to open file!");
- fwrite($jsonFile, json_encode($swagger));
- fclose($jsonFile);
- // 跳转到Swagger UI
- $url = '/swagger/index.html';
- Header('HTTP/1.1 303 See Other');
- Header("Location: $url");
- exit;
8、打开浏览器运行 public 下的 api.php 就 ok 了。
ThinkPHP 使用 SwaggerUi 自动生成 api 文档的更多相关文章
- SpringBoot结合Swagger2自动生成api文档
首先在pom.xml中添加如下依赖,其它web,lombok等依赖自行添加 <dependency> <groupId>io.springfox</groupId> ...
- Spring Boot 项目学习 (四) Spring Boot整合Swagger2自动生成API文档
0 引言 在做服务端开发的时候,难免会涉及到API 接口文档的编写,可以经历过手写API 文档的过程,就会发现,一个自动生成API文档可以提高多少的效率. 以下列举几个手写API 文档的痛点: 文档需 ...
- springboot 集成 swagger 自动生成API文档
Swagger是一个规范和完整的框架,用于生成.描述.调用和可视化RESTful风格的Web服务.简单来说,Swagger是一个功能强大的接口管理工具,并且提供了多种编程语言的前后端分离解决方案. S ...
- 使用bee自动生成api文档
beego中的bee工具可以方便的自动生成api文档,基于数据库字段,自动生成golang版基于beego的crud代码,方法如下: 1.进入到gopath目录的src下执行命令: bee api a ...
- 自动生成api文档
vs2010代码注释自动生成api文档 最近做了一些接口,提供其他人调用,要写个api文档,可是我想代码注释已经写了说明,能不能直接把代码注释生成api?于是找到以下方法 环境:vs2010 先下载安 ...
- 试试使用 eolinker 扫描 GitLab 代码注释自动生成 API 文档?
前言: 一般写完代码之后,还要将各类参数注解写入API文档,方便后续进行对接和测试,这个过程通常都很麻烦,如果有工具可以读取代码注释直接生成API文档的话,那会十分方便. 此前一直都是在使用eolin ...
- go实践之swagger自动生成api文档
文章目录 go实践之swagger自动生成api文档 1.安装需要用到的包 2.接口代码支持swagger 3. 生成swagger接口 go实践之swagger自动生成api文档 作为一个后端开发, ...
- Django restful framework中自动生成API文档
自动生成api文档(不管是函数视图还是类视图都能显示) 1.安装rest_framework_swagger库 pip install django-rest-swagger 2.在项目下的 urls ...
- 【转】Django restful framework中自动生成API文档
转自 https://www.cnblogs.com/sui776265233/p/11350434.html 自动生成api文档(不管是函数视图还是类视图都能显示) 1.安装rest_framewo ...
随机推荐
- CodeForces 837F - Prefix Sums | Educational Codeforces Round 26
按tutorial打的我血崩,死活挂第四组- - 思路来自FXXL /* CodeForces 837F - Prefix Sums [ 二分,组合数 ] | Educational Codeforc ...
- .net core Areas区域
//使用MVC app.UseMvc(routes => { routes.MapRoute( name: "areas", template: "{area:ex ...
- Python 3 格式化字符串的几种方法!
Python 3 格式化字符串的几种方法! %s和%d,%s是用来给字符串占位置,%d是给数字占位置,简单解释下: a = 'this is %s %s' % ('an','apple') 程序输出的 ...
- 03 JavaScript的使用
01 注册界面的校验 <!-- 作者:offline 时间:2018-09-05 描述:通常在CSS中使用类选择器,在JS中使用id选择器,两者区分开. 在页面跳转时要先把要跳转的页面用浏览器打 ...
- Visual Stdio的使用
以下基于vs2017版本 part 1: 问题及解决 1.命令窗口一闪而过 右键项目,选择属性--连接器---系统---子系统---选择控制台. 2.修改默认启动项目 右键解决方案,选择属性,选择当前 ...
- CSP-S 模拟测试 45 题解
由于咕掉的题解太多了,所以只能趁改完不动题的时间,来补补坑qwq,还是太弱了. 考试过程: 到新机房的第一次考试,貌似海星? 第一题一开始就觉得是个贪心,但以为所有小怪兽都要打完,所以想复杂了,但后来 ...
- 从斐波那契数列看java方法的调用过程
先看斐波那契数列的定义: 斐波那契数列(Fibonacci sequence),又称黄金分割数列.因数学家列昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入,故又称为 ...
- 数据结构实验之链表二:逆序建立链表(SDUT 2117)
题目链接 #include <bits/stdc++.h> using namespace std; struct node { int data; struct node *next; ...
- Jmeter(十三)阶梯式压测
阶梯式压测,就是对系统的压力呈现阶梯性增加的过程,每个阶段压力值都要增加一个数量值,最终达到一个预期值.然后保持该压力值,持续运行一段时间. Jmeter中有个插件可以实现这个场景,这个插件就是:Co ...
- Difference Between static and default methods in interface
I was learning through interfaces when I noticed that you can now define static and default methods ...