Swagger的使用

何为Swagger

设计是API开发的基础。Swagger使API设计变得轻而易举,为开发人员,架构师和产品所有者提供了易于使用的工具。——官网

1)具有准确的API模型

API设计容易出错,在建模API时发现和纠正错误是非常困难和耗时的。Swagger Editor是第一个使用OpenAPI规范(OAS)设计API的编辑器,并且继续满足开发人员使用OAS构建API的需求。编辑器实时验证您的设计,检查OAS合规性,并随时提供视觉反馈。

2)在设计时可视化

最好的API是针对最终消费者而设计的。像Swagger编辑器和SwaggerHub这样的Swagger工具为YAML编辑器提供了一个可视化面板,供开发人员使用,并查看API对最终消费者的外观和行为。

3)在整个团队中标准化设计风格

提供共享通用行为,模式和一致的RESTful接口的API将极大地简化构建它们的人员和想要使用它们的消费者的工作。SwaggerHub配备了内置的API标准化工具,可以使您的API符合您的组织设计指南。

添加依赖

1、pom.xml:

在此添加如下依赖:

<dependency>
	<groupId>com.spring4all</groupId>
	<artifactId>spring-boot-starter-swagger</artifactId>
	<version>1.5.1.RELEASE</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.8.0</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.8.0</version>
</dependency>

启动类

在Spring Boot项目启动类上添加@EnableSwagger2注解。

项目配置

在项目的.properties中添加:

#swagger开启关闭
swagger.enabled=true

类配置

import org.springframework.beans.factory.annotation.Value;
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;

/**
 * Swagger2 的配置注入
 * @author ligj
 *
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Value("${swagger.enable}")
    private boolean enable;
    @Bean
    public Docket createRestApi() {
		
        return new Docket(DocumentationType.SWAGGER_2).enable(enable)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("你的title")
                .description("xxx 项目RestAPI文档")
                .termsOfServiceUrl("...")
                .version("1.0")
                .build();
    }

	
}

拦截器

如果有设置拦截器,那么需要放行swagger。

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(authenticationInterceptor())
         .addPathPatterns("/**")
         .excludePathPatterns("/swagger-resources/**", "/webjars/**","/v2/**", "/swagger-ui.html/**"); //放行swagger;
}

如果项目中没有拦截器,并且遇到了No mapping found for HTTP request with URI [/swagger-resources/configuration/ui] in DispatcherServlet with name 'dispatcherServlet',那么需要添加WebMvcConfigurerConfig:

package com.lamarsan.livelihood_background.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * className: WebMvcConfigurerConfig
 * description: TODO
 *
 * @author hasee
 * @version 1.0
 * @date 2019/8/12 10:02
 */
@Configuration
@EnableWebMvc
public class WebMvcConfigurerConfig implements WebMvcConfigurer {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");

        return corsConfiguration;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }
}

常用API

常用注解有:

1、Api

2、ApiModel

3、ApiModelProperty

4、ApiOperation

5、ApiParam

6、ApiResponse

7、ApiResponses

8、ResponseHeader

Api注解

Api用在类上,说明该类的作用,可以标记一个Controller类作为swagger文档资源,标记在类上,使用方式:

@Api(tags = "信息")
public class Controller{
	...
}

属性配置

属性名称备注
valueurl的路径值
tags如果设置这个值,value的值会被覆盖
description对api资源的描述
basePath基本路径可以不配置
position如果配置多个Api 想改变显示的顺序位置
producesFor example, “application/json, application/xml”
consumesFor example, “application/json, application/xml”
protocolsPossible values: http, https, ws, wss.
authorizations高级特性认证时配置
hidden配置为true 将在文档中隐藏

ApiOperation注解

用在方法上,说明方法的作用,每一个url资源的定义,使用方式:

@ApiOperation(value = "your describle")
@RequestMapping(value = "/xxx",method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public RestResponseModel getSongByUnit(@RequestBody @Validated UnitDTO unitDTO, @ApiIgnore ReqUser reqUser){
    your code
}

如果项目中没有拦截器,并且遇到了No mapping found for HTTP request with URI [/swagger-resources/configuration/ui] in DispatcherServlet with name 'dispatcherServlet',那么需要添加WebMvcConfigurerConfig:

package com.lamarsan.livelihood_background.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * className: WebMvcConfigurerConfig
 * description: TODO
 *
 * @author hasee
 * @version 1.0
 * @date 2019/8/12 10:02
 */
@Configuration
@EnableWebMvc
public class WebMvcConfigurerConfig implements WebMvcConfigurer {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");

        return corsConfiguration;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }
}

属性配置

属性名称备注
valueurl的路径值
tags如果设置这个值、value的值会被覆盖
description对api资源的描述
basePath基本路径可以不配置
position如果配置多个Api 想改变显示的顺序位置
producesFor example, “application/json, application/xml”
consumesFor example, “application/json, application/xml”
protocolsPossible values: http, https, ws, wss.
authorizations高级特性认证时配置
hidden配置为true 将在文档中隐藏
response返回的对象
responseContainer这些对象是有效的 “List”, “Set” or “Map”.,其他无效
httpMethod“GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS” and “PATCH”
codehttp的状态码 默认 200
extensions扩展属性

ApiParam注解

ApiParam为请求属性,使用方式:

public ResponseEntity<User> createUser(@RequestBody @ApiParam(value = "Created user object", required = true)  User user)

属性配置

属性名称备注
name属性名称
value属性值
defaultValue默认属性值
allowableValues可以不配置
required是否属性必填
access不过多描述
allowMultiple默认为false
hidden隐藏该属性
example举例子

ApiModelProperty注解

描述一个model的属性,具体用法如下:

@ApiModelProperty(value = "your describle")
private String id;

swagger页面

运行springboot项目后,在浏览器中输入http://localhost:8080/swagger-ui.html#/,页面效果如图所示:

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Swagger是一个用于设计、构建和文档化RESTful Web服务的开源工具集。下面是一个简单的Swagger使用教程: 1. 安装Swagger:可以通过npm、pip等包管理工具安装Swagger相关的库和工具。例如,对于Node.js项目,可以使用以下命令安装swagger-jsdoc和swagger-ui-express: ```bash npm install swagger-jsdoc swagger-ui-express ``` 2. 编写Swagger注解:在你的API代码中,使用Swagger注解来描述API的信息、请求和响应参数等。以下是一个示例: ```javascript /** * @swagger * /api/users: * get: * summary: 获取所有用户 * description: 获取所有用户列表 * responses: * 200: * description: 成功获取用户列表 * schema: * type: array * items: * $ref: '#/definitions/User' */ ``` 在这个示例中,我们使用Swagger注解来描述一个GET请求,它可以获取所有用户的列表。 3. 生成Swagger文档:使用Swagger注解编写完API代码后,可以使用相应的工具将这些注解转换为Swagger文档。例如,对于Node.js项目,我们可以使用swagger-jsdoc库生成Swagger文档。在项目的入口文件中添加以下代码: ```javascript const swaggerJSDoc = require('swagger-jsdoc'); const swaggerUi = require('swagger-ui-express'); const options = { definition: { openapi: '3.0.0', info: { title: 'API文档', version: '1.0.0', }, }, apis: ['./path/to/api/controllers/*.js'], // API代码文件的路径 }; const swaggerSpec = swaggerJSDoc(options); app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec)); ``` 这段代码将会在`/api-docs`路径下提供Swagger文档。 4. 查看Swagger文档:运行项目并访问`/api-docs`路径,你将会看到生成的Swagger文档。Swagger提供了一个交互式的UI界面,可以方便地查看API的信息、请求和响应参数等。 这只是一个简单的Swagger使用教程,你可以根据自己的项目需求进一步深入学习和使用Swagger

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值