在Ubuntu上生成Swagger API文档的常见流程
首先安装Node.js和npm(Node.js包管理器),这是使用Swagger工具的基础:
sudo apt update
sudo apt install -y nodejs npm
根据需求选择以下工具(任选其一即可):
sudo npm install -g swagger-ui
sudo npm install -g swagger-codegen
sudo npm install -g swagger-jsdoc
OpenAPI规范(OAS)是Swagger文档的基础,通常为swagger.yaml或swagger.json格式。可通过以下两种方式创建:
swagger.yaml):openapi: 3.0.0
info:
title: Sample API
version: 1.0.0
paths:
/users:
get:
summary: List all users
responses:
'200':
description: An array of users
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
swagger.yaml文件。若项目已有代码,可使用swagger-jsdoc从代码注释中提取API信息,生成OpenAPI规范:
swagger-jsdoc -c path/to/swagger-config.yaml -o path/to/output/swagger.json
其中,swagger-config.yaml是配置文件(定义注释解析规则),output/swagger.json是生成的规范文件。
若需要生成特定语言的客户端代码(如Java),可使用swagger-codegen:
swagger-codegen generate -i path/to/swagger.yaml -l java -o path/to/output/java-client
其中,-i指定输入规范文件,-l指定生成语言(如java、python),-o指定输出目录。
若使用Spring Boot等框架,可通过注解和插件自动生成文档:
pom.xml(Maven)中添加Swagger依赖:<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 指定Controller包
.paths(PathSelectors.any())
.build();
}
}
http://localhost:8080/swagger-ui.html即可查看交互式文档。swagger.yaml/swagger.json文件导入Swagger UI(可通过swagger-ui-express或其他工具托管),通过浏览器访问查看交互式文档(支持接口测试、参数填写等功能)。/swagger-ui.html即可查看实时文档(文档随代码更新自动刷新)。openapi版本、路径格式等),否则可能导致生成失败。@ApiOperation、@ApiParam),否则文档信息不完整。