在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文檔。