Swagger实用示例全集

Swagger是一套基于OpenAPI规范构建的开源工具,可以快速帮助我们编写最新的API接口文档。

常用注解

@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述方法,或者说接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiModelProperty:用对象接收参数时,描述对象的一个字段
@ApiImplicitParam:一个请求参数
@ApiImplicitParams:多个请求参数

Swagger2使用

在2.10.0版本之前,是swagger2阻塞式编程,配置swagger都是用的注解@EnableSwagger2 从2.10.0—2.10.5,由于20年初响应式编程的出现,从2.10.0开始,配置swagger已经把注解@EnableSwagger2弃用,为区分阻塞式和响应式,开始使用的注解开始分为:@EnableSwagger2WebMvc、@EnableSwagger2WebFlux。此时会出现不利于维护的问题。因此不常用。

Swagger3:基于之前2.10版本,swagger3正式推出,非阻断式升级兼容阻塞式编程和响应式编程。Swagger3将@EnableSwagger2WebMvc、 @EnableSwagger2WebFlux注解弃用,兼容的注解为@EnableOpenAPI或@EnableSwagger2,使用这俩个注解都可以。

访问:

        swagger2:/swagger-ui.html

        swagger3:/swagger-ui/index.html

各项注释在代码中体现,属性取值只贴一遍,因为下面三个都一样.

Swagger2 

版本2.10.0之前的依赖包,常用的是2.9.2版本

<!--springfox-swagger2:Swagger2核心依赖-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!--springfox-swagger-ui:界面支持;为项目提供API界面的展示和测试-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

YML配置

swagger:
  enabled: true;
  contact-name: Ltter
  contact-url: https://www.baidu.com/
  contact-email: 6723885439275@qq.com
  title: 测试Swagger服务
  version: v1.0
  description: Swagger描述
  license: 1.1.1
  license-url: https://blog.csdn.net/u013812135?type=blog
  terms-of-service-url: https://blog.csdn.net/u013812135/article/details/121357346?spm=1001.2014.3001.5502
package com.learn.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @Title SwaggerProperties
 * @Description 属性
 * @Author Ltter
 * @Date 2022/8/17 14:01
 * @Version 1.0
 */
@Data
@Component
@ConfigurationProperties(prefix = "swagger")
public class SwaggerProperties {

    /**
     * 作者名称
     */
    private String contactName;
    /**
     * 作者—url
     */
    private String contactUrl;
    /**
     * 作者邮箱
     */
    private String contactEmail;
    /**
     * 标题
     */
    private String title;
    /**
     * 版本
     */
    private String version;
    /**
     * 描述
     */
    private String description;
    /**
     *
     */
    private String termsOfServiceUrl;
    /**
     * 网站连接显示文字
     */
    private String license;
    /**
     * 网站连接地址
     */
    private String licenseUrl;
}

配置文件

package com.learn.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

/**
 * @Title SwaggerConfig
 * @Description Swagger配置文件
 * @Author Ltter
 * @Date 2022/8/17 9:26
 * @Version 1.0
 */
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfig {

    @Autowired
    private SwaggerProperties swaggerProperties;

    /**
     * 配置Docket的Bean
     * @return
     */
    @Bean
    public Docket customDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                //接口文档的基础信息
                .apiInfo(customApiInfo())
                //对Api进行安全认证
                //.securitySchemes(customSecurity())
                //设置需要使用参数的接口
                //.securityContexts(customSecurityContext())
                .select()
                //1、扫描所有
                //.apis(RequestHandlerSelectors.any())
                //2、扫描所有使用注解的API,这种方法更灵活
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //3、扫描指定包中的注解
                .apis(RequestHandlerSelectors.basePackage("com.learn"))
                //路径风格
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 接口文档的基础信息
     * @return
     */
    private ApiInfo customApiInfo() {
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .version(swaggerProperties.getVersion())
                .description(swaggerProperties.getDescription())
                .contact(new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactUrl(), swaggerProperties.getContactEmail()))
                .license(swaggerProperties.getLicense())
                .licenseUrl(swaggerProperties.getLicenseUrl())
                .build();
    }

    /**
     * 对Api进行安全认证
     * @return
     */
    private List<ApiKey> customSecurity() {
        return null;
    }

    /**
     * 设置需要使用参数的接口
     * @return
     */
    private List<SecurityContext> customSecurityContext() {
        return null;
    }
}
@RestController
@RequestMapping("/knsw")
@Api(tags = "KNIFE4J-SWAGGER服务测试")
public class Knife4jController {

    @ApiOperation(value = "查询")
    @GetMapping("/find")
    public String find(){
        return "查询-结果-";
    }

    @ApiOperation(value = "保存")
    @PostMapping("/save")
    public String save(){
        return "保存-结果-";
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "编码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "params", value = "参数", dataType = "String", paramType = "query")
    })
    @ApiOperation(value = "查询测试")
    @GetMapping("findALl")
    public String findALl(@RequestParam("code") String code,@RequestParam("params") String params){
        return "返回结果:编码:"+ code +" 参数信息:"+ params;
    }
}

Swagger3

Swagger3的依赖包

<!--Swagger3-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
swagger:
  enabled: true;
  contact-name: Ltter
  contact-url: https://www.baidu.com/
  contact-email: 6723885439275@qq.com
  title: 测试Swagger服务
  version: v1.0
  description: Swagger描述
  license: 1.1.1
  license-url: https://blog.csdn.net/u013812135?type=blog
  terms-of-service-url: https://blog.csdn.net/u013812135/article/details/121357346?spm=1001.2014.3001.5502
package com.learn.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.service.Contact;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

/**
 * @Title Swagger3Config
 * @Description Swagger3配置文件
 * @Author Ltter
 * @Date 2022/8/17 14:59
 * @Version 1.0
 */

@Configuration
@EnableSwagger2
@EnableConfigurationProperties(Swagger3Properties.class)
public class Swagger3Config {

    @Autowired
    private Swagger3Properties swagger3Properties;

    @Bean
    public Docket customSwagger3Docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(customApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.learn"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo customApiInfo() {
        return new ApiInfoBuilder()
                .title(swagger3Properties.getTitle())
                .version(swagger3Properties.getVersion())
                .description(swagger3Properties.getDescription())
                .contact(new Contact(swagger3Properties.getContactName()
                        , swagger3Properties.getContactUrl()
                        , swagger3Properties.getContactEmail()))
                .license(swagger3Properties.getLicense())
                .licenseUrl(swagger3Properties.getLicenseUrl())
                .build();
    }

}

Knife4j-Swagger2

        knife4j是Swagger的升级版本;引用所有的knife4j提供的资源,包括前端Ui的jar包。在项目中一般将knife4j和knife4j-micro俩个依赖放入根pom中;若是微服务项目并使用了gateway的情况下,将knife4j依赖放入gateway中;knife4j-micro在其它微服务中,一般放common中,以避免依赖臃肿。

<!--knife4j:swagger的升级版本;引用所有的knife4j提供的资源,包括前端Ui的jar包-->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>2.0.2</version>
</dependency>

<!--其它依赖-->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>20.0</version>
</dependency>
<dependency>
    <groupId>io.projectreactor</groupId>
    <artifactId>reactor-core</artifactId>
    <version>3.4.17</version>
</dependency>
knife4j:
  enabled: true;
  contact-name: Ltter
  contact-url: https://www.baidu.com/
  contact-email: 6723885439275@qq.com
  title: 测试knife4j-Swagger2服务
  version: v1.0.0
  description: knife4j-Swagger2描述
  license: 哇呀呀呀```呔、何方妖孽
  license-url: https://blog.csdn.net/u013812135?type=blog
package com.learn.config;

import com.google.common.base.Predicates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Title Knife4jSwaggerConfig
 * @Description 配置文件
 * @Author Ltter
 * @Date 2022/8/17 15:48
 * @Version 1.0
 */
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(Knife4jSwaggerProperties.class)
public class Knife4jSwaggerConfig {

    @Autowired
    private Knife4jSwaggerProperties knife4jSwaggerProperties;

    @Bean
    public Docket customKnife4jSwaggerDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(customApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.learn"))
                .paths(PathSelectors.any())
                //不显示错误的接口地址 basic-error-controller
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build();
    }

    private ApiInfo customApiInfo() {
        return new ApiInfoBuilder()
                .title(knife4jSwaggerProperties.getTitle())
                .version(knife4jSwaggerProperties.getVersion())
                .description(knife4jSwaggerProperties.getDescription())
                .contact(new Contact(knife4jSwaggerProperties.getContactName()
                        , knife4jSwaggerProperties.getContactUrl()
                        , knife4jSwaggerProperties.getContactEmail()))
                .license(knife4jSwaggerProperties.getLicense())
                .licenseUrl(knife4jSwaggerProperties.getLicenseUrl())
                .build();
    }
}

GtiHub代码地址https://github.com/mrzltao/spring-boot-learns

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个通过 Swagger Codegen 生成 Python 代码的示例: 1. 首先,在本地安装 Swagger Codegen 工具。可以通过官方文档中的安装方法进行安装。 2. 创建一个 Swagger 规范文件,比如 `swagger.yaml`,内容如下: ``` swagger: '2.0' info: title: Example API version: '1.0.0' paths: /pets: get: summary: List all pets produces: - application/json responses: '200': description: OK schema: type: array items: type: object properties: id: type: integer format: int64 name: type: string ``` 这个 Swagger 规范文件定义了一个 `/pets` 路径,当使用 GET 方法请求该路径时,会返回一个包含所有宠物信息的 JSON 数组。 3. 使用 Swagger Codegen 生成 Python 代码。在终端中执行以下命令: ``` swagger-codegen generate -i swagger.yaml -l python -o ./petstore ``` 这个命令会使用 `swagger.yaml` 文件中的规范生成 Python 代码,并将代码输出到 `./petstore` 目录中。 4. 在 `./petstore` 目录中,可以看到生成的 Python 代码,包括 `README.md` 文件和 `swagger_client` 目录。 5. 在 Python 代码中,可以使用 `swagger_client` 包中的方法来调用 API。比如,要列出所有宠物信息,可以使用以下代码: ```python from swagger_client.api_client import ApiClient from swagger_client.pet_api import PetApi # 创建 API Client api_client = ApiClient() api_client.host = 'http://petstore.swagger.io/v2' # 创建 PetApi 实例 pet_api = PetApi(api_client) # 调用 list_pets 方法,列出所有宠物信息 pets = pet_api.list_pets() print(pets) ``` 这样,就可以使用 Swagger Codegen 生成的 Python 代码来调用 API 了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值