swagger php 生成文档,Swagger 生成 PHP API 接口文档

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 结果如图:

18026bb32361649010d486d57e56ccf0.png

4、参考资料

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值