springfox集成openapi实践

一 。openapi介绍

  OpenAPI的前身是swagger规范。Swagger是一套有助于前后端分离,接口管理和测试工具集
  SwaggerTM是一个用于描述和文档化RESTful接口的项目。 
Swagger规范定义了一系列的文件,用以描述API。这些文件可以被Swagger-UI项目用于展示API,也可以被Swagger-Codegen项目用于生成代码。一些其他的工具也可以利用这些文件,例如测试工具soapui。

规划文件格式:

格式是遵循JSON格式的。YAML作为JSON的一个超集,也是被支持的。 
有关于field,有两种: 
第一种是fixed fields,是说field的名称是固定的; 
第二种是Patterned fields,field的名字不是固定的,而是使用正则表达式匹配。

filed名称大小写敏感

文件结构

Swagger的规范要求将API用一个单一的文件表示。不过,定义可以拆成多个文件。使用$ref将他们拼合在一起。这符合JSON Schema规范。 
按照惯例,Swagger规范文件命名为swagger.json。

Swagger文件根元素(具体节点描述参考官网https://swagger.io/docs/specification/basic-structure/)

名称类型描述
swaggerstring必填。值必须为“2.0”
infoInfo对象必填。提供有关于API的元数据。
hoststringhost地址,域名或者是ip。可以包含端口,但不得包含其他路径
basePathstring必须以”/”开头,定义基础路径。不支持路径模板
schemesstring数组定义传输协议,必须从以下选择:http、https、ws、wss。如果不指定schemes,默认的scheme就是访问Swagger时访问的协议
consumesstring数组定义一系列可以被消费的MIME类型。
producesstring数组定义一系列可以被生产的MIME类型。
pathsPaths对象必填。可获得的paths和操作符。
definitionsDefinitions对象持有通过操作生产和消费的数据类型
parametersParameters Definitions对象持有操作时使用的参数。
responsesResponses Definitions对象持有操作的结果。
securityDefinitionsSecurity Definitions对象安全策略
securitySecurity Definitions对象数组整体安全策略
tagsTag对象数组标签
externalDocsExternal Documentation对象添加外部文档
基于jax-rf的注解规范 参考(https://github.com/swagger-api/swagger-core/wiki/Annotations-2.X)

使用springfox集成swagger 参考(https://github.com/springfox/springfox) 点击文档可进入

http://springfox.github.io/springfox/docs/current/

二。 openapi工具集swagger

swagger是围绕openapi规范构建的一组开源工具,可以帮助您设计、构建、记录和使用RESTAPI。 
主要的swagger工具包括:

  •     swagger编辑器--基于浏览器的编辑器,您可以在其中编写openapi规范。
  •    swagger UI--将openapi规范呈现为交互式API文档(界面展示openapi规范文件 更清晰明了)。
  •    swagger codegen--从openapi规范生成服务器存根和客户机库。

1. 安装swagger编辑器 

编辑器可以编辑openapi规范文件 预览ui效果等 安装过程参考 (https://swagger.io/docs/swagger-tools/#swagger-editor-documentation-0)

准备服务器 centos7 ip 192.168.58.144

swagger编辑器 需要nodejs环境支持 

yum -y install epel-release.noarch 
yum -y install nodejs npm

安装swagger编辑器

yum -y install openssl openssl-devel
wget https://github.com/swagger-api/swagger-editor/releases/download/v2.10.4/swagger-editor.zip
unzip swagger-editor.zip
http-server swagger-editor

启动后使用浏览器访问

http://192.168.58.144:8080/#/

界面出现可以左侧便捷openapi  右侧ui方式显示 菜单项 Generate Server可以生成不同环境下的服务器代码 也可以生成调用的客户端代码


2 安装swaggerui

ui是可以直接通过读取openapi文档来直接可视化api 

官网文档提供的是2.X版本安装 3.X版本 直接解压即可用 不过没找到汉化的方式 这里就安装官方文档安装2.X吧

文档地址:https://swagger.io/docs/swagger-tools/
github地址:https://github.com/swagger-api/swagger-ui(这是3.X)
3.X代码下文档有提供2.X代码地址 https://github.com/swagger-api/swagger-ui/tree/2.x
下载zip代码包

解压后目录 swagger-ui-2.xdist 就是ui的目录 进入dist目录 双击index.html可以单击使用 也可以服务器部署使用

cd swagger-ui-2.xdist && http-server -p8888
访问地址 
http://192.168.58.144:8888/

界面效果为(默认有个openapi的json 可以点击explore预览ui效果):、


汉化过程参考官方文档

打开index.html文件 将js的以下两行放开 将js替换成 zh-cn.js

<!-- Some basic translations -->
  <script src='lang/translator.js' type='text/javascript'></script>
  <script src='lang/zh-cn.js' type='text/javascript'></script>

汉化后的界面是



三 。springfox集成 swagger

springboot使用springfox集成swagger2(http://springfox.github.io/springfox/docs/current/#springfox-support-for-jsr-303)

添加maven依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cn.et</groupId>
	<artifactId>springfox</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.8.0</version>
		</dependency>
		<dependency>
    <groupId>io.springfox.ui</groupId>
    <artifactId>springfox-swagger-ui-rfc6570</artifactId>
    <version>1.0.0</version>
</dependency>
	</dependencies>
</project>

添加main方法测试

package springfox;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import io.swagger.annotations.ApiOperation;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.DocExpansion;
import springfox.documentation.swagger.web.ModelRendering;
import springfox.documentation.swagger.web.OperationsSorter;
import springfox.documentation.swagger.web.TagsSorter;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Controller
@EnableAutoConfiguration
@EnableSwagger2

public class RestController {

	@ApiOperation(value = "helloworld方法",
		      notes = "${RestController.home}") 
	@RequestMapping(value="/",method=RequestMethod.GET)
	@ResponseBody
	String home() {
		return "Hello World!";
	}

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

	@Bean
	  public Docket petApi() {
	    return new Docket(DocumentationType.SWAGGER_2)
	        .select()
	          .apis(RequestHandlerSelectors.any())
	          .paths(PathSelectors.any())
	          .build()
	        .pathMapping("/");
	        
	  }
	  @Bean
	  UiConfiguration uiConfig() {
	    return UiConfigurationBuilder.builder()
	        .deepLinking(true)
	        .displayOperationId(false)
	        .defaultModelsExpandDepth(1)
	        .defaultModelExpandDepth(1)
	        .defaultModelRendering(ModelRendering.EXAMPLE)
	        .displayRequestDuration(false)
	        .docExpansion(DocExpansion.NONE)
	        .filter(false)
	        .maxDisplayedTags(null)
	        .operationsSorter(OperationsSorter.ALPHA)
	        .showExtensions(false)
	        .tagsSorter(TagsSorter.ALPHA)
	        .validatorUrl(null)
	        .build();
	  }
}

其他api注解参考 官网 访问swagger-ui界面(http://localhost:8080/swagger-ui.html#/rest-controller)



原文地址:https://www.cnblogs.com/liaomin416100569/p/9331140.html