SpringBoot使用Swagger2實現Restful API

不少時候,咱們須要建立一個接口項目用來數據調轉,其中不包含任何業務邏輯,好比咱們公司。這時咱們就須要實現一個具備Restful API的接口項目。html

本文介紹springboot使用swagger2實現Restful API。java

本項目使用mysql+jpa+swagger2。mysql

首先pom中加入swagger2,代碼以下:web

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dalaoyang</groupId>
    <artifactId>springboot_swagger2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot_swagger2</name>
    <description>springboot_swagger2</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>
複製代碼

接下來是配置文件,和整合jpa同樣。代碼以下:spring

##端口號
server.port=8888

##數據庫配置
##數據庫地址
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
##數據庫用戶名
spring.datasource.username=root
##數據庫密碼
spring.datasource.password=root
##數據庫驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
複製代碼

建立一個swagger2配置類,簡單解釋一下,@Configuration註解讓spring來加載配置,@EnableSwagger2開啓swagger2。sql

package com.dalaoyang.config;

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;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.config
 * @email yangyang@dalaoyang.cn
 * @date 2018/4/9
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.dalaoyang.swagger"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("使用Swagger2構建RESTful APIs")
                .description("關注博主博客:https://www.dalaoyang.cn/")
                .termsOfServiceUrl("https://www.dalaoyang.cn/")
                .contact("dalaoyang")
                .version("1.0")
                .build();
    }
}
複製代碼

建立一個user類做爲model數據庫

package com.dalaoyang.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.model
 * @email yangyang@dalaoyang.cn
 * @date 2018/4/9
 */
@Entity
@ApiModel(description = "user")
public class User {

    @ApiModelProperty(value = "主鍵id",hidden = true)
    @GeneratedValue
    @Id
    int id;

    @ApiModelProperty(value = "用戶名稱")
    @NotNull
    @Column
    String userName;

    @ApiModelProperty(value = "用戶密碼")
    @Column
    String userPassword;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public User(int id, String userName, String userPassword) {
        this.id=id;
        this.userName = userName;
        this.userPassword = userPassword;
    }
    public User(String userName, String userPassword) {
        this.userName = userName;
        this.userPassword = userPassword;
    }

    public User() {
    }
}
複製代碼

jpa數據操做類UserRepositoryapache

package com.dalaoyang.repository;

import com.dalaoyang.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.repository
 * @email yangyang@dalaoyang.cn
 * @date 2018/4/9
 */
public interface UserRepository extends JpaRepository<User,Integer> {

    User findById(int id);
}

複製代碼

而後添加文檔內容,其實和寫controller同樣,只不過方法和參數中間穿插一些註解。json

package com.dalaoyang.swagger;

import com.dalaoyang.model.User;
import com.dalaoyang.repository.UserRepository;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.swagger
 * @email yangyang@dalaoyang.cn
 * @date 2018/4/9
 */
@RestController
@RequestMapping(value="/users")
@Api(value="用戶操做接口",tags={"用戶操做接口"})
public class UserSwagger {

    @Autowired
    UserRepository userRepository;

    @ApiOperation(value="獲取用戶詳細信息", notes="根據用戶的id來獲取用戶詳細信息")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true,paramType = "query", dataType = "Integer")
    @GetMapping(value="/findById")
    public User findById(@RequestParam(value = "id")int id){
        User user = userRepository.findById(id);
        return user;
    }

    @ApiOperation(value="獲取用戶列表", notes="獲取用戶列表")
    @GetMapping(value="/getUserList")
    public List getUserList(){
        return userRepository.findAll();
    }


    @ApiOperation(value="保存用戶", notes="保存用戶")
    @PostMapping(value="/saveUser")
    public String saveUser(@RequestBody @ApiParam(name="用戶對象",value="傳入json格式",required=true) User user){
        userRepository.save(user);
        return "success!";
    }

    @ApiOperation(value="修改用戶", notes="修改用戶")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="主鍵id",required=true,paramType="query",dataType="Integer"),
            @ApiImplicitParam(name="username",value="用戶名稱",required=true,paramType="query",dataType = "String"),
            @ApiImplicitParam(name="password",value="用戶密碼",required=true,paramType="query",dataType = "String")
    })
    @GetMapping(value="/updateUser")
    public String updateUser(@RequestParam(value = "id")int id,@RequestParam(value = "username")String username,
                             @RequestParam(value = "password")String password){
        User user = new User(id, username, password);
        userRepository.save(user);
        return "success!";
    }


    @ApiOperation(value="刪除用戶", notes="根據用戶的id來刪除用戶")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true,paramType = "query", dataType = "Integer")
    @DeleteMapping(value="/deleteUserById")
    public String deleteUserById(@RequestParam(value = "id")int id){
        User user = userRepository.findById(id);
        userRepository.delete(user);
        return "success!";
    }

}
複製代碼

啓動項目,訪問http://localhost:8888/swagger-ui.html,能夠看到以下圖api

爲了方便你們學習觀看,我分別用了幾種不一樣的方法寫,

1.刪除用戶,代碼以下

