swagger使用这些就够了

swagger简单应用

简单介绍好处就是借助Swagger可以为用户,团队和企业简化API开发。

是一款RESTFUL接口的文档在线自动生成+功能测试功能软件

  • 集成简单,学习成本低
  • 能有效简化团队协作成本
1. 使用springboot集成swagger引入如下依赖:
<!-- https://mvnrepository.com/artifact/com.spring4all/swagger-spring-boot-starter -->
<dependency>
    <groupId>com.spring4all</groupId>
    <artifactId>swagger-spring-boot-starter</artifactId>
    <version>1.9.0.RELEASE</version>
</dependency>
2. application.yml配置
swagger:
  enabled: true #是否开启swagger 默认true
  base-package: com.itmck.web
  contact:
    name: miaochangke
    email: 8080@163.com
    url:
  title: swagger测试项目标题
  description: 文档描述
  ui-config:
    json-editor: true #启用json编辑器


spring:
  servlet:
    multipart:      ##自定上传文件大小
      max-file-size: 10MB
      max-request-size: 10MB
3.启动类上启用swagger注解 @EnableSwagger2Doc 如下:
@EnableSwagger2Doc
@SpringBootApplication
public class MybatisPlusDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusDemoApplication.class, args);
    }
}
4.swagger注解详解:
@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"
 
@ApiIgnore: 类上,表示隐藏这个类不在swagger-ui中展示 

@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"
 
 
@ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body-->请求参数的获取:@RequestBody(代码中接收注解)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="int" 代表请求参数类型为int类型,当然也可以是Map、User、String等;     
        defaultValue:参数的默认值
 
 
@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类
 
 
@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性

5:swaggwer注解演示:

控制器演示 这里基本使用比较多注意事项演示如下:

@Slf4j
@Api(value = "SwaggerActionController文档测试",tags = "控制器作用")
@RestController
public class SwaggerActionController {


    @ApiOperation(value = "swaggwer测试", notes = "swagger使用演示1")
    @PostMapping("/hello")
    public Student helloSwagger(@RequestBody Student student) {

        return student;
    }


    @ApiOperation(value = "swaggwer测试2", notes = "swagger使用演示2")
    @GetMapping("hello2")
    public Student helloSwagger2(Student student) {

        return student;
    }

    @ApiOperation(value = "swaggwer测试3", notes = "swagger使用演示3")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "age", value = "年龄", dataType = "Integer",paramType = "path")
    })
    @GetMapping("hello3/{name}/{age}")
    public String helloSwagger3(@PathVariable  String name,@PathVariable int age) {


        return "my name is:"+name+" and age is : "+age;
    }

    @ApiOperation(value = "swaggwer测试4", notes = "swagger使用演示4")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", dataType = "String",paramType = "path"),
            @ApiImplicitParam(name = "address", value = "地址", dataType = "String",paramType = "query")
    })
    @GetMapping("hello4/{name}")
    public String helloSwagger4(@PathVariable  String name,@RequestParam String address) {


        return "my name is:"+name+" address: "+address;
    }

    @ApiOperation(value = "上传swagger演示", notes = "swagger演示上传",consumes = "multipart/form-data",hidden = true)
    @PostMapping("hello5/{name}")
    public String helloSwagger5(@PathVariable  String name,@RequestParam("qqfile") MultipartFile file) {

        String name1 = file.getName();
        return "my name is:"+name+"正在测试上传文件:"+name1;
    }

    @ApiOperation(value = "swaggwer隐藏方法", notes = "swaggwer隐藏方法",hidden = true)
    @PostMapping("hello6/{name}")
    public String helloSwagger6(@PathVariable  String name) {


        return "my name is:"+name;
    }

Model演示

@Data
@ApiModel(value = "Student类")
public class Student {


    @ApiModelProperty(value = "姓名",name = "name",example = "itmck",dataType ="String")
    private String name;

    @ApiModelProperty(value = "年龄",name = "age",example = "25")
    private int  age;

    @ApiModelProperty(value = "邮箱",name = "email",example = "17355805355@163.com")
    private String email;


    @ApiModelProperty(value = "地址",name = "address",example = "安徽阜阳")
    private String address;

	//hidden = true:隐藏这个方法
    @ApiModelProperty(value = "性别",name = "sex",example = "男",hidden = true)
    private  String sex;

}
6:本地启动后访问:http://127.0.0.1:8080/swagger-ui.html 界面如下:

在这里插入图片描述

swaggwe2集成方式2

1引入依赖
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.6.1</version>
</dependency>
 
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.6.1</version>
</dependency>
5配置swagger信息
@Configuration
public class Swagger2 {
 
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.basePackage("com.itmk"))// API接口包扫描路径
				.paths(PathSelectors.any())
				.build();
	}
	
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("springboot利用swagger构建api文档")
				.description("简单优雅的restfun风格,https://mp.csdn.net/console/article")
				.termsOfServiceUrl("https://mp.csdn.net/console/article")
				.version("1.0")
				.build();
	}
}

启动类 @EnableSwagger2
@SpringBootApplication
@EnableSwagger2
public class SpringbootSwagger2Application {
 
	public static void main(String[] args) {
		SpringApplication.run(SpringbootSwagger2Application.class, args);
	}
}

鉴权swagger-ui.html

1.引入如下依赖:
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.application.yml新增
spring:
  security:
    user:
      name: mck
      password: 123
3.这时候访问http://127.0.0.1:8080/swagger-ui.html会出现如下:

在这里插入图片描述

4.自定义鉴权规则:如只想拦截 /swagger-ui.html 其余不拦截.增加如下代码
@EnableWebSecurity
@Configuration
public class SwaggerConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable()//禁用csrf跨站请求伪造
                .authorizeRequests()//认证请求
                .antMatchers("/swagger-ui.html").authenticated() //这里只认证 /swagger-ui.html
                .anyRequest().permitAll()//其他放行
                .and().formLogin()
                .and().headers().frameOptions().disable();

    }
}

题外话.如何优雅的进行入参的非空验证,避免出现过多垃圾代码
  if(StringUtils.isBlank(student.getName())){
  
      return "姓名非空";
  }

controller层可以使用 @ValidatedBindingResult
    public Map<String,Object> helloSwagger0(@Validated  @RequestBody Student student, BindingResult bindingResult) {
        Map<String,Object> map = new HashMap<>();
        if (bindingResult.hasErrors()){
            bindingResult.getFieldErrors().forEach(error->{
                log.error("参数:{},校验失败,原因:{}",error.getField(),error.getDefaultMessage());
            });
            map.put("message", "非空校验失败");
            map.put("flag", false);
        }
        return map;
    }

Model

@Data
public class Student {

    @NotNull(message = "姓名不能为空")
    private String name;

}

更多关于验证@Validated 使用自行百度细节

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【优质项目推荐】 1、项目代码均经过严格本地测试,运行OK,确保功能稳定后才上传平台。可放心下载并立即投入使用,若遇到任何使用问题,随时欢迎私信反馈与沟通,博主会第一时间回复。 2、项目适用于计算机相关专业(如计科、信息安全、数据科学、人工智能、通信、物联网、自动化、电子信息等)的在校学生、专业教师,或企业员工,小白入门等都适用。 3、该项目不仅具有很高的学习借鉴价值,对于初学者来说,也是入门进阶的绝佳选择;当然也可以直接用于 毕设、课设、期末大作业或项目初期立项演示等。 3、开放创新:如果您有一定基础,且热爱探索钻研,可以在此代码基础上二次开发,进行修改、扩展,创造出属于自己的独特应用。 欢迎下载使用优质资源!欢迎借鉴使用,并欢迎学习交流,共同探索编程的无穷魅力! 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip 基于业务逻辑生成特征变量python实现源码+数据集+超详细注释.zip
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。
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、付费专栏及课程。

余额充值