Laravel?Swagger?使用超詳細(xì)教程
一、Swagger 基礎(chǔ)
1、 什么是Swagger
Swagger 是一個(gè)基于 Open Api 規(guī)范的 API 管理工具,通過項(xiàng)目注解的形式自動(dòng)構(gòu)建 API 文檔,擁有在線調(diào)試的功能。提供了多語言的客戶端,laravel 中也有相應(yīng)的擴(kuò)展包。
darkaonline/l5-swagger是一款針對(duì) laravel 集成開發(fā)的擴(kuò)展包,可以直接使用 laravel 命令行模式進(jìn)行操作。
我是正巧用的是laravel框架,所以選了darkaonline/l5-swagger擴(kuò)展,而zircote/swagger-php擴(kuò)展是適用于所有php語言的框架(使用方法可以參考這里,點(diǎn)擊前往。這里只介紹darkaonline/l5-swagger擴(kuò)展的使用
2、 安裝過程
這是它的安裝環(huán)境和依賴:
1 、composer安裝
composer require darkaonline/l5-swagger
2、添加服務(wù)提供者,引導(dǎo)框架運(yùn)行時(shí)加載,在 app 配置文件,providers 選項(xiàng)中添加(laravel 5以上忽略此步驟)
L5Swagger\L5SwaggerServiceProvider::class
3、配置完成后,通過輸入命令 php artisan 查看已經(jīng)發(fā)現(xiàn)該擴(kuò)展已經(jīng)加入 laravel 命令列表
4、生成命令
在沒有在任何控制器方法中添加注釋的時(shí)候,不要執(zhí)行該命令,否則會(huì)報(bào)致命性錯(cuò)誤
php artisan l5-swagger:generate
5、打開 API 文檔頁(yè)面
訪問網(wǎng)址: http://yourdomain/api/documentation,就能看到了
3、 注解介紹
由于 Swagger 是采用注解的形式進(jìn)行文檔生成,需要按照既定的規(guī)則去編寫注解,這里只提供一些重要的信息
請(qǐng)求
@OA\Get | @OA\Post:請(qǐng)求類型
path:請(qǐng)求URI
tag:歸納相同標(biāo)簽的接口
summary:接口概要
description:接口描述
operationId:接口ID,全局唯一
@OA\Parameter:接收的參數(shù)是來自requestHeader中,即請(qǐng)求頭。GET、\POST都適用
@OA\RequestBody:接收的參數(shù)是來自requestBody中,即請(qǐng)求體。主要用來接收前端傳遞給后端的json字符串中的數(shù)據(jù)的,所以只能發(fā)送POST請(qǐng)求
注意:匹配path中的數(shù)值則 in path 查詢 in query
/** * @OA\Post( * path="/api/resource/detail/{id}", * operationId="getProjectById", * tags={"Resource相關(guān)"}, * summary="資源詳情", * description="獲取資源的詳細(xì)信息的接口", * 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:因?yàn)楝F(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="獲取項(xiàng)目列表的接口,調(diào)用接口需要傳遞token令牌", * security={{"Bearer":{} }}, * @OA\Parameter( * name="page", * description="頁(yè)碼,默認(rèn)為1", * required=false, * in="query", * ), * @OA\Parameter( * name="pagesize", * description="每頁(yè)的數(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ā)布時(shí)間"), * ), * ) * ), * @OA\Response(response=400, description="Bad request"), * @OA\Response(response=404, description="Resource Not Found"), * ) */
二、Swagger 實(shí)戰(zhàn)
1、修改配置
根據(jù)以上流程,已經(jīng)安裝了擴(kuò)展,并對(duì)注釋的使用也有了一定的了解,那就來具體實(shí)戰(zhàn)吧(本人項(xiàng)目用到了JWT,未用到的可自行跳過)。
- 如果不想每次修改后都手動(dòng)執(zhí)行生成命令,可以通過修改 env 文件,添加配置項(xiàng)
L5_SWAGGER_GENERATE_ALWAYS=true
- 因?yàn)槲业膖oken令牌是以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)識(shí)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、驗(yàn)證提供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": {}}},
這時(shí),swagger Ui 會(huì)出現(xiàn)一個(gè)鎖一樣的東西,
在這里,可以輸入自己的token,請(qǐng)求的時(shí)候會(huì)帶上token。當(dāng)token輸入以后點(diǎn)擊認(rèn)證,這時(shí)候需要驗(yàn)證token的接口,都會(huì)被鎖上,就是出現(xiàn)這個(gè)鎖的樣式,如圖:
然后你try 接口的時(shí)候,就會(huì)帶上你剛剛輸入的token,這時(shí)可以在你的接口中間件中去接收并驗(yàn)證token的有效性了。
2、post請(qǐng)求
備注:配置項(xiàng)security={{“Bearer”:{} }},:該項(xiàng)就是說明該接口需要安全驗(yàn)證,且用到的是Bearer方式
/** * @OA\Post( * path="/api/resource/list", * tags={"Resource相關(guān)"}, * summary="資源列表", * description="獲取項(xiàng)目列表的接口,調(diào)用接口需要傳遞token令牌", * security={{"Bearer":{} }}, * @OA\Parameter( * name="page", * description="頁(yè)碼,默認(rèn)為1", * required=false, * in="query", * ), * @OA\Parameter( * name="pagesize", * description="每頁(yè)的數(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ā)布時(shí)間"), * ), * ) * ), * @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請(qǐng)求
/** * @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)計(jì)答題時(shí)長(zhǎng)",path="/api/behavior/count_answer_time",tags={"行為埋點(diǎn)"},description="統(tǒng)計(jì)用戶答題時(shí)長(zhǎ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)識(shí)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、文件上傳
備注:這里是支持多文件上傳,刪除一個(gè)就是單文件上傳
/** * @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 配置的問題,因?yàn)?,laravel-swagger 是通過file_content_get() 的方式 echo 輸出js 的。而你的nginx 配置判斷,如果是 .js 或者css 是靜態(tài)文件,所以到不了index.php ,更執(zhí)行不了 file_content_get 函數(shù)了。
這時(shí)候去掉js的緩存
2、ErrorException : Required @OA\Info() not found
在終端輸入命令
php artisan l5-swagger:generate
提示異常:
這是因?yàn)樵谶\(yùn)行之前,您必須在控制器中至少有一個(gè)方法,并帶有描述路由的注釋
<?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使用測(cè)試", version="1.0") */ class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; }
然后使用命令php artisan make:controller ProjectsController生成一個(gè)控制器,隨便寫個(gè)方法,然后在方法前添加注釋即可:
/** * @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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Grunt插件之LiveReload實(shí)現(xiàn)頁(yè)面自動(dòng)刷新(兩種方案)
這篇文章主要通過兩種方案詳解Grunt插件之LiveReload實(shí)現(xiàn)頁(yè)面自動(dòng)刷新,需要的朋友可以參考下2015-07-07laravel 驗(yàn)證錯(cuò)誤信息到 blade模板的方法
今天小編就為大家分享一篇laravel 驗(yàn)證錯(cuò)誤信息到 blade模板的方法,具有很好的參考價(jià)值。希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-09-09PHP批量刪除、清除UTF-8文件BOM頭的代碼實(shí)例
這篇文章主要介紹了PHP批量刪除、清除UTF-8文件BOM頭的代碼實(shí)例,需要的朋友可以參考下2014-04-04thinkPHP框架單元測(cè)試庫(kù)tpunit用法示例
這篇文章主要介紹了thinkPHP框架單元測(cè)試庫(kù)tpunit用法,結(jié)合實(shí)例形式分析了tpunit簡(jiǎn)單使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2018-08-08laravel實(shí)現(xiàn)上傳圖片,并且制作縮略圖,按照日期存放的代碼
今天小編就為大家分享一篇laravel實(shí)現(xiàn)上傳圖片,并且制作縮略圖,按照日期存放的代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-10-10PHP實(shí)現(xiàn)與java 通信的插件使用教程
這篇文章主要介紹了PHP與java 通信插件,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。2019-08-08