table of Contents
I. Introduction and use
Second, the integration steps
Third, the explanatory notes
I. Introduction and use
Known: the world's most popular API framework
Official website: http://swagger.io/
To solve the problem:
Background isolated in the previous development model, communication interface definition reduced cost, convenient test development process, automatically generated interface document
Use:
1, the configuration file through the official website, write an interface to an interface
2, multi-pass configuration notes, json dynamically generated data is generated automatically by the code display frame
Second, the integration steps
Framework of the project requirements: In this paper, springboot
1, support the introduction of swagger in the pom file that is associated rely --- jar package
<!--依赖管理 -->
<dependencies>
<dependency> <!--添加Web依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><!--添加Swagger依赖 -->
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency><!--添加Swagger-UI依赖 -->
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency> <!--添加热部署依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency><!--添加Test依赖 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2, add the configuration --- that is written swagger startup class SwaggerConfig.java
package dcc.core;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
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 //声明启动Swagger2
public class SwaggerConfig{
@Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.epoch.ccfindcars.controller"))//扫描的包路径
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("反向寻车")//文档说明
.version("1.0.0")//文档版本说明
.build();
}
}
3, namely to write the interface documentation ---- integration swagger open spring configuration
Swagger2 basic use:
- The main purpose @Api described class / interface
- The method described uses @ApiOperation
- Parameter Description method @ApiImplicitParam
- Parameter Description @ApiImplicitParams method (Multi-Params)
- Documents @ApiIgnore ignore certain types / methods / parameters
Swagger2 uses annotations to write a document:
Write Swagger2 interface documentation is quite simple, just add annotation layer control (Controller) to describe the interface information can be.
package com.epoch.ccfindcars.controller;
import com.epoch.ccfindcars.entity.LotAddress;
import com.epoch.ccfindcars.entity.LotAddressList;
import com.epoch.ccfindcars.service.LotAddressService;
import com.epoch.ccfindcars.service.LotAddressServiceList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Author: ljj
* @Description: 反向寻车功能
* @Date:
*/
@RestController
@Api("反向寻车管理功能")
public class ReverseForCarController {
@Autowired
private LotAddressService lotAddressService;
@Autowired
private LotAddressServiceList lotAddressServiceList;
@ApiOperation("通过id确定唯一车牌")
@GetMapping("/getone")
@ApiImplicitParam(name = "id",value = "车位表对应的id",dataType = "int ")
public LotAddress getOneCatLotAddress(int id) {
LotAddress lotAddress = lotAddressService.OneCatLotAddress(id);
return lotAddress;
}
/**
* 快速寻车:通过输入车牌中的一个或多个字母或数字,快速查询车位
*
* @param carLicense
* @return lotAddressList
*/
@ApiOperation("通过车牌号,获取相关车牌列表")
@GetMapping("/serchlike")
@ApiImplicitParam(name = "carLicense",value = "车牌号",dataType = "String")
public List<LotAddressList> getCarLotAddress(String[] carLicense) {
StringBuffer sc = new StringBuffer();
for (int i = 0; i < carLicense.length; i++) {
sc.append(carLicense[i]);
}
String s = sc.toString();
System.out.println(s);
List<LotAddressList> lotAddressList = lotAddressServiceList.getCatAllRow(s);
return lotAddressList;
}
@ApiOperation("通过车位号来获取车位")
@GetMapping("/findcar")
@ApiImplicitParam(name = "carAddress",value = "车位号",dataType = "String")
public List<LotAddressList> getCarAddressByCarAddress(String carAddress) {
List<LotAddressList> carAddressByCarLicense = lotAddressService.findCarAddressByCarLicense(carAddress);
return carAddressByCarLicense;
}
}
4 Check out interface documentation
After the preparation of the document is complete, start the current project, open the browser:
[ HTTP: // localhost: 4040 / Swagger-ui.html ] - (port to write according to their own settings) to see the effect as follows:
5 test interface
The power of Swagger2 not only to quickly generate clean and elegant RestAPI document, while supporting the test operation of the interface method (similar to the client PostMan).
To get through the parking space number, for example, just 5 input parameters, click on the "Try" button:
6. In addition, this tutorial also provided additional UI localization tutorial , remove the trouble to read the official English interface. (Currently Swagger finished the tutorial is not found, because it is written in the official manual sucks ..)
①. The default English interface UI
Must have a lot of small partners have used Swagger, but after opening the UI interface, but it is such a style below, plain English and not very friendly interface, as people still used Chinese language interface.
②. Chinese custom interface
2.1 Add Home and translation
Focus here, in the src/main/resources
creation directory META-INF\resources
directory, then create a name for the "swagger-ui.html" HTML file. Figure:
Do not pay attention to the file name from wrong, then the following piece of content intact copy into it.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
<link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>
<script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>
<!--国际化操作:选择中文版 -->
<script src='webjars/springfox-swagger-ui/lang/translator.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lang/zh-cn.js' type='text/javascript'></script>
</head>
<body class="swagger-section">
<div id='header'>
<div class="swagger-ui-wrap">
<a id="logo" href="http://swagger.io">![](webjars/springfox-swagger-ui/images/logo_small.png)<span class="logo__title">swagger</span></a>
<form id='api_selector'>
<div class='input'>
<select id="select_baseUrl" name="select_baseUrl"></select>
</div>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
<div id='auth_container'></div>
<div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
</form>
</div>
</div>
<div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>
OK we're done visit http: // localhost: 4040 / swagger -ui.html look at display:
2.2 More detailed translation translation (non-essential)
If you want to adjust the translation, you can add zh-cn.js file in the META-INF \ resources \ webjars \ springfox-swagger-ui \ lang directory.
Then in the translation (zh-cn.js) to add translated content based on personal preferences, as follows
'use strict';
/* jshint quotmark: double */
window.SwaggerTranslator.learn({
"Warning: Deprecated":"警告:已过时",
"Implementation Notes":"实现备注",
"Response Class":"响应类",
"Status":"状态",
"Parameters":"参数",
"Parameter":"参数",
"Value":"值",
"Description":"描述",
"Parameter Type":"参数类型",
"Data Type":"数据类型",
"Response Messages":"响应消息",
"HTTP Status Code":"HTTP状态码",
"Reason":"原因",
"Response Model":"响应模型",
"Request URL":"请求URL",
"Response Body":"响应体",
"Response Code":"响应码",
"Response Headers":"响应头",
"Hide Response":"隐藏响应",
"Headers":"头",
"Try it out!":"试一下!",
"Show/Hide":"显示/隐藏",
"List Operations":"显示操作",
"Expand Operations":"展开操作",
"Raw":"原始",
"can't parse JSON. Raw result":"无法解析JSON. 原始结果",
"Example Value":"示例",
"Click to set as parameter value":"点击设置参数",
"Model Schema":"模型架构",
"Model":"模型",
"apply":"应用",
"Username":"用户名",
"Password":"密码",
"Terms of service":"服务条款",
"Created by":"创建者",
"See more at":"查看更多:",
"Contact the developer":"联系开发者",
"api version":"api版本",
"Response Content Type":"响应Content Type",
"Parameter content type:":"参数类型:",
"fetching resource":"正在获取资源",
"fetching resource list":"正在获取资源列表",
"Explore":"浏览",
"Show Swagger Petstore Example Apis":"显示 Swagger Petstore 示例 Apis",
"Can't read from server. It may not have the appropriate access-control-origin settings.":"无法从服务器读取。可能没有正确设置access-control-origin。",
"Please specify the protocol for":"请指定协议:",
"Can't read swagger JSON from":"无法读取swagger JSON于",
"Finished Loading Resource Information. Rendering Swagger UI":"已加载资源信息。正在渲染Swagger UI",
"Unable to read api":"无法读取api",
"from path":"从路径",
"server returned":"服务器返回"
});
Third, the usual explanatory notes
1, commonly used notes
@Api () for the class;
This class is a flag indicating swagger resources
@ApiOperation () method is used;
Operation represents a http request
@ApiParam () method is used, parameter field specifies;
Add metadata to represent the parameters (instructions or if required, etc.)
@ApiModel () for the class
Indicates the class will be described, the parameters for receiving entity class
@ApiModelProperty () method is used, the field
Representation of instructions or data operation model property changes
@ApiIgnore () for classes, methods, method parameters
This method represents a class or ignored
@ApiImplicitParam () method for
Represent individual request parameters
@ApiImplicitParams () method is used, comprising a plurality @ApiImplicitParam
@ApiResponse
Return parameters
2, the specific use
@Api () for the class;
parameter:
tags: explanatory, tags if there are multiple values, generates a plurality of list
value: with obsolete
hidde: No effect
description: Interface Description
Code:
Interface effects:
@ApiOperation () method is used;
value used in the methods described
notes for tips content
tags may be re-grouping (Conditional use)
Code:
Document effects:
@ApiImplicitParam () method for
Represent individual request parameters
@ApiImplicitParams () method is used, comprising a plurality @ApiImplicitParam
Parameter name name-
value- Parameter Description
dataType- data types
paramType- parameter type
@ApiResponse
Return Parameters Description
response: return object information
code: return status information
message: return text messages
Object information specific comments
@ApiModelProperty
Object Field Description
value: Field Name
example: Field Description