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

相关文章

Spring Boot整合Redis注解实现增删改查功能(Redis注解使用)

《SpringBoot整合Redis注解实现增删改查功能(Redis注解使用)》文章介绍了如何使用SpringBoot整合Redis注解实现增删改查功能,包括配置、实体类、Repository、Se... 目录配置Redis连接定义实体类创建Repository接口增删改查操作示例插入数据查询数据删除数据更

Java Lettuce 客户端入门到生产的实现步骤

《JavaLettuce客户端入门到生产的实现步骤》本文主要介绍了JavaLettuce客户端入门到生产的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 目录1 安装依赖MavenGradle2 最小化连接示例3 核心特性速览4 生产环境配置建议5 常见问题

使用python生成固定格式序号的方法详解

《使用python生成固定格式序号的方法详解》这篇文章主要为大家详细介绍了如何使用python生成固定格式序号,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以参考一下... 目录生成结果验证完整生成代码扩展说明1. 保存到文本文件2. 转换为jsON格式3. 处理特殊序号格式(如带圈数字)4

Java使用Swing生成一个最大公约数计算器

《Java使用Swing生成一个最大公约数计算器》这篇文章主要为大家详细介绍了Java使用Swing生成一个最大公约数计算器的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下... 目录第一步:利用欧几里得算法计算最大公约数欧几里得算法的证明情形 1:b=0情形 2:b>0完成相关代码第二步:加

Java 的ArrayList集合底层实现与最佳实践

《Java的ArrayList集合底层实现与最佳实践》本文主要介绍了Java的ArrayList集合类的核心概念、底层实现、关键成员变量、初始化机制、容量演变、扩容机制、性能分析、核心方法源码解析、... 目录1. 核心概念与底层实现1.1 ArrayList 的本质1.1.1 底层数据结构JDK 1.7

Java Map排序如何按照值按照键排序

《JavaMap排序如何按照值按照键排序》该文章主要介绍Java中三种Map(HashMap、LinkedHashMap、TreeMap)的默认排序行为及实现按键排序和按值排序的方法,每种方法结合实... 目录一、先理清 3 种 Map 的默认排序行为二、按「键」排序的实现方式1. 方式 1:用 TreeM

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.