在Linux上使用Swagger生成API文档,可以按照以下步骤进行:
sudo apt update
sudo apt install openjdk-11-jdk
验证安装:
java -version
sudo apt install maven
验证安装:
mvn -version
# 安装Docker
sudo apt-get update
sudo apt-get install -y docker.io
sudo systemctl start docker
sudo systemctl enable docker
# 拉取镜像
docker pull swaggerapi/swagger-ui:latest
docker pull swaggerapi/swagger-editor:latest
# 运行容器
docker run -d -p 8080:8080 swaggerapi/swagger-ui:latest
docker run -d -p 8081:8080 swaggerapi/swagger-editor:latest
访问Swagger Editor:http://localhost:8081
访问Swagger UI:http://localhost:8080
# 安装Node.js和npm
curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs
# 安装依赖
npm install -g express http-server
# 安装Swagger UI
git clone https://github.com/swagger-api/swagger-ui.git
cd swagger-ui
npm install
http-server -p 8080
# 安装Swagger Editor
git clone https://github.com/swagger-api/swagger-editor.git
cd swagger-editor
npm install
http-server -p 8081
访问Swagger UI:http://localhost:8080
访问Swagger Editor:http://localhost:8081
创建Swagger配置文件:创建一个swagger.yaml文件,定义API的元数据,包括路径、参数等信息。
集成到项目中:根据你的项目框架(如Spring Boot、Flask等),集成Swagger。以下是Spring Boot的示例:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
}
在你的代码中使用Swagger注解来描述API,例如:
@RestController
@RequestMapping("/api/users")
@Api(tags = "用户管理")
public class UserController {
@GetMapping("/{id}")
@ApiOperation(value = "根据用户ID获取用户信息", notes = "根据用户唯一标识查询用户详情")
public User getUserById(@PathVariable Long id) {
// ...
}
@GetMapping
public List<User> getUsers(@ApiParam(value = "用户名", required = true) @RequestParam String username) {
// ...
}
}
使用Swagger命令行工具生成API文档:
swagger generate spec -o ./swagger.json
启动Swagger UI以查看生成的文档:
swagger serve --no-open ./swagger.json
使用Swagger Editor在线编辑器设计或修改API规范。支持JSON和YAML格式,并提供实时错误提示:
# 下载并解压Swagger Editor
wget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.50.0.tar.gz
tar -xvf swagger-editor-3.50.0.tar.gz
cd swagger-editor-3.50.0
npm install
npm run start
# 访问Swagger Editor
http://localhost:9000
通过以上步骤,你可以在Linux上成功生成和查看API文档。