Swagger

简介

Swagger是一种接口描述语言,用于描述使用JSON表示的RESTful API。

Swagger与一组开源工具一起使用,以设计,构建,记录和使用RESTful Web服务。Swagger包括自动文档,代码生成和测试用例生成。

说人话:

没写项目前把接口文档写好,文档中要把前后端的接口规则定义好,大家照着这些规则去开发接口

快速入门

依赖

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-boot-starter</artifactId>
   <version>3.0.0</version>
</dependency>

配置

如果使用2.5.10以上版本,请加如下配置

spring.mvc.pathmatch.matching-strategy=ant_path_matcher      # path_pattern_parser

注解

@SpringBootApplication
@EnableOpenApi
public class SpringbootdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootdemoApplication.class, args);
    }
}

地址

http://localhost:8080/swagger-ui/index.html

结果

image-20230327235707883

@RestController
public class PersonController {

    @GetMapping("/findList")
    public  Map<String,Object>  findList() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code",200);
        hashMap.put("message","ok");
        hashMap.put("data",null);
        return hashMap;
    }
}

image-20230328000027715

注解

@Api

用在Controller层上的,表示对类的说明,tags="说明该类的作用,可以在UI界面上看到的注解",description是具体描述

@RestController
@Api(tags = "人",description="与人相关的操作")
public class PersonController {
  .....
}

@ApiOperation

  • 用在请求的方法上,说明方法的用途、作用

  • value="说明方法的用途、作用"

  • notes="方法的备注说明"

  • hidden=true UI界面上隐藏该接口

  • @ApiOperation(value = "查询所有人的数据",notes = "不需要传参")
      @GetMapping("/findList")
        public  Map<String,Object>  findList() {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("code",200);
            hashMap.put("message","ok");
            hashMap.put("data",null);
            return hashMap;
        }

image-20230328000715397

@ApiImplicitParams

  • @ApiImplicitParams:用在请求的方法上,表示一组参数说明

  • @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面

  • name:参数名,不能为null

  • value:参数的汉字说明、解释

  • required:参数是否必须传

  • defaultValue:参数的默认值

image-20230328001153888

image-20230328001529857

@ApiOperation(value = "根据id查询具体人的信息")
    @ApiImplicitParam(name = "id",value = "用户id",required = true,defaultValue = "1")
    @GetMapping("/findById")
    public  Map<String,Object>  findById(Integer id) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code",200);
        hashMap.put("message","ok");
        hashMap.put("data",null);
        return hashMap;
    }  

	
    @ApiOperation(value = "分页查询人的信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "请求页数",required = true,defaultValue = "1"),
            @ApiImplicitParam(name = "pageSIze",value = "请求条数",required = true,defaultValue = "10")
    })
    @GetMapping("/findByPage")
    public  Map<String,Object>  findById(Integer pageNum,Integer pageSize) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code",200);
        hashMap.put("message","ok");
        hashMap.put("data",null);
        return hashMap;
    }

@ApiModel

  • 用于响应类上,表示一个返回响应数据的信息

  • 这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候

  • value:标注实体是做什么的

  • description:描述信息,内容可以在UI界面显示出来

@ApiModelProperty

用在属性上,描述响应类的属性

value:信息描述,内容可以在UI界面显示出来

required:必填值

hidden:可以在UI界面上隐藏不显示,比如一些is_deleted这些前端是不需要传递的

@ApiOperation(value = "根据id修改人的信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",required = true,defaultValue = "1")
    })
    @PostMapping("/updateById")
    public  Map<String,Object>  updateById(Integer id, @RequestBody Person person) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code",200);
        hashMap.put("message","ok");
        hashMap.put("data",null);
        return hashMap;
    }
@Data
@ApiModel("人")
public class Person {
    @ApiModelProperty("用户id")
    private Integer id;
    @ApiModelProperty(value = "用户姓名",required = true)
    private String name;
    @ApiModelProperty("用户年龄")
    private Integer age;
    @ApiModelProperty(value = "密码",hidden = true)
    private String password;
}

image-20230328002217465

knife4j

概述

image-20230328002709407

knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案

他是对原生的swagger进行了封装

Knife4j · 集Swagger2及OpenAPI3为一体的增强解决方案. | Knife4j

依赖

以前的springfox-boot-starter就不需要了,直接引入如下依赖即可

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

测试地址

http://localhost:8080/doc.html#/home

image-20230328002943849

配置代码

package com.codingfuture.swagger_demo.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.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * @author Petrel
 */
@Configuration
//@EnableSwagger
public class ConfigSwagger {
    public class Swagger2 {

        //默认文档地址为 http://localhost:8088/swagger-ui.html
        //新接口文档地址为 http://localhost:8080/doc.html#/home
        @Bean
        public Docket createRestApi(){

            return new Docket(DocumentationType.SWAGGER_2)          //指定Api类型为Swagger2
                    .apiInfo(apiInfo())                             //指定文档汇总信息
                    .select()
                    .apis(RequestHandlerSelectors.any()) //          或者指定controller包路径
                    .paths(PathSelectors.any())                      //指定展示所有controller
                    .build();
        }

        private ApiInfo apiInfo(){
            //返回一个apiinfo
            return new ApiInfoBuilder()
                    .title("api接口文档")                               //文档页标题
                    .contact(new Contact( "Petrel",
                            "https://www.123.com",
                            "123@sina.com"))                                  // 联系人信息
                    .description("简介")                            // 详细信息
                    .version("1.0.1")                                  // 文档版本号
                    .termsOfServiceUrl("https://www.123.com")                      //网站地址
                    .build();
        }

    }
}

<think>好的,我现在需要处理用户关于Swagger API文档工具的使用指南的请求。首先,用户明确提到想了解Swagger或查找相关技术资料,特别是使用指南。根据用户提供的系统级指令,我需要确保回答结构清晰,使用中文,正确应用LaTeX格式,并生成相关问题。同时,用户的历史引用中有两篇关于Swagger的文章,我需要参考这些内容,但也要注意用户指出这些引用并非真实需求,可能需要更多依赖之前的互动,不过当前对话中用户只提到了这两篇,所以得合理利用。 首先,我应该先确定用户的需求层次。他们可能希望了解Swagger的基本概念、如何安装配置、如何编写API文档以及相关工具的使用,比如生成离线文档。根据引用[1],Swagger用于创建和管理RESTful API文档,提供交互式测试界面。引用[2]提到一个离线工具,可以转换在线文档为HTML或Markdown。因此,在回答中需要涵盖基础使用步骤,并可能提到离线工具作为扩展内容。 接下来,我需要按照用户的要求分步骤说明,结构清晰。可能需要分为以下几个部分:1. Swagger简介;2. 安装与配置;3. 编写API文档;4. 生成离线文档。每个部分需要简明扼要,同时嵌入引用标记。例如,在介绍Swagger时引用[^1],在离线工具部分引用[^2]。 另外,需要注意LaTeX格式的应用。比如,变量或技术术语如YAML文件是否需要使用行内数学表达式?可能不需要,但如果有示例代码中的路径或文件名,可能需要用代码块而非LaTeX。用户要求行内数学表达式用$...$,但技术文档中的代码部分应使用代码块,如示例中的Python代码。因此,在回答中,我会正确使用代码块和LaTeX,比如在提到数学公式时使用,但可能在这个主题下数学公式较少,更多是代码示例。 生成相关问题部分,需要考虑用户可能进一步询问的内容,比如Swagger UI的定制、安全配置、与其他工具的对比、离线文档工具的具体使用步骤等。需要确保问题覆盖用户可能感兴趣的扩展话题。 最后,检查是否符合所有系统指令:中文回答、正确格式、引用标识自然、相关问题生成。需要确保没有使用Markdown格式,除了代码块,但用户示例中的代码块使用了```python,所以可能允许。同时,回答中的引用标识应放在相关段落末尾,如[^1]和[^2]。</think>### Swagger API 文档工具使用指南 #### 1. Swagger 简介 Swagger(现称为 OpenAPI 规范)是一套用于设计、构建和记录 RESTful API 的开源工具集。它通过标准化的 YAML/JSON 格式描述 API 结构,并提供交互式界面$^{[^1]}$。核心功能包括: - **API 设计**:使用 `swagger.yaml` 或 `swagger.json` 定义接口 - **文档生成**:自动生成可读性强的 HTML 页面 - **接口测试**:直接在浏览器中模拟 API 调用 #### 2. 安装与配置 以 Node.js 环境为例: ```bash # 安装 Swagger 命令行工具 npm install -g swagger # 初始化项目 swagger project create my-api ``` 配置文件 `config/default.yaml` 中可设置服务器端口、数据库连接等参数$^{[^1]}$。 #### 3. 编写 API 文档 创建 `api/swagger/swagger.yaml` 文件: ```yaml swagger: "2.0" info: title: 用户管理系统 version: 1.0.0 paths: /users: get: summary: 获取用户列表 responses: 200: description: 成功返回用户列表 ``` #### 4. 生成离线文档 使用 SwaggerOfflineDoc 工具转换在线文档为离线格式$^{[^2]}$: ```bash # 下载工具 git clone https://github.com/example/SwaggerOfflineDoc # 生成 HTML 文档 python convert.py --input http://api.example.com/swagger.json --format html ``` #### 5. 高级功能 - **安全定义**:添加 OAuth2/JWT 认证 ```yaml securityDefinitions: Bearer: type: apiKey name: Authorization in: header ``` - **数据模型**:定义可复用的数据结构 ```yaml definitions: User: type: object properties: id: type: integer name: type: string ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gao_xu_sheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值