在Linux系統(tǒng)中使用Swagger進(jìn)行API調(diào)試,可以按照以下步驟進(jìn)行:
安裝Swagger
- 安裝docker(如果尚未安裝):
sudo apt-get update sudo apt-get install -y docker.io sudo systemctl start docker sudo systemctl enable docker
- 拉取并運(yùn)行Swagger Editor:
docker pull swaggerapi/swagger-editor:v4.6.0 docker run -d -p 38080:8080 swaggerapi/swagger-editor:v4.6.0
- 拉取并運(yùn)行Swagger ui:
docker pull swaggerapi/swagger-ui:v4.15.5 docker run -d -p 38081:8080 swaggerapi/swagger-ui:v4.15.5
配置和使用Swagger
- 導(dǎo)入Swagger配置文件:
- 打開Swagger Editor(http://localhost:38080),點(diǎn)擊左上角的【File】-【Import File】,選擇你的 swagger.json 或 swagger.yaml 文件進(jìn)行導(dǎo)入。
- 測(cè)試API接口:
- 在Swagger UI界面中,瀏覽到相應(yīng)的API接口。
- 點(diǎn)擊“try IT OUT”按鈕,輸入必要的參數(shù)。
- 發(fā)送請(qǐng)求并查看返回結(jié)果,以驗(yàn)證API是否按預(yù)期工作。
在spring Boot項(xiàng)目中集成Swagger
- 添加依賴:
在你的spring boot項(xiàng)目的 pom.xml 文件中添加以下依賴:
<<span>dependency></span> <<span>groupId></span>io.springfox</<span>groupId></span> <<span>artifactId></span>springfox-boot-starter</<span>artifactId></span> <<span>version></span>3.0.0</<span>version></span> </<span>dependency></span>
- 定義啟動(dòng)類:
package org.coffeebeans; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @Slf4j public class SwaggerApplication { public static void main(String[] args) { SpringApplication.run(SwaggerApplication.class, args); } }
- 配置Swagger:
創(chuàng)建一個(gè)Swagger配置類:
package org.coffeebeans.config; 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("org.coffeebeans.controller")) .paths(PathSelectors.any()) .build(); } }
- 使用Swagger注解定義API文檔:
在你的Controller類中使用Swagger注解來描述你的API:
package org.coffeebeans.controller; import io.swagger.annotations.*; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @Api(tags = "用戶管理") public class UserController { @GetMapping("/users") @ApiOperation(value = "獲取用戶列表") public List<User> getUsers( <span>@ApiParam(value = "分頁(yè)信息", required = false) @RequestParam(value = "page", defaultValue = "1") int page, @ApiParam(value = "每頁(yè)顯示數(shù)量", required = false) @RequestParam(value = "size", defaultValue = "10") int size)</span> { // 實(shí)現(xiàn)獲取用戶列表的邏輯 return userService.getUsers(page, size); } @GetMapping("/users/{id}") @ApiOperation(value = "獲取用戶信息") public User getUser( <span>@PathVariable Long id)</span> { // 實(shí)現(xiàn)獲取用戶信息的邏輯 return userService.getUserById(id); } }
通過以上步驟,你就可以在Linux系統(tǒng)上成功部署和使用Swagger進(jìn)行API測(cè)試了。