Laravel使用swagger PHP生成api接口文檔

Laravel使用swagger PHP生成api接口文檔php

Swagger集接口文檔和測試於一體,就類比將postman和showdoc的結合體laravel

首先要先安裝基於laravel5的swagger包git

地址:github.com/DarkaOnLine…github

1、安裝web

Laravel Swagger UI OpenAPI Spec compatibility L5-Swagger
5.1.x 2.2 1.1, 1.2, 2.0 php composer require "darkaonline/l5-swagger:~3.0"
5.2.x 2.2 1.1, 1.2, 2.0 php composer require "darkaonline/l5-swagger:~3.0"
5.3.x 2.2 1.1, 1.2, 2.0 php composer require "darkaonline/l5-swagger:~3.0"
5.4.x 2.2 1.1, 1.2, 2.0 php composer require "darkaonline/l5-swagger:~4.0"
5.4.x 3 2.0 php composer require "darkaonline/l5-swagger:5.4.*"
5.5.x 3 2.0, 3.0 php composer require "darkaonline/l5-swagger:5.5.*"
5.6.x 3 2.0, 3.0 php composer require "darkaonline/l5-swagger:5.6.*"

2、json

php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"複製代碼

3、Open your AppServiceProvider (located in app/Providers) and add this line in register functionapi

$this->app->register(\L5Swagger\L5SwaggerServiceProvider::class);複製代碼

or open your config/app.php and add this line in providers sectionbash

L5Swagger\L5SwaggerServiceProvider::class,
複製代碼

我仍在使用Swagger @SWG註釋

若是在項目中仍然使用Swagger @SWG註釋,您應該:app

swagger-php經過運行如下命令在您的項目做曲家中明確要求版本2. *:composer

composer require 'zircote/swagger-php:2.*'複製代碼

在你的config/l5-swagger.php

'swagger_version' => env('SWAGGER_VERSION', '2.0'),複製代碼

創建swaggerController控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Swagger\Annotations as SWG;

class SwaggerController extends Controller
{
    /**
     * @SWG\Swagger(
     *     schemes={"http","https"},
     *     host="api.host.com",
     *     basePath="/",
     *     @SWG\Info(
     *         version="1.0.0",
     *         title="This is my website cool API",
     *         description="Api description...",
     *         termsOfService="",
     *     ),
     * )
     */

    public function getJSON()
    {
        // 正式環境(production)訪問swagger文檔時返回空
        if (config('app.env') == 'production') {
            return response()->json([], 200);
        }

        $swagger = \Swagger\scan(app_path('/'));

        return response()->json($swagger, 200);
    }
}
複製代碼

在routes/web.php下加入以下代碼

Route::get('/swagger', function () {
    return view('vendor.l5-swagger.index',['urlToDocs' => '/doc/json']);
});
Route::group(['prefix' => 'doc'], function () {
    Route::get('json', 'SwaggerController@getJSON');
});複製代碼

經過你的域名/swager能夠訪問到接口、域名/doc/json訪問到的是json

http://*****.com/swagger#/article/article.list 要想顯示article.list 則須要添加deepLinking: true

創建BaseController

<?php

namespace App\Http\Controllers\V1;


use App\Http\Controllers\Controller ;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

class BaseController extends Controller
{
    use AuthenticatesUsers ;



    /**
     * @SWG\Swagger(
     *   host="",
     *   basePath="/api/v1",
     *   @SWG\Info(
     *     title="app",
     *     version="1.0.0"
     *   ),
     * @SWG\SecurityScheme(
     *   securityDefinition="api_key",
     *   type="apiKey",
     *   in="header",
     *   description = "認證token Bearer+空格+token",
     *   name="Authorization"
     * ),
     * )
     */
    public function __construct()
    {

    }

}
複製代碼

這樣基本swagger文檔就搭建成功了

每一個接口編寫 swagger 格式的註釋會有不少種、下面舉幾個例子

Get請求

/**
     * @SWG\Get(
     *      path="/article/list",
     *      tags={"article"},
     *      operationId="article.list",
     *      summary="獲取知識庫列表(分頁)",
     *      consumes={"application/json"},
     *      produces={"application/json"},
     *      security={{"api_key": {"scope"}}},
     *      @SWG\Parameter(in="query",name="page",description="頁碼",required=false,type="integer",),
     *      @SWG\Parameter(in="query",name="title",description="知識庫標題",required=false,type="string",),
     *      @SWG\Parameter(in="query",name="type_id",description="類型id",required=false,type="integer",),
     *      @SWG\Parameter(in="query",name="pid",description="產品編號",required=false,type="string",),
     *      @SWG\Response(
     *          response=200,
     *          description="",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(property="code", type="string",description="狀態碼"),
     *              @SWG\Property(property="message", type="string",description="提示信息"),
     *              @SWG\Property(property="data", type="object",
     *                  @SWG\Property(property="current_page", type="string", description="如今的頁碼"),
     *                  @SWG\Property(property="first_page_url", type="string", description="第一頁URL"),
     *                  @SWG\Property(property="from", type="integer", description="開始"),
     *                  @SWG\Property(property="last_page", type="string", description="最後一頁頁碼"),
     *                  @SWG\Property(property="last_page_url", type="string", description="最後一頁url"),
     *                  @SWG\Property(property="next_page_url", type="integer", description="下一頁url"),
     *                  @SWG\Property(property="path", type="string",description="路徑"),
     *                  @SWG\Property(property="per_page", type="integer", description="每頁顯示數量"),
     *                  @SWG\Property(property="prev_page_url", type="string",description="上一頁地址"),
     *                  @SWG\Property(property="to", type="integer", description="結束"),
     *                  @SWG\Property(property="total", type="integer", description="總條數"),
     *                  @SWG\Property(property="lists", type="array",
     *                      @SWG\Items(type="object",
     *                          @SWG\Property(property="aid", type="string",description="知識庫編號"),
     *                          @SWG\Property(property="title", type="string",description="標題"),
     *                          @SWG\Property(property="content", type="string",description="內容"),
     *                          @SWG\Property(property="created_at", type="string",description="建立時間"),
     *                          @SWG\Property(property="views", type="integer",description="瀏覽數量"),
     *                          @SWG\Property(property="product_name", type="string",description="產品名稱"),
     *                          @SWG\Property(property="type_name", type="string",description="類型名稱"),
     *                      ),
     *                  ),
     *              ),
     *          )
     *      ),
     * )
     */複製代碼

get請求效果以下:

Post請求

/**
     * @SWG\Post(
     *      path="/article/create",
     *      tags={"article"},
     *      operationId="create_article",
     *      summary="建立知識庫",
     *      consumes={"application/json"},
     *      produces={"application/json"},
     *      security={{"api_key": {"scope"}}},
     *      @SWG\Parameter(
     *          in="body",
     *          name="data",
     *          description="",
     *          required=true,
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(property="pid",description="產品編號",type="string"),
     *              @SWG\Property(property="uids",type="array",
     *                  @SWG\Items(type="integer",description="成員編號"),
     *              ),
     *          )
     *      ),
     *      @SWG\Response(
     *          response=200,
     *          description="",
     *          @SWG\Schema(
     *              type="object",
     *              @SWG\Property(property="code", type="string",description="狀態碼"),
     *              @SWG\Property(property="message", type="string",description="提示信息"),
     *          )
     *      ),
     * )
     */複製代碼

post請求效果以下:

接口描述 (@SWG\Get, @SWG\Post 等) 經常使用字段:

summary - string
接口的簡要介紹,會顯示在接口標頭上,不能超過120個字符
 
description - string
接口的詳細介紹
 
externalDocs - string
外部文檔連接
 
operationId - string
全局惟一的接口標識
 
consumes - [string]
接口接收的MIME類型
 
produces - [string]
接口返回的MIME類型,如 application/json
 
schemes -	[string]
接口所支持的協議,取值僅限: "http", "https", "ws", "wss"
 
parameters -	[Parameter Object | Reference Object]
參數列表複製代碼

參數描述 (@SWG\Parameter) 經常使用字段:

name - string
參數名. 經過路徑傳參(in 取值 "path")時有注意事項,沒用到,懶得看了...
 
in - string
參數從何處來. 必填. 取值僅限: "query", "header", "path", "formData", "body"
 
description - string
參數描述. 最好別太長
 
type - string
參數類型. 取值僅限: "string", "number", "integer", "boolean", "array", "file"
 
required - boolean
參數是否必須. 經過路徑傳參(in 取值 "path")時必須爲 true.複製代碼

暫時項目用到的大概就這些把,但願能夠對你們有幫助。

相關文章
相關標籤/搜索