Swagger和Postman的配置和使用


Swagger

1. 配置

  • pom文件添加swagger依賴,注意版本,2.8.0可以使用
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.8.0</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.8.0</version>
    </dependency>
  • 新建一個配置類,添加以下內容和注解(注意修改相關的內容,比如包)
@Configuration
@EnableSwagger2
public class Swagger2Setting {
    @Bean
    public Docket createRestAPI(){
        return new Docket(DocumentationType.SWAGGER_2)
                //.apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.crab.classfight.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("classfight項目")
                .description("這里是classfight項目的API列表說明")
                .contact("crab")
                .version("1.0")
                .build();
    }
}
  • 開發restful風格的接口,例如:
    @DeleteMapping(value = "/deleteUser/{username}")
    @ApiOperation("刪除一個用戶")
    public void deleteUser(@PathVariable("username") String username){
        userService.deleteUserByName(username);

    }
  • 編寫注釋文檔,例如:
    • 在rest接口上使用@Api注解:
    @RestController
    @Api("用戶相關的API")
    public class UserController {
    }
- 在方法上使用@ApiOperation注解:
    ` @ApiOperation(value = "添加一個用戶")`
- 方法參數注解
@ApiParam或者
    ```
@ApiImplicitParams({
        @ApiImplicitParam(name = "userName", required = true, value = "輸入用戶名關鍵字", dataType = "String"),
        @ApiImplicitParam(name = "courseId", required = true, value = "當前報名的課程id", dataType = "String")
})
    - 在實體類上使用@ApiModelProperty注解,可選參數(name, value, required, hidden, default value)
還有相關其他的注解,這里不舉例了
- 運行項目,進入網址http://localhost:8080/swagger-ui.html查看接口信息文檔,測試接口。

### Postman
- 去Postman官網下載並安裝,運行項目,在Postman中按照請求方式輸入網址和請求參數,測試。
- 可以選擇相應的請求方式,然后在body中添加相應的參數,點擊send查看返回結果。
    ![](https://img2018.cnblogs.com/blog/1369152/201903/1369152-20190320213332813-1176174412.png)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM