Java | Spring Boot Swagger2 集成REST ful API 生成接口文檔

Spring Boot Swagger2 集成REST ful API 生成接口文檔

原文html

簡介

因爲Spring Boot 的特性,用來開發 REST ful 變得很是容易,而且結合 Swagger 來自動生成 REST ful API 文檔變得方便快捷。 前端

Swagger 是一個簡單但功能強大的API表達工具。幾乎全部的語言均可以找到與之對應的Swagger 版本。使用Swagger生成API,咱們能夠獲得交互式文檔。聽過Spring Boot 與Swagger 的結合,生成更加完備的REST ful API 文檔。經過在源碼中添加部份內容,系統生成文檔,大大提升工做效率,不用再花費大量時間來建立文檔,同時因爲同時是經過代碼開生成文檔,大大下降了維護成本
Swagger 不只能夠組織生成強大的 REST ful 文檔,同時也提供了完備的測試功能,能夠直接在文檔頁面測試接口功能。java

接下來將基於 Spring Boot 與Swagger 2 搭建完整的API 文檔系統。先來提早目擊下Swagger 生成的文檔樣式
git

實踐

建立Spring Boot 工程

能夠參考前文Spring Boot 初體驗github

在POM 文件中添加 Swagger2 包引用

<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.7.0</version>
    </dependency>
    
    //導入測試須要的庫 
            <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.196</version>
            <scope>runtime</scope>
        </dependency>

本實例採用的是基於內存數據庫H2 的JPA 形式spring

建立配置類

經過以上方式只能導入 Swagger2 須要的jar包,但當前並不能運行(雖然Spring boot 支持自動化配置)mongodb

@Configuration
@EnableSwagger2
public class SwaggerConfig {

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

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2構建RESTful APIs")
                .description("spring boot , swagger2")
                .termsOfServiceUrl("http:github.com/zhuamaodeyu")
                .contact("抓?的?")
                .version("1.0")
                .build();
    }
}

說明:數據庫

  1. @Configuration: 此註解是告訴 Spring Boot 這是一個配置類,須要在項目啓動時加載該類
  2. @EnableSwagger2: Swagger2 是經過此註解來啓動的
  3. 經過 api方法建立 Docket 對象,其中主要注意 basePackage配置以及私有方法 apiInfo方法建立的基本信息
    經過指定掃描包來配置,以上配置 Swagger 會掃描整個項目工程

建立實體和respository

@Entity
@Table(name="user")
public class User implements Serializable {
//    @ApiModelProperty(notes = "id")
    @Id

    @GeneratedValue(strategy = GenerationType.AUTO)
    private  String id;
    @ApiModelProperty(notes = "uuid")
    private UUID uuid;
    @ApiModelProperty(notes = "用戶名稱")
    private  String name;
    private  String password;
    @ApiModelProperty(notes = "用戶地址")
    private  String address;
    @ApiModelProperty(notes = "年齡")
    private  int age;
    @ApiModelProperty(notes = "郵箱地址")
    private  String email;
    @ApiModelProperty(notes = "描述")
    private  String desc;
    
    // getter/ setter 方法

}

@Repository
public interface UserRepository extends  CrudRepository<User,String> {

}

測試controller

@RestController
@Api(value = "product 商品操做API")
@RequestMapping("/product")
public class IndexController {

    /**
     * 1. 獲取列表
     * 2. 顯示單個的信息
     * 3. 添加
     * 4. 更新
     * 5. 刪除
     */

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/")
    @ApiOperation(value = "首頁",notes = "測試代碼")
    public  String index()
    {
        return  "index";
    }



    @GetMapping("/list")
    @ApiOperation(value = "獲取所有數據列表", notes = "獲取數據列表")
    public Iterable list(Model model)
    {
        return  userRepository.findAll();
    }

    @GetMapping("/get_user_message")
    @ApiOperation(value = "獲取用戶詳情信息")
    @ApiImplicitParam(name = "userId",value = "用戶ID",defaultValue = "",required = true,dataType = "String")
    public User getUserMessage(String userId)
    {
        return  userRepository.findOne(userId);
    }


    @PostMapping("/save")
    @ApiOperation(value = "保存用戶數據")
    @ApiImplicitParam(name = "user", value = "用戶對象",required = true, dataTypeClass = User.class)
    public String save(@RequestBody User user)
    {
        if (user == null)
        {
            return  "false";
        }

        userRepository.save(user);
        return  "true";
    }

