1. 程式人生 > >Swagger介面文件快速生成

Swagger介面文件快速生成

1.openapi介紹

OpenAPI規範(OpenAPI Specification 簡稱OAS)是Linux基金會的一個專案,試圖通過定義一種用來描述API格式或API定義的語言,來規範RESTful服務開發過程,目前版本是V3.0,並且已經發布並開源在github上.

2.swagger

Swagger是全球最大的OpenAPI規範(OAS)API開發工具框架,支援從設計和文件到測試和部署的整個API生命週期的開發。

Spring Boot 可以整合Swagger,生成Swagger介面,Spring Boot是Java領域的神器,它是Spring專案下快速構建專案的框架。

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
    </dependency>

1.swagger常用註解

在Java類中新增Swagger的註解即可生成Swagger介面,常用Swagger註解如下:

@Api:修飾整個類,描述Controller的作用

@ApiOperation:描述一個類的一個方法,或者說一個介面

@ApiParam:單個引數描述

@ApiModel:用物件來接收引數

@ApiModelProperty:用物件接收引數時,描述物件的一個欄位

@ApiResponse:HTTP響應其中1個描述

@ApiResponses:HTTP響應整體描述

@ApiIgnore:使用該註解忽略這個API

@ApiError :發生錯誤返回的資訊

@ApiImplicitParam:一個請求引數

@ApiImplicitParams:多個請求引數

@ApiImplicitParam屬性:下面是網上從別處找的一張圖,

2. 定義介面,測試

@Api(value = "頁面管理服務端介面",description = "提供了crud的基本操作")
public interface CmsPageControllerApi {

    @ApiOperation("分類查詢介面")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",required = true,value = "頁碼",paramType = "path",dataType = "int")
    })
    public QueryResponseResult queryCmsPage(QueryPageRequest request,int size,int page);
}

在QueryPageRequest類中使用註解 ApiModelProperty 對屬性註釋:

public class QueryPageRequest extends RequestData {

//    站點id
    @ApiModelProperty("站點id")
    private String siteId;
}

Swagger介面測試

Swagger介面生成工作原理:

1、系統啟動,掃描到api工程中的Swagger2Configuration類

2、在此類中指定了包路徑com.test,找到在此包下及子包下標記有@RestController註解的controller類

3、根據controller類中的Swagger註解生成介面文件。

配置類程式碼

用的時候直接拷貝就行....

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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

//
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.test"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("學成網api文件")
                .description("學成網api文件")
//                .termsOfServiceUrl("/")
                .version("1.0")
                .build();
    }

}

啟動服務,檢視介面文件

正常啟動服務,然後訪問地址