Swagger 生成 PHP API 接口文檔
Lumen微服務生成Swagger文檔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 結果如圖:

