在Ubuntu上生成Swagger文档的常见方法
在开始生成文档前,需安装Node.js和npm(Node.js包管理器),这是使用Swagger工具的前提:
sudo apt update
sudo apt install -y nodejs npm
Swagger Editor是可视化编辑OpenAPI规范的工具,适合快速创建和预览文档。
swagger-editor.zip),解压后在目录下运行http-server(需提前安装http-server:sudo npm install -g http-server),启动后访问http://localhost:8080。swagger.yaml/swagger.json文件或新建文档。若项目使用Go语言,可通过swag工具根据代码注释自动生成Swagger文档。
go install github.com/swaggo/swag/cmd/swag@latest
swag init,生成docs目录(包含docs.go、swagger.json、swagger.yaml等文件)。// @Summary 获取用户信息
// @Description 根据用户ID获取详细信息
// @Tags Users
// @Accept json
// @Produce json
// @Param id path int true "用户ID"
// @Success 200 {object} User
// @Router /users/{id} [get]
func GetUser(c *gin.Context) {
// 业务逻辑
}
swag init,工具会自动更新Swagger文档。若项目使用Spring Boot,可通过springdoc-openapi-ui依赖自动生成Swagger文档,适合Java项目。
pom.xml中添加以下依赖(以Maven为例):<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.14</version>
</dependency>
SwaggerConfig.java),启用Swagger并设置扫描路径:import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.OpenAPI;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("public")
.pathsToMatch("/**") // 扫描所有路径
.build();
}
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("Spring Boot Swagger API")
.version("1.0")
.description("API文档自动生成"));
}
}
http://localhost:8080/swagger-ui.html即可查看交互式文档。swagger-ui-express用于Node.js、flask-swagger-ui用于Python Flask)。