Swagger 生成 PHP API 接口文档

52次阅读

共计 1844 个字符,预计需要花费 5 分钟才能阅读完成。

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、参考资料

Swagger 生成 PHP restful API 接口文档
如何编写基于 Swagger-PHP 的 API 文档
https://github.com/zircote/swagger-php
https://github.com/swagger-api/swagger-ui
Easy Mock
Laravel(PHP)使用 Swagger 生成 API 文档不完全指南

正文完
 0