Swagger 生成 PHP API 接口文档

2022-12-13,,,,

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

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文档不完全指南

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

Swagger 生成 PHP API 接口文档的相关教程结束。

《Swagger 生成 PHP API 接口文档.doc》

下载本文的Word格式文档,以方便收藏与打印。