首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Swagger 生成 PHP API 接口文档详细步骤

现在程序员写几十个接口文档需要两天的工作量, 随着多部门之间的协作越来越频繁, 维护成本越来越高, 文档的可维护性越来越差, 需要一个工具来管理这些接口的文档, 并能够充当mock server给调用方使用。

Swagger是一个简单但功能强大的API表达工具。 这里介绍使用swagger-php生成PHP API文档的方法。

1.安装swagger-php包

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

// 全局的

composer global require zircote/swagger-php

// 项目中

composer global require zircote/swagger-php

2.laravel项目安装

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

3.编写API注解

# 创建文件 demo/customer.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)

{

}

}

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'

5.展示

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

如果你想和更多PHP大神交流,添加下方微信号,拉你入群

如果你想获得更多学习资料,添加下方微信号,送你资源

关注菲菲

带你入群,带你学习

更有资源免费送!

COME BABY

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20181019A1NV8U00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券