zoukankan      html  css  js  c++  java
  • Swagger rest API 描述

     

     

    1 工作原理

    使用Spring Boot开发前、后端分离的项目越来越多,而前、后端往往是由不同的开发人员或团队负责。如果后端开发了一些REST接口,如何将这些接口即快速又准确地描述给前端开发人员呢?

    Swagger提供了一种自动扫描生成API接口文档的技术实现

    2 集成步骤

    第一步,添加Maven依赖如下:

    <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>

    第二步,编写配置类;

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("API文档")
                    .description("")
                    .termsOfServiceUrl("")
                    .version("1.0")
                    .build();
        }
    }

    第三步,编写测试Controller:

    @Api(description = "测试")
    @RestController @RequestMapping(
    "/demo") public class DemoController { @RequestMapping(value = "/user", method = RequestMethod.GET) public Object getUsers(@ApiParam(value = "名称") @RequestParam(required = false) String name) {
        List list
    = new ArrayList();
        list.add(name
    );
       

        return list;
      }
    }

     启动应用并访问  http://localhost:8080/swagger-ui.html

    3 API注解

    Swagger还提供了一些@注解用于详细的对API接口进行描述。

        @Api:修饰整个类,描述Controller的作用。

        @ApiOperation:描述一个类的一个方法,或者说一个接口。

        @ApiParam:单个参数描述。

        @ApiModel:用对象来接收参数。

        @ApiProperty:用对象接收参数时,描述对象的一个字段。

        @ApiResponse:HTTP响应其中一个描述。

        @ApiResponses:HTTP响应整体描述。

        @ApiIgnore:使用该注解忽略这个API。

        @ApiError:发生错误返回的信息。

        @ApiParamImplicit:一个请求参数。

     @ApiParamsImplicit:多个请求参数。

    4 安全问题

      这种公开的接口API文档一般只用于开发环境,在生产环境下会有一定的安全问题。此时可以通过在Swagger配置类上添加@Profile({"dev"})注解进行控制,这样Swagger只有在dev这个profile下才会生效。

    不积跬步,无以至千里;不积小流,无以成江海。
  • 相关阅读:
    Linux下调试caffe
    MXnet的使用
    Cmake的使用
    深度学习的移动端实现
    【WPF】面板布局介绍Grid、StackPanel、DockPanel、WrapPanel
    【WinForm】Dev ComboxEdit、BarManager的RepositoryItemComboBox、ComboBox操作汇总
    【WinForm】DataGridView使用小结
    【Linux】常用指令
    【c++】MFC 程序入口和执行流程
    【WPF】拖拽改变控件大小
  • 原文地址:https://www.cnblogs.com/lovedaodao/p/8951811.html
Copyright © 2011-2022 走看看