Laravel?Swagger?使用超詳細教程
一、Swagger 基礎(chǔ)
1、 什么是Swagger
Swagger 是一個基于 Open Api 規(guī)范的 API 管理工具,通過項目注解的形式自動構(gòu)建 API 文檔,擁有在線調(diào)試的功能。提供了多語言的客戶端,laravel 中也有相應(yīng)的擴展包。
darkaonline/l5-swagger是一款針對 laravel 集成開發(fā)的擴展包,可以直接使用 laravel 命令行模式進行操作。

我是正巧用的是laravel框架,所以選了darkaonline/l5-swagger擴展,而zircote/swagger-php擴展是適用于所有php語言的框架(使用方法可以參考這里,點擊前往。這里只介紹darkaonline/l5-swagger擴展的使用
2、 安裝過程
這是它的安裝環(huán)境和依賴:

1 、composer安裝
composer require darkaonline/l5-swagger
2、添加服務(wù)提供者,引導(dǎo)框架運行時加載,在 app 配置文件,providers 選項中添加(laravel 5以上忽略此步驟)
L5Swagger\L5SwaggerServiceProvider::class
3、配置完成后,通過輸入命令 php artisan 查看已經(jīng)發(fā)現(xiàn)該擴展已經(jīng)加入 laravel 命令列表

4、生成命令
在沒有在任何控制器方法中添加注釋的時候,不要執(zhí)行該命令,否則會報致命性錯誤
php artisan l5-swagger:generate
5、打開 API 文檔頁面
訪問網(wǎng)址: http://yourdomain/api/documentation,就能看到了

3、 注解介紹
由于 Swagger 是采用注解的形式進行文檔生成,需要按照既定的規(guī)則去編寫注解,這里只提供一些重要的信息
請求
@OA\Get | @OA\Post:請求類型
path:請求URI
tag:歸納相同標(biāo)簽的接口
summary:接口概要
description:接口描述
operationId:接口ID,全局唯一
@OA\Parameter:接收的參數(shù)是來自requestHeader中,即請求頭。GET、\POST都適用
@OA\RequestBody:接收的參數(shù)是來自requestBody中,即請求體。主要用來接收前端傳遞給后端的json字符串中的數(shù)據(jù)的,所以只能發(fā)送POST請求
注意:匹配path中的數(shù)值則 in path 查詢 in query
/**
* @OA\Post(
* path="/api/resource/detail/{id}",
* operationId="getProjectById",
* tags={"Resource相關(guān)"},
* summary="資源詳情",
* description="獲取資源的詳細信息的接口",
* security={{"Bearer":{} }},
* @OA\Parameter(
* name="from",
* description="引流的來源",
* required=false,
* in="query",
* ),
* @OA\Parameter(
* name="id",
* description="Resource id",
* required=true,
* in="path",
* @OA\Schema(
* type="integer"
* )
* ),
* )
*/- 響應(yīng)
@OA\Response:響應(yīng)信息
response:響應(yīng)的 http 狀態(tài)碼
description:響應(yīng)描述
@OA\MediaType:響應(yīng)體
mediaType:返回格式
@OA\Schema:定義響應(yīng)體內(nèi)的數(shù)據(jù)
@OA\Property:定義屬性字段(id),數(shù)據(jù)類型(string),字段描述(description)
@OA\JsonContent:因為現(xiàn)在接口通常采用 json 通訊,所以可以直接定義 json 響應(yīng)格式
ref:指定可復(fù)用的注解模塊,TestApi 為模塊ID,全局唯一
@OA\Schema:可復(fù)用注解模塊,內(nèi)部可嵌套 Schema
/**
* @OA\Post(
* path="/api/resource/list",
* tags={"Resource相關(guān)"},
* summary="資源列表",
* description="獲取項目列表的接口,調(diào)用接口需要傳遞token令牌",
* security={{"Bearer":{} }},
* @OA\Parameter(
* name="page",
* description="頁碼,默認(rèn)為1",
* required=false,
* in="query",
* ),
* @OA\Parameter(
* name="pagesize",
* description="每頁的數(shù)量,默認(rèn)5條",
* required=false,
* in="query",
* ),
*
* @OA\Response(
* response=200,
* description="successful",
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(
* @OA\Property(property="id", type="integer", description="資源ID"),
* @OA\Property(property="type", type="integer", description="資源類型,1=>病例,2=>文章"),
* @OA\Property(property="title", type="string", description="資源名稱"),
* @OA\Property(property="cover", type="string", description="資源封面圖"),
* @OA\Property(property="view_count", type="integer", description="瀏覽量"),
* @OA\Property(property="created_at", type="string", description="發(fā)布時間"),
* ),
* )
* ),
* @OA\Response(response=400, description="Bad request"),
* @OA\Response(response=404, description="Resource Not Found"),
* )
*/
二、Swagger 實戰(zhàn)
1、修改配置
根據(jù)以上流程,已經(jīng)安裝了擴展,并對注釋的使用也有了一定的了解,那就來具體實戰(zhàn)吧(本人項目用到了JWT,未用到的可自行跳過)。
- 如果不想每次修改后都手動執(zhí)行生成命令,可以通過修改 env 文件,添加配置項
L5_SWAGGER_GENERATE_ALWAYS=true
- 因為我的token令牌是以Authorization bearer XXXXX傳遞的,所以要增加securitySchemes,在配置文件l5-swagger.php中,修改如下:
/*
* API security definitions. Will be generated into documentation file.
*/
'securityDefinitions' => [
'securitySchemes' => [
'Bearer' => [ // 這是我要用到的Schemes
'type' => 'apiKey', // Valid values are "basic", "apiKey" or "oauth2".
'description' => 'Enter token in format (Bearer <token>)',
'name' => 'Authorization', // The name of the header or query parameter to be used.
'in' => 'header', // The location of the API key. Valid values are "query" or "header".
],
/*
* Examples of Security schemes
*/
/*
'api_key_security_example' => [ // Unique name of security
'type' => 'apiKey', // The type of the security scheme. Valid values are "basic", "apiKey" or "oauth2".
'description' => 'A short description for security scheme',
'name' => 'api_key', // The name of the header or query parameter to be used.
'in' => 'header', // The location of the API key. Valid values are "query" or "header".
],
'oauth2_security_example' => [ // Unique name of security
'type' => 'oauth2', // The type of the security scheme. Valid values are "basic", "apiKey" or "oauth2".
'description' => 'A short description for oauth2 security scheme.',
'flow' => 'implicit', // The flow used by the OAuth2 security scheme. Valid values are "implicit", "password", "application" or "accessCode".
'authorizationUrl' => 'http://example.com/auth', // The authorization URL to be used for (implicit/accessCode)
//'tokenUrl' => 'http://example.com/auth' // The authorization URL to be used for (password/application/accessCode)
'scopes' => [
'read:projects' => 'read your projects',
'write:projects' => 'modify projects in your account',
]
],
*/
/* Open API 3.0 support
'passport' => [ // Unique name of security
'type' => 'oauth2', // The type of the security scheme. Valid values are "basic", "apiKey" or "oauth2".
'description' => 'Laravel passport oauth2 security.',
'in' => 'header',
'scheme' => 'https',
'flows' => [
"password" => [
"authorizationUrl" => config('app.url') . '/oauth/authorize',
"tokenUrl" => config('app.url') . '/oauth/token',
"refreshUrl" => config('app.url') . '/token/refresh',
"scopes" => []
],
],
],*/
],
],2、使用示例
Swagger的使用就是在你的控制器里的方法前面加上注釋,示例如下:
<?php
namespace App\Http\Controllers\Api;
class TokenController extends Controller
{
/**
* @OA\Post(
* path="/api/common/token",
* tags={"公共接口"},
* summary="token令牌",
* description="獲取用戶token令牌",
* @OA\Parameter(
* name="type",
* description="類型,有token、user兩種",
* required=true,
* in="query",
* @OA\Schema(
* type="string"
* )
* ),
* @OA\Parameter(
* name="user_id",
* description="用戶唯一標(biāo)識id",
* required=true,
* in="query",
* ),
* @OA\Response(
* response=200,
* description="successful operation"
* ),
* )
*/
public function postToken(){
//邏輯
return $this->success(
[
'access_token' => $token,
'token_type' => 'bearer',
]);
}
}1、驗證提供outh2 或和apikey 兩種方式,在存放全局配置中寫入(也可以任意目錄中)。
我是放在了最基礎(chǔ)的controller中
備注:具體的可以點擊這里去了解
<?php
namespace App\Http\Controllers\Api;
use App\Traits\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
/**
* @SWG\SecurityScheme(
* securityDefinition="Bearer",
* in="header",
* name="Authorization",
* type="apiKey",
* ),
*/
class Controller extends BaseController
{
public $request;
public function __construct(Request $request){
$this->request = $request;
}
}在接口中添加:
security={{"Bearer": {}}},這時,swagger Ui 會出現(xiàn)一個鎖一樣的東西,

在這里,可以輸入自己的token,請求的時候會帶上token。當(dāng)token輸入以后點擊認(rèn)證,這時候需要驗證token的接口,都會被鎖上,就是出現(xiàn)這個鎖的樣式,如圖:

然后你try 接口的時候,就會帶上你剛剛輸入的token,這時可以在你的接口中間件中去接收并驗證token的有效性了。
2、post請求
備注:配置項security={{“Bearer”:{} }},:該項就是說明該接口需要安全驗證,且用到的是Bearer方式
/**
* @OA\Post(
* path="/api/resource/list",
* tags={"Resource相關(guān)"},
* summary="資源列表",
* description="獲取項目列表的接口,調(diào)用接口需要傳遞token令牌",
* security={{"Bearer":{} }},
* @OA\Parameter(
* name="page",
* description="頁碼,默認(rèn)為1",
* required=false,
* in="query",
* ),
* @OA\Parameter(
* name="pagesize",
* description="每頁的數(shù)量,默認(rèn)5條",
* required=false,
* in="query",
* ),
*
* @OA\Response(
* response=200,
* description="successful",
* @OA\MediaType(
* mediaType="application/json",
* @OA\Schema(
* @OA\Property(property="id", type="integer", description="資源ID"),
* @OA\Property(property="type", type="integer", description="資源類型,1=>病例,2=>文章"),
* @OA\Property(property="title", type="string", description="資源名稱"),
* @OA\Property(property="cover", type="string", description="資源封面圖"),
* @OA\Property(property="view_count", type="integer", description="瀏覽量"),
* @OA\Property(property="created_at", type="string", description="發(fā)布時間"),
* ),
* )
* ),
* @OA\Response(response=400, description="Bad request"),
* @OA\Response(response=404, description="Resource Not Found"),
* )
*/
public function postList(){
$params = $this->request->all();
$params['page'] = $params['page'] ?? 1;
$params['pagesize'] = $params['pagesize'] ?? 5;
//邏輯
}
3、Get請求
/**
* @OA\Get(
* path="/projects/{id}",
* operationId="getProjectById",
* tags={"Projects"},
* summary="Get project information",
* description="Returns project data",
* @OA\Parameter(
* name="id",
* description="Project id",
* required=true,
* in="path",
* @OA\Schema(
* type="integer"
* )
* ),
* @OA\Response(
* response=200,
* description="successful operation"
* ),
* @OA\Response(response=400, description="Bad request"),
* @OA\Response(response=404, description="Resource Not Found"),
* },
* )
*/4、Body 為Json 方式
/**
* @OA\Post(summary="統(tǒng)計答題時長",path="/api/behavior/count_answer_time",tags={"行為埋點"},description="統(tǒng)計用戶答題時長",
* security={{"Bearer":{} }},
* @OA\Parameter(name="resource_id",in="query",required=true,description="資源id",
* @OA\Schema(
* type="integer"
* )),
* @OA\Parameter(name="log_id",in="query",required=true,description="當(dāng)下訪問記錄的唯一標(biāo)識id",
* @OA\Schema(
* type="integer"
* )),
* @OA\RequestBody(
* @OA\MediaType(mediaType="application/json",
* @OA\Schema(
* @OA\Property(property="ques_id",type="int",description="問題id"),
* @OA\Property(property="type",type="string",description="行為的類型:start和end兩種"),
* example={"ques_id": 10, "type": "start"}
* )
* )
* ),
* @OA\Response(response="200",description="獲取成功"),
* )
*/
public function countAnswerTime(){
info(json_encode($this->request->all()));
$resource_id = $this->request->get('resource_id');
$log_id = $this->request->get('log_id');
$all_params = $this->request->only(['resource_id', 'log_id']);
$current_type = $this->request->get('type');
//邏輯
}
5、文件上傳
備注:這里是支持多文件上傳,刪除一個就是單文件上傳
/**
* @OA\Post(summary="上傳文件",path="/api/upload/file/{type}",tags={"Upload"},description="上傳文件",
* security={{"Bearer":{} }},
* @OA\Parameter(name="type",in="path",required=true,description="類型"),
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* @OA\Property(property="file",type="file",description="文件"),
* @OA\Property(property="file2",type="file",description="文件2")
* )
* )
* ),
* @OA\Response(response="200",description="獲取成功",
* @OA\MediaType(mediaType="application/json",
* @OA\Schema(
* @OA\Property(property="img_url",description="路徑",type="string"),
* @OA\Property(property="original_name",description="原始名稱",type="string"),
* )
* )
* )
* )
*/
public function postUploadFile($case){
$file = $this->request->file('file');
//邏輯
}
更多的使用方法可以參考官網(wǎng)例子:https://github.com/zircote/swagger-php/tree/master/Examples/petstore-3.0
三、可能遇到的問題
1、線上環(huán)境無法正常訪問
可能是你nginx 配置的問題,因為,laravel-swagger 是通過file_content_get() 的方式 echo 輸出js 的。而你的nginx 配置判斷,如果是 .js 或者css 是靜態(tài)文件,所以到不了index.php ,更執(zhí)行不了 file_content_get 函數(shù)了。
這時候去掉js的緩存
2、ErrorException : Required @OA\Info() not found
在終端輸入命令
php artisan l5-swagger:generate
提示異常:

這是因為在運行之前,您必須在控制器中至少有一個方法,并帶有描述路由的注釋
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
/**
* @OA\Info(title="Swagger使用測試", version="1.0")
*/
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}然后使用命令php artisan make:controller ProjectsController生成一個控制器,隨便寫個方法,然后在方法前添加注釋即可:
/**
* @OA\Get(
* path="/projects",
* @OA\Response(response="200", description="Display a listing of projects.")
* )
*/
public function index(){
}然后再執(zhí)行php artisan l5-swagger:generate命令,就正常了

到此這篇關(guān)于Laravel Swagger 使用完整教程的文章就介紹到這了,更多相關(guān)Laravel Swagger 使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
布隆過濾器(bloom filter)及php和redis實現(xiàn)布隆過濾器的方法
這篇文章主要介紹了布隆過濾器(bloom filter)介紹以及php和redis實現(xiàn)布隆過濾器實現(xiàn)方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12
PHP根據(jù)傳入?yún)?shù)合并多個JS和CSS文件的簡單實現(xiàn)
這篇文章主要介紹了PHP合并多個JS和CSS文件的簡單實現(xiàn),本文使用了一種比較簡單的方法,重在揭示實現(xiàn)原理,需要的朋友可以參考下2014-06-06
Codeigniter實現(xiàn)多文件上傳并創(chuàng)建多個縮略圖
這篇文章主要介紹了Codeigniter實現(xiàn)多文件上傳并創(chuàng)建多個縮略圖,需要的朋友可以參考下2014-06-06