    @PutMapping("/update/{userId}")
    @ApiOperation(value = "更新用戶數據")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用戶的ID", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "user", value = "用戶對象", required = true, dataTypeClass = User.class)
    })

    public ResponseEntity updateUserMessage(@PathVariable String userId, @RequestBody User user)
    {
        User user1 = userRepository.findOne(userId);
        user1.setAddress(user.getAddress());


        userRepository.save(user1);
        return  new ResponseEntity("更新數據成功", HttpStatus.OK);
    }

    @DeleteMapping("/delete/{userId}")
    @ApiOperation(value = "根據用戶ID 刪除用戶數據")
    @ApiImplicitParam(name = "刪除用戶數據",value = "",required = true, dataType = "String")
    public  ResponseEntity deleteUser(@PathVariable String userId)
    {
        userRepository.delete(userId);
        return new ResponseEntity("刪除用戶數據", HttpStatus.OK);
    }
}

測試

實現以上代碼,啓動項目 直接訪問http://localhost:8080/swagger-ui.html
就能看到Swagger2 所生成的文檔。能夠操做每一個請求,其下面是具體的描述和文檔內容npm

接口調試
  1. Swagger 集成測試
    前文提到 Swagger 也提供了 接口調試功能, 能夠直接根據接口要求在圖中標記處填寫接口參數
    調試
  2. Postman 測試
    經過以上方式能夠獲得接口文檔,其包含了具體的內容,有了這些內容,就能夠經過Postman 等專業的接口測試工具來進行接口的測試
    postman接口測試

Swagger2 經常使用配置詳解

  • @Apijson

    @Api(value="onlinestore", description="當前控制器中的API 的描述信息")
  • @ApiOperation

    此註解是對當前 API 接口的描述,主要是名稱,詳細描述,返回值類型等信息

    @ApiOperation(value = "首頁",notes = "測試代碼", tags = {"測試服務是否正常"}, response = String.class)
    • value : API 的名稱
    • notes : API 詳細描述信息
    • response : 返回值類型
    • tags : 默認的是以 類名爲 標籤的,此處能夠自定義標籤
  • @ApiResponses
  • @ApiResponse

    此註解是對API 返回的結果進行描述

    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
            @ApiResponse(code = 404, message = "The resource you were trying to reach is not found")
    }
    )
  • @ApiImplicitParams
  • @ApiImplicitParam

    這兩個註解是對API 請求參數的描述

    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用戶的ID", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "user", value = "用戶對象", required = true, dataTypeClass = User.class)
    })
  • @ApiModelProperty
    實體類屬性添加描述信息,在接口文檔中可針對類屬性具體含義進行查看

    @GeneratedValue(strategy = GenerationType.AUTO)
    private  String id;
    @ApiModelProperty(notes = "uuid")
    private UUID uuid;
    @ApiModelProperty(notes = "用戶名稱")
    private  String name;
    private  String password;
    @ApiModelProperty(notes = "用戶地址")
    private  String address;
    @ApiModelProperty(notes = "年齡")
    private  int age;
    @ApiModelProperty(notes = "郵箱地址")
    private  String email;
    @ApiModelProperty(notes = "描述")
    private  String desc;

    經過以上配置,能夠文檔中進行查看

擴展知識

Mock 系統

在現現在的開發中,一個因爲項目需求緊,開發週期短,一般涉及到後端以及前端協同工做;一個因爲如今大多采用的是先後端分離的開發形式,先後端交互只是經過 REST ful 接口形式來實現的,先後端各自分工工做,因此就存在一個現象就是前端作的快,後端沒法及時的給出接口實現而且開發階段沒有數據支撐而形成前端必須等待後端。

如今能夠經過先定義接口文檔,生成 Mock 數據的形式來進行先後端分離開發。前端經過調用定義的 Mock 數據來進行前端調試和開發。不須要等待後端的數據

接下來將經過集成 easy-Mock 系統來實現協同開發

easy Mock

easy-mock 是大搜車公司開源的一套 mock 工具,是一個可視化,而且能快速生成 模擬數據 的持久化服務. 下面將 easy-mock 與 Swagger 結合進行協同工做

  • 搭建easy-mock

    • 下載源碼
      easy-mock是一套開源系統,其託管在 github 上,能夠經過一下方式獲取源碼
      git clone https://github.com/easy-mock/easy-mock.git
    • 修改配置
      easy-mock 是使用MongoDB數據的,因此須要配置數據庫
      進入 config文件夾,修改 default.json文件

      {
            "port": 7300,
            "pageSize": 30,
            "routerPrefix": {
              "mock": "/mock",
              "api": "/api"
            },
            "db": "mongodb://192.168.99.100:32773/easy-mock_",
            "unsplashClientId": "",

      修改 db 添加一個能夠用的 數據庫

    • 啓動
      npm run dev
      默認的監聽 7300 端口,能夠經過localhost:7300訪問系統
  • 導入 Swagger
    進入系統建立項目並根據如下方式導入 Swagger

    • 獲取 Swagger 地址
      獲取 Swagger 地址
    • easy-mock建立項目
      建立項目
    • 經過
      同步

參考

相關文章
相關標籤/搜索