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#/,页面效果如图所示:

<think>好的,我现在需要回答用户关于如何使用Swagger创建API文档的问题。首先,我应该先整理用户提供的引用内容,看看里面有哪些关键点可以利用。引用1提到Swagger用于描述、创建和维护RESTful API文档,并提到了安装过程和交互式界面。引用2补充了Swagger是一个规范和框架,用于生成和可视化接口文档。引用3是关于在Asp.Net MVC Web API中使用Swagger的步骤,包括创建项目和集成Swagger。引用4则详细介绍了使用Swagger 3的注解,比如@Tag和@Operation。 接下来,我需要按照用户的要求,结构清晰地分步骤说明。用户希望看到教程式的回答,所以应该从安装开始,然后逐步讲解配置、定义API、使用注解、生成文档、测试接口等步骤。要注意的是,用户示例中的代码块使用了Python,但引用3中的例子是Asp.Net,可能需要调整语言环境,但用户可能希望看到通用步骤,或者具体某个框架的步骤? 根据引用3和4,用户可能对如何在不同的环境中使用Swagger感兴趣,比如在Asp.Net中使用,或者在Spring Boot中使用注解。所以可能需要分环境来说明,或者先给出通用步骤,再提供不同框架的例子。不过用户的问题比较广泛,可能更适合一般性的步骤,然后补充不同框架的示例。 另外,用户提到要生成相关问题,所以最后需要提出几个相关问题,比如安装步骤、与OpenAPI的关系、注解的作用等。 需要注意的是,必须使用中文回答,数学公式用$...$,独立公式用$$...$$,但这个问题可能不涉及数学公式,所以可能不需要。另外要正确使用LaTeX语法,但同样这里可能用不上。需要检查是否有变量或代码需要正确格式化。 可能的结构: 1. 安装Swagger工具 2. 配置Swagger(根据框架不同) 3. 定义API端点 4. 添加注解描述API 5. 生成和访问文档 6. 测试API 每个步骤中引用相应的引用内容,比如在配置部分提到引用3的Asp.Net步骤,在注解部分引用4的@Tag和@Operation。最后的问题需要涵盖教程中的各个部分,比如优化文档、测试方法、版本控制等。 现在需要确保每个步骤都清晰,并且引用正确的来源。例如,在提到使用Swagger UI时,引用1和2都提到了交互式界面,可以标注引用1和2。在注解部分,引用4详细说明了注解的使用,所以需要标注引用4。对于Asp.Net的具体步骤,引用3提供了创建项目和集成的步骤,所以需要标注引用3。 还需要注意,用户的问题是如何使用Swagger创建API文档,所以可能需要涵盖Swagger的不同使用方式,比如通过代码注解自动生成,或者手动编写YAML文件。根据引用内容,引用3和4更偏向于代码注解的方式,而引用1和2可能更偏向于整体描述。 总结回答结构: - 简介Swagger的作用 - 分步骤教程,包括安装、配置、定义API、添加注解、生成文档、测试 - 不同框架的示例(如Spring Boot和Asp.Net) - 相关问题 现在开始组织内容,确保每个部分都有对应的引用标注,并且语言自然,结构清晰。例如,步骤1安装Swagger可能包括使用npm安装Swagger CLI或者在Maven中添加依赖,根据不同的工具链。步骤2配置可能是在项目中启用Swagger,比如在Spring Boot中使用@EnableSwagger2,或者在Asp.Net中添加Swashbuckle包。步骤3定义API端点是编写控制器方法。步骤4添加注解如@Tag、@Operation等。步骤5生成文档后访问Swagger UI,步骤6测试接口。 需要检查每个步骤是否有对应的引用支持,比如在Asp.Net的配置步骤引用3,注解部分引用4,交互式界面引用1和2。 最后,生成的相关问题应该覆盖教程中提到的不同方面,比如安装、注解使用、测试、版本控制等。</think>### 如何使用 Swagger 创建 API 文档 Swagger 是一套用于设计、构建和文档化 RESTful API 的工具集,支持通过代码注解或 YAML 文件自动生成交互式文档。以下是详细步骤: --- #### 1. **安装 Swagger 工具** 根据开发环境选择安装方式: - **Node.js 项目**:使用 Swagger CLI 工具 ```bash npm install -g swagger-cli ``` - **Java/Spring Boot**:通过 Maven 引入依赖 ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>3.0.0</version> </dependency> ``` - **.NET 项目**:通过 NuGet 安装 `Swashbuckle.AspNetCore`[^3]。 --- #### 2. **配置 Swagger** 在项目中启用 Swagger 并定义基本配置: - **Spring Boot**:添加 `@EnableSwagger2` 注解到主类,并配置 Docket Bean[^2]。 ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } } ``` - **.NET**:在 `Startup.cs` 中注册 Swagger 服务[^3]: ```csharp services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); }); ``` --- #### 3. **定义 API 端点** 在控制器中编写 API 方法,例如 Spring Boot 示例: ```java @RestController @RequestMapping("/api/users") @Tag(name = "用户管理", description = "用户相关操作") // 引用[^4] public class UserController { @GetMapping("/{id}") @Operation(summary = "获取用户信息", description = "根据ID查询用户") public User getUser(@PathVariable Long id) { // 实现逻辑 } } ``` --- #### 4. **添加注解描述 API** 使用 Swagger 注解增强文档可读性: - `@Tag`:为 API 分组(如“用户管理”)。 - `@Operation`:描述接口功能。 - `@ApiResponse`:定义响应状态码和说明。 - **示例**: ```java @PostMapping @Operation(summary = "创建用户", description = "提交用户信息并保存") @ApiResponse(responseCode = "201", description = "用户创建成功") public ResponseEntity<User> createUser(@RequestBody User user) { // 实现逻辑 } ``` --- #### 5. **生成并访问文档** 启动项目后,通过以下 URL 访问交互式文档: - **默认路径**:`http://localhost:8080/swagger-ui.html`(Spring Boot) `http://localhost:<port>/swagger`(.NET) 文档将展示所有 API 端点、请求参数和响应模型。 --- #### 6. **在线测试 API** 在 Swagger UI 中直接发送请求并查看结果: ![Swagger 测试界面示例](https://example.com/swagger-ui-screenshot.png) 支持修改参数并实时验证功能[^1]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值