@ApiOperation(value="刪除用戶", notes="根據用戶的id來刪除用戶")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true,paramType = "query", dataType = "Integer")
    @DeleteMapping(value="/deleteUserById")
    public String deleteUserById(@RequestParam(value = "id")int id){
        User user = userRepository.findById(id);
        userRepository.delete(user);
        return "success!";
    }
複製代碼

2.獲取用戶詳細信息

@ApiOperation(value="獲取用戶詳細信息", notes="根據用戶的id來獲取用戶詳細信息")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true,paramType = "query", dataType = "Integer")
    @GetMapping(value="/findById")
    public User findById(@RequestParam(value = "id")int id){
        User user = userRepository.findById(id);
        return user;
    }
複製代碼

3.獲取用戶列表

@ApiOperation(value="獲取用戶列表", notes="獲取用戶列表")
    @GetMapping(value="/getUserList")
    public List getUserList(){
        return userRepository.findAll();
    }
複製代碼

4.保存用戶

@ApiOperation(value="保存用戶", notes="保存用戶")
    @PostMapping(value="/saveUser")
    public String saveUser(@RequestBody @ApiParam(name="用戶對象",value="傳入json格式",required=true) User user){
        userRepository.save(user);
        return "success!";
    }
複製代碼

5.修改用戶

@ApiOperation(value="修改用戶", notes="修改用戶")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="主鍵id",required=true,paramType="query",dataType="Integer"),
            @ApiImplicitParam(name="username",value="用戶名稱",required=true,paramType="query",dataType = "String"),
            @ApiImplicitParam(name="password",value="用戶密碼",required=true,paramType="query",dataType = "String")
    })
    @PutMapping(value="/updateUser")
    public String updateUser(@RequestParam(value = "id")int id,@RequestParam(value = "username")String username,
                             @RequestParam(value = "password")String password){
        User user = new User(id, username, password);
        userRepository.save(user);
        return "success!";
    }
複製代碼

而後給你們分享一下我以前學習時記錄在有道雲筆記的關於swagger2的使用說明,原創做者是誰,我也記不清了。若是原創做者看到的話,能夠私聊我,我給您的名字加上,抱歉。

@Api:用在請求的類上,表示對類的說明
    tags="說明該類的做用,能夠在UI界面上看到的註解"
    value="該參數沒什麼意義,在UI界面上也看到,因此不須要配置"
示例:
@Api(tags="APP用戶註冊Controller")

@ApiOperation:用在請求的方法上,說明方法的用途、做用
    value="說明方法的用途、做用"
    notes="方法的備註說明"
示例:
@ApiOperation(value="用戶註冊",notes="手機號、密碼都是必輸項,年齡隨邊填,但必須是數字")

@ApiImplicitParams:用在請求的方法上,表示一組參數說明
    @ApiImplicitParam:用在@ApiImplicitParams註解中,指定一個請求參數的各個方面
        name:參數名
        value:參數的漢字說明、解釋
        required:參數是否必須傳
        paramType:參數放在哪一個地方
            · header --> 請求參數的獲取:@RequestHeader
            · query --> 請求參數的獲取:@RequestParam
            · path(用於restful接口)--> 請求參數的獲取:@PathVariable
            · body(不經常使用)
            · form(不經常使用)    
        dataType:參數類型,默認String,其它值dataType="Integer"       
        defaultValue:參數的默認值
示例:
@ApiImplicitParams({
    @ApiImplicitParam(name="mobile",value="手機號",required=true,paramType="form"),
    @ApiImplicitParam(name="password",value="密碼",required=true,paramType="form"),
    @ApiImplicitParam(name="age",value="年齡",required=true,paramType="form",dataType="Integer")
})

@ApiResponses:用在請求的方法上,表示一組響應
    @ApiResponse:用在@ApiResponses中,通常用於表達一個錯誤的響應信息
        code:數字,例如400
        message:信息,例如"請求參數沒填好"
        response:拋出異常的類
@ApiOperation(value = "select1請求",notes = "多個參數,多種的查詢參數類型")
@ApiResponses({
    @ApiResponse(code=400,message="請求參數沒填好"),
    @ApiResponse(code=404,message="請求路徑沒有或頁面跳轉路徑不對")
})

@ApiModel:用於響應類上,表示一個返回響應數據的信息
            (這種通常用在post建立的時候,使用@RequestBody這樣的場景,
            請求參數沒法使用@ApiImplicitParam註解進行描述的時候)
    @ApiModelProperty:用在屬性上,描述響應類的屬性
示例:
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

@ApiModel(description= "返回響應數據")
public class RestMessage implements Serializable{

    @ApiModelProperty(value = "是否成功")
    private boolean success=true;
    @ApiModelProperty(value = "返回對象")
    private Object data;
    @ApiModelProperty(value = "錯誤編號")
    private Integer errCode;
    @ApiModelProperty(value = "錯誤信息")
    private String message;

    
}



POST請求傳入對象 
示例:
   @ApiOperation(value="保存用戶", notes="保存用戶")
    @RequestMapping(value="/saveUser", method= RequestMethod.POST)
    public String saveUser(@RequestBody @ApiParam(name="用戶對象",value="傳入json格式",required=true) User user){
        userDao.save(user);
        return "success!";
    }
複製代碼
相關文章
相關標籤/搜索