springboot项目使用Swagger RestAPI最佳说明文档

本文主要是介绍springboot项目使用Swagger RestAPI最佳说明文档,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

#springboot项目使用Swagger RestAPI最佳说明文档

我们在开发各种rest服务的时候,需要给出rest api的介绍使用。如果没有rest API的介绍使用文档,除了看源代码几乎没人知道怎么使用。那么如何来编写rest API的说明文档了? 当然我们可以自己写一个类似javadoc的工具,然后每次构建的时候生成对应的html, 或者字节开发注解,然后根据一定规则生成rest doc文档, 那么有没有一种开源的,统一并且便捷好用的rest 说明文档工具了? 当然有,那就是Swagger.

我们先看看Swagger官方网站是如何介绍该项目的。
Swagger–The World’s Most Popular API Tooling, 世界上最流行的API工具。

下面我们直接进入正题,如何在springboot项目中使用Swagger。总共分为三部
第一步,引入swagger依赖
第二部,在spring-boot中配置swagger-ui界面
第三步,提供API文档页基本信息
第四步,给rest API编写文档
项目在这里。 欢迎下载和关注, 谢谢!

#第一步引入swagger依赖
在pom文件中添加如下依赖

        <!-- Use Swagger for rest API --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.8.0</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.8.0</version></dependency>

#第二步 在spring-boot中配置swagger-ui界面
在我们项目中增加一个类WebMvcConfig。

package com.yq.demo.config;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");}}

#第三步 提供API文档页基本信息
也是添加一个新类
package com.yq.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.service.Contact;
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;

@Configuration
@EnableSwagger2
public class Swagger2 {
//swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage(“com.yq.demo.controller”))
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(“Spring Boot 测试使用 Swagger2 构建RESTful API”)
.contact(new Contact(“EricYang”, “https://github.com/xyz/abc.git”, "test1@163.com"))
.version(“1.0”)
.description(“User API 描述”)
.build();
}

}

#第四步,给rest API编写文档
这一步是我们的主要工作,这里我们给两个Controller编写api文档
第一个是HelloWorldController, 它有一个get rest api显示Hello World

    @ApiOperation(value = "hello demo", notes = "just for demo")@GetMapping(value = "/hello", produces = "text/plain;charset=UTF-8")public String hello() {return "Hello World";}

可以看到@GetMapping(value = “/hello”, produces = “text/plain;charset=UTF-8”)
其中的value = “/hello"就是我们rest的路径, 因为我们返回的是字符串,所以使用"text/plain;charset=UTF-8”
下面是另外一个UserController, API比较多, 我们选择其中2个,项目类容可以参看源代码

    @ApiOperation(value = "add new user", notes = "add new user to system")@ApiImplicitParams({@ApiImplicitParam(name = "userName", value = "userName", required = true, dataType = "String", paramType = "query"),@ApiImplicitParam(name = "password", value = "密码", required = true ,dataType = "String", paramType = "query"),@ApiImplicitParam(name = "fullName", value = "fullName", required = true ,dataType = "String", paramType = "query"),@ApiImplicitParam(name = "email", value = "email", required = true ,dataType = "String", paramType = "query"),@ApiImplicitParam(name = "usertype", allowableValues="1,2,3", required = false ,dataType = "int", paramType = "query"),@ApiImplicitParam(name = "dateformat", value = "dateformat", required = false ,dataType = "String", paramType = "query"),@ApiImplicitParam(name = "timeforamt", value = "timeforamt", required = false ,dataType = "String", paramType = "query"),@ApiImplicitParam(name = "timezone", value = "timezone", required = false ,dataType = "String", paramType = "query"),@ApiImplicitParam(name = "language", value = "language", required = false ,dataType = "String", paramType = "query")})@PostMapping(value = "/add", produces = "application/json;charset=UTF-8")public  @ResponseBody User addNewUser(@RequestParam String userName,@RequestParam String password,@RequestParam String fullName,@RequestParam String email,@RequestParam Integer usertype,@RequestParam(value = "dateformat", defaultValue = "yyyy-MM-dd") String dateformat,@RequestParam(value = "timeforamt", defaultValue = "HH:mm:ss") String timeforamt,@RequestParam(value = "timezone", defaultValue = "GMT+8") String timezone,@RequestParam(value = "language", defaultValue = "zh_CN") String language) {User user = new User();user.setUsername(userName);user.setFullname(fullName);user.setEmail(email);user.setLanguage(language);user.setPassword(password);user.setActive(1);user.setUserType(usertype);user.setCan_delete(1);user.setTimeZone(timezone);user.setTimeFormat(timeforamt);user.setDateFormat(dateformat);userRepository.save(user);return user;}

下面这个是根据FullName进行查询的例子。其中只有一个path的参数fullname

    @ApiOperation(value = "findByFullName", notes = "find by fullName")@ApiImplicitParam(name = "fullname", value = "fullname", required = true, dataType = "String", paramType = "path")@GetMapping(value = "/findByFullName/{fullname}", produces = "application/json;charset=UTF-8")@ResponseBodypublic User getUserByFullName(@PathVariable String fullname){User user = userRepository.getByFullName(fullname);return user;}

最后运行我们的项目, 在浏览器打开http://127.0.0.1:8080/swagger-ui.html

示例图1
这里写图片描述

选择运行findByFullName
这里写图片描述

这篇关于springboot项目使用Swagger RestAPI最佳说明文档的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/251662

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。