美文网首页
SpringBoot+Swagger-UI构建API及其文档

SpringBoot+Swagger-UI构建API及其文档

作者: Lyudmilalala | 来源:发表于2020-05-12 00:33 被阅读0次

    本文实现了将数据库操作通过API暴露给外界使用,并通过Swagger-UI简化了API文档

    本文需要用到SpringBoot+MySQL+JPA后端数据库搭建所建的数据库架构

    目前项目架构


    Project Structure

    1. 在pom.xml添加dependencies

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

    2. 创建Swagger配置的Docket Bean

    在config包中创建一个SwaggerConfig
    可以根据自己的需要修改API documentation的title,version,description等

    注意这里的contactspringfoxcontact而不是swagger

    package com.pde_staff.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.Contact;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
         @Bean
         public Docket createRestApi() {
             return new Docket(DocumentationType.SWAGGER_2)
                     .pathMapping("/")
                     .select()
                     .apis(RequestHandlerSelectors.basePackage("com.pde_staff.controller"))
                     .paths(PathSelectors.any())
                     .build().apiInfo(new ApiInfoBuilder()
                             .title("User API")
                             .description("Functions for managing the user table......")
                             .version("1.0")
                             .contact(new Contact("Lyudmila", "http://blog.example.com/", "example@email.com"))
                             .license("The Apache License")
                             .licenseUrl("http://www.example.com")
                             .build());
            }
    }
    

    3. 创建User Table对应的CRUD Controller

    在controller包中创建一个UserController
    @Api用来注释整个Controller的functionality
    创建Create, Retrieve, Update, Delete相对应的方法
    @ApiOperation用来注释当前方法的functionality

    package com.pde_staff.controller;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.pde_staff.entity.User;
    import com.pde_staff.repository.UserRepository;
    
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    
    @RestController
    @Api(tags = "User internface")
    @RequestMapping(value="/user")
    public class UserController {
    
        @Autowired
        private UserRepository userRepository;
        
        @RequestMapping(value="/list", method=RequestMethod.GET)
        @ApiOperation("List All Users")
        public List<User> list(){
            return userRepository.findAll();
        }
        
        @RequestMapping(value="/add", method=RequestMethod.GET)
        @ApiOperation("Add User")
        public void add(User u){
            userRepository.save(u);
        }
        
        @RequestMapping(value="/deleteById", method=RequestMethod.DELETE)
        @ApiOperation("Delete User by Id")
        public void delete(long id){
            userRepository.delete(id);
        }
        
        @RequestMapping(value="/deleteByName", method=RequestMethod.DELETE)
        @ApiOperation("Delete User by First Name and Last Name")
        public void delete(String firstName, String lastName){
            userRepository.deleteByFirstNameAndLastName(firstName, lastName);
        }
        
        @RequestMapping(value="/update", method=RequestMethod.GET)
        @ApiOperation("Update User")
        public void update(User u){
            userRepository.save(u);
        }
    }
    

    这样一来,其他进程就可以通过http://localhost:6050/user/list
    获取数据库所有的数据信息,通过http://localhost:6050/user/deleteById?id=1删除Id=1的User Object,以此类推

    4. 展示Swagger-UI的API文档

    浏览器输入http://localhost:6050/swagger-ui.html
    网页中发生错误


    网上有人说降低Swagger版本可以修好,但是对我无效
    后来看到有人说应该是带有Swagger配置类的包没有被Spring扫描到,于是把包加入程序执行主类
    package com.pde_staff;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.ComponentScan;
    
    @SpringBootApplication
    @ComponentScan(value = {"com.pde_staff.config"}) 
    @ComponentScan(value = {"com.pde_staff.controller"}) 
    public class Hello {
         public static void main(String[] args) {
             SpringApplication.run(Hello.class, args);
         }
    }
    

    果然有效

    API Documentation
    可用通过点击每个方法查看他们的信息,使用Try it out测试
    在测试的时候还发现,Swagger-UI里的date虽说是RFC3339,但输入如2018-05-26T10:36:39.580Z的格式是无效的,一定要写成类似于Sat, 26 May 2018 10:36:48 GMT
    最后私心觉得Swagger-UI 2.7.0比2.9.2更漂亮
    mysql> SELECT * FROM testu;
    +----+---------------------+------------+-----------+
    | id | birth_date          | first_name | last_name |
    +----+---------------------+------------+-----------+
    | 11 | 2020-05-11 02:37:59 | Ronald     | Weasley   |
    | 12 | 1981-02-22 10:00:00 | Harry      | Potter    |
    | 14 | 2018-10-29 18:16:04 | Luna       | Lovegood  |
    +----+---------------------+------------+-----------+
    
    Swagger-UI 2.7.0 DeleteById
    mysql> SELECT * FROM testu;
    +----+---------------------+------------+-----------+
    | id | birth_date          | first_name | last_name |
    +----+---------------------+------------+-----------+
    | 11 | 2020-05-11 02:37:59 | Ronald     | Weasley   |
    | 14 | 2018-10-29 18:16:04 | Luna       | Lovegood  |
    +----+---------------------+------------+-----------+
    
    Swagger-UI 2.7.0 Add
    mysql> SELECT * FROM testu;
    +----+---------------------+------------+-----------+
    | id | birth_date          | first_name | last_name |
    +----+---------------------+------------+-----------+
    | 11 | 2020-05-11 02:37:59 | Ronald     | Weasley   |
    | 14 | 2018-10-29 18:16:04 | Luna       | Lovegood  |
    | 16 | 2018-05-26 05:36:48 | Harry      | Potter    |
    +----+---------------------+------------+-----------+
    

    5. 参考文献

    SpringBoot整合Swagger2
    关于通过Swagger查看接口浏览器跳出Unable to infer base url...
    Swagger测试Date类型参数

    下一步:用独立前端调用后台API~AngularJS通过HTTP与后台API进行数据交互

    相关文章

      网友评论

          本文标题:SpringBoot+Swagger-UI构建API及其文档

          本文链接:https://www.haomeiwen.com/subject/tnemnhtx.html