REST API文檔工具Swagger2,以及與SpringBoot的集成

手寫Api文檔的幾個(gè)痛點(diǎn):

  • 前后端聯(lián)調(diào)接口,需要不斷的更新接口文檔,一般是文檔跟不上接口變化的節(jié)奏;
  • 接口返回結(jié)果不明確;
  • 不能直接在線測(cè)試接口,通常需要使用工具,比如postman、jmeter;
  • 接口文檔太多,不好管理;

Swagger簡(jiǎn)介

swagger是一個(gè)API框架,號(hào)稱世界上最流行的API工具。它提供了API管理的全套解決方案,比如API在線編輯器,APIUI展示界面,代碼生成器等諸多功能。
Swagger官方地址

Springfox簡(jiǎn)介

如果想引入swagger進(jìn)行API管理。目前springfox是一個(gè)很好的選擇,它內(nèi)部會(huì)自動(dòng)解析Spring容器中Controller暴露出的接口,并且也提供了一個(gè)界面用于展示或調(diào)用這些API。
Springbox官方地址

Maven依賴

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>       

Swagger配置類

package com.lx;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.lx.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger構(gòu)建api文檔")
                .description("簡(jiǎn)單優(yōu)雅的restfun風(fēng)格")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }
}

Application.class 加上注解@EnableSwagger2 表示開啟Swagger

package com.lx;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
@MapperScan("com.lx.mapper")
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

REST API接口增加Swagger注釋

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value="添加用戶信息", notes="添加用戶信息")
    @ApiImplicitParam(name = "user", value = "用戶詳細(xì)實(shí)體user", required = true)
    @ResponseBody
    @RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    public int addUser(User user){
        return userService.addUser(user);
    }

    @ApiOperation(value="查看信息", notes="查看用戶信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "頁碼", required = true, dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每頁個(gè)數(shù)", required = true, dataType = "int")
    })
    @ResponseBody
    @RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public Object findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){

        return userService.findAllUser(pageNum,pageSize);
    }
}

Swagger2文檔

啟動(dòng)SpringBoot,打開url http://127.0.0.1:8080/swagger-ui.html#/

Swagger REST API頁面

注解

@Api

用在類上,說明該類的作用

@Api(value = "UserController", description = "用戶相關(guān)api")

@ApiOperation

用在方法上,說明方法的作用

@ApiOperation(value = "查找用戶", notes = "查找用戶", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

@ApiImplicitParams

用在方法上包含一組參數(shù)說明

@ApiImplicitParam

用在@ApiImplicitParams注解中,指定一個(gè)請(qǐng)求參數(shù)的各個(gè)方面
paramType:參數(shù)放在哪個(gè)地方

header–>請(qǐng)求參數(shù)的獲?。篅RequestHeader
query–>請(qǐng)求參數(shù)的獲?。篅RequestParam
path(用于restful接口)–>請(qǐng)求參數(shù)的獲取:@PathVariable
body(不常用)
form(不常用)

name:參數(shù)名
dataType:參數(shù)類型
required:參數(shù)是否必須傳
value:參數(shù)的意思
defaultValue:參數(shù)的默認(rèn)值

@ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path"),
})

@ApiResponses

用于表示一組響應(yīng)

@ApiResponse

用在@ApiResponses中,一般用于表達(dá)一個(gè)錯(cuò)誤的響應(yīng)信息
code:數(shù)字,例如400
message:信息,例如”請(qǐng)求參數(shù)沒填好”
response:拋出異常的類

@ApiResponses(value = {
        @ApiResponse(code = 400, message = "No Name Provided")  
    })

@ApiModel

Swagger-core builds the model definitions based on the references to them throughout the API introspection.
The @ApiModel allows you to manipulate the meta data of a model from a simple description or name change to a definition of polymorphism.
描述一個(gè)Model的信息(這種一般用在post創(chuàng)建的時(shí)候,使用@RequestBody這樣的場(chǎng)景,請(qǐng)求參數(shù)無法使用@ApiImplicitParam注解進(jìn)行描述的時(shí)候)

@ApiModel(value = "用戶實(shí)體類")

@ApiModelProperty

描述一個(gè)model的屬性

@ApiModelProperty(value = "登錄用戶")
@ApiIgnore //使用這個(gè)注解忽略這個(gè)接口
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容