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简单整合ElasticSearch实践

《SpringBoot简单整合ElasticSearch实践》Elasticsearch支持结构化和非结构化数据检索,通过索引创建和倒排索引文档,提高搜索效率,它基于Lucene封装,分为索引库、类型... 目录一:ElasticSearch支持对结构化和非结构化的数据进行检索二:ES的核心概念Index:

Python数据验证神器Pydantic库的使用和实践中的避坑指南

《Python数据验证神器Pydantic库的使用和实践中的避坑指南》Pydantic是一个用于数据验证和设置的库,可以显著简化API接口开发,文章通过一个实际案例,展示了Pydantic如何在生产环... 目录1️⃣ 崩溃时刻:当你的API接口又双叒崩了!2️⃣ 神兵天降:3行代码解决验证难题3️⃣ 深度

Linux内核定时器使用及说明

《Linux内核定时器使用及说明》文章详细介绍了Linux内核定时器的特性、核心数据结构、时间相关转换函数以及操作API,通过示例展示了如何编写和使用定时器,包括按键消抖的应用... 目录1.linux内核定时器特征2.Linux内核定时器核心数据结构3.Linux内核时间相关转换函数4.Linux内核定时

C#借助Spire.XLS for .NET实现在Excel中添加文档属性

《C#借助Spire.XLSfor.NET实现在Excel中添加文档属性》在日常的数据处理和项目管理中,Excel文档扮演着举足轻重的角色,本文将深入探讨如何在C#中借助强大的第三方库Spire.... 目录为什么需要程序化添加Excel文档属性使用Spire.XLS for .NET库实现文档属性管理Sp

C++ move 的作用详解及陷阱最佳实践

《C++move的作用详解及陷阱最佳实践》文章详细介绍了C++中的`std::move`函数的作用,包括为什么需要它、它的本质、典型使用场景、以及一些常见陷阱和最佳实践,感兴趣的朋友跟随小编一起看... 目录C++ move 的作用详解一、一句话总结二、为什么需要 move?C++98/03 的痛点⚡C++

Java方法重载与重写之同名方法的双面魔法(最新整理)

《Java方法重载与重写之同名方法的双面魔法(最新整理)》文章介绍了Java中的方法重载Overloading和方法重写Overriding的区别联系,方法重载是指在同一个类中,允许存在多个方法名相同... 目录Java方法重载与重写:同名方法的双面魔法方法重载(Overloading):同门师兄弟的不同绝

python中的flask_sqlalchemy的使用及示例详解

《python中的flask_sqlalchemy的使用及示例详解》文章主要介绍了在使用SQLAlchemy创建模型实例时,通过元类动态创建实例的方式,并说明了如何在实例化时执行__init__方法,... 目录@orm.reconstructorSQLAlchemy的回滚关联其他模型数据库基本操作将数据添

Spring配置扩展之JavaConfig的使用小结

《Spring配置扩展之JavaConfig的使用小结》JavaConfig是Spring框架中基于纯Java代码的配置方式,用于替代传统的XML配置,通过注解(如@Bean)定义Spring容器的组... 目录JavaConfig 的概念什么是JavaConfig?为什么使用 JavaConfig?Jav

Java数组动态扩容的实现示例

《Java数组动态扩容的实现示例》本文主要介绍了Java数组动态扩容的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1 问题2 方法3 结语1 问题实现动态的给数组添加元素效果,实现对数组扩容,原始数组使用静态分配

Java中ArrayList与顺序表示例详解

《Java中ArrayList与顺序表示例详解》顺序表是在计算机内存中以数组的形式保存的线性表,是指用一组地址连续的存储单元依次存储数据元素的线性结构,:本文主要介绍Java中ArrayList与... 目录前言一、Java集合框架核心接口与分类ArrayList二、顺序表数据结构中的顺序表三、常用代码手动