一、找到swagger的包
我们访问packagist网站,搜索swagger,这里我们选择下载量最多的包
二、安装swagger-ui
cd public
在public目录下
git clone https://github.com/swagger-api/swagger-ui
git clone拷贝完之后呢,其实我们只需要 dist
目录就行,其他的目录以及文件可以删掉
三、使用
创建SwaggerController
配置数据
php artisan make:controller SwaggerController
SwaggerController:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Swagger\Annotations\Info;
use Swagger\Annotations\OA;
/**
* @OA\Info(title="My First API", version="0.1")
*/
/**
* @OA\Get(
* path="/api/resource.json",
* @OA\Response(response="200", description="An example resource")
* )
*/
class SwaggerController extends Controller
{
public function doc()
{
$swagger = \OpenApi\scan(app_path('Http/Controllers/Api'));
return response()->json($swagger);
}
}
同时配置路由
/**
* Swagger-UI
*/
Route::get('/swagger/doc', 'SwaggerController@doc');
修改public/dist/index.html
window.onload = function() {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
// url: "https://petstore.swagger.io/v2/swagger.json",
url: "/swagger/doc", //新的配置
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
}
这样配置完毕,就可以直接通过/swagger-ui/dist/index.html
路径来访问到swagger文档了
四、示例
/**
* @OA\Tag(
* name="user",
* description="用户模块",
* )
*/
class UserController extends Controller
{
/**
* @OA\Post(
* path="/api/login",
* tags={"user"},
* summary="登录",
* @OA\Parameter(name="isFastLogin", in="query", @OA\Schema(type="boolean")),
* @OA\Parameter(name="tel", in="query", @OA\Schema(type="string")),
* @OA\Parameter(name="verification_code", in="query", @OA\Schema(type="string")),
* @OA\Parameter(name="password", in="query", @OA\Schema(type="string")),
* @OA\Response(response=200, description=" {err_code: int32, msg:string, data:[]} "
* )
* )
*/
public function login(Request $request)
{
}
}
更多使用方法参考:https://github.com/zircote/swagger-php/blob/master/docs/Getting-started.md
当然,要注意的是部分注解已经在新版本的swagger中弃用了,详细请看:https://github.com/zircote/swagger-php/blob/master/docs/Migrating-to-v3.md
demo可以参考:https://github.com/zircote/swagger-php/tree/master/Examples/petstore.swagger.io
参考博客:https://ld246.com/article/1548065819985