1. 程式人生 > >Swagger 生成 PHP API 介面文件

Swagger 生成 PHP API 介面文件

Swagger 生成 PHP API 介面文件

標籤(空格分隔): php


1、概況

有同學反饋寫幾十個介面文件需要兩天的工作量, 隨著多部門之間的協作越來越頻繁, 維護成本越來越高, 文件的可維護性越來越差, 需要一個工具來管理這些介面的文件, 並能夠充當mock server給呼叫方使用。

有同學推薦了swagger+easymock,Swagger是一個簡單但功能強大的API表達工具。 這裡介紹使用swagger-php生成PHP API文件的方法。

2、安裝與使用

2.1 安裝swagger-php包


git clone https://github.com/zircote/swagger-php.git

composer install

// 全域性的
composer global require zircote/swagger-php

// 專案中
composer global require zircote/swagger-php

2.2 laravel專案安裝

使用 L5 Swagger https://github.com/DarkaOnLine/L5-Swagger

具體安裝過程請參考此文件: https://github.com/DarkaOnLin...

2.3 編寫API註解

# 建立檔案 demo/customer.php
<?php

/**
 * @OA\Info(title="My First API", version="0.1")
 */
class Customer
{
    /**
     * @OA\Get(
     *     path="/customer/info",
     *     summary="使用者的個人資訊",
     *     description="這不是個api介面,這個返回一個頁面",
     *     @OA\Parameter(name="userId", in="query", @OA\Schema(type="string"), required=true, description="使用者ID"),
     *     @OA\Response(
     *      response="200",
     *      description="An example resource"
     *     )
     * )
     */
    public function info(int $userId, string $userToken)
    {

    }
}

2.4 生成swagger API 檔案


./swagger-php/bin/openapi demo -o ./docs

API 內容如下:


# docs/openapi.yaml
openapi: 3.0.0
info:
  title: 'My First API'
  version: '0.1'
paths:
  /customer/info:
    get:
      summary: 使用者的個人資訊
      description: '這不是個api介面,這個返回一個頁面'
      operationId: 'Customer::info'
      parameters:
        -
          name: userId
          in: query
          description: 使用者ID
          required: true
          schema:
            type: string
      responses:
        '200':
          description: 'An example resource'

3、展示


git clone https://github.com/swagger-api/swagger-ui.git

composer install

直接通過Dockerfile構建、啟動專案, 或者使用docker-compose進行服務管理。


version: '2'

services:
    swagger-ui:
      build: .
      ports:
        - "8080:8080"
      volumes:
        - ./dist/:/usr/share/nginx/html/
      restart: on-failure

訪問 http://localhost:8080/ 即可到 swagger 編輯器預覽介面。


./swagger-php/bin/openapi demo -o ./swagger-ui/dist/

將 api文件輸出值swagger ui的根目錄下,可通過 http://localhost:8080/openapi.yaml 訪問此api文件。

執行 Explore 結果如圖:

4、參考資料

原文地址:https://segmentfault.com/a/1190000016735909