Reprinted: https://blog.csdn.net/xxoo00xx00/article/details/77163399
swagger study notes
Build environment:
- 1, jdk1.8
- 2,idea
- 3,spring-boot-starter-parent版本1.5.6.RELEASE
- 4,springfox-swagger2 And springfox-swagger-ui 版本2.2.2
1 Rapid environment construction
Create a new project, file->new->Porject->Spring Initializr->next- as shown below (idea professional version, community version can copy the pom file on git)
Add the following content to the pom.xml file (see clearly and then copy, not all content here)
<properties>
...
<swagger.version>2.2.2</swagger.version> ... </properties> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger.version}</version> </dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
Create a new swagger configuration file swaggerConfig.java in the config directory
@EnableSwagger2
@Configuration
public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com"))//扫描com路径下的api文档 .paths(PathSelectors.any())//路径判断 .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("《----我是title-----》")//标题 .description("《-----我是描述----》:http://www.google.com.hk")//描述 .termsOfServiceUrl("http://www.google.com.hk")//(不可见)条款地址 .contact(new Contact("zz","google.com.hk","[email protected]"))//作者信息 .version("6.6.6")//版本号 .build(); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
Create a new entity class User, the basic fields are as follows
@ApiModel(value = "User得实体,----》",reference = "我是参考")
public class User { @ApiParam(value = "姓名--------------",required = true) private String name; //在swagger-ui.html#页面中如果返回User,ModelModel Schema选项卡可见 @ApiModelProperty(value = "id",dataType = "String") private String id; //在http://localhost:8080/v2/api-docs最后一行的实体可见 @ApiModelProperty(value = "年龄----------",required = true) private Integer age; ...此处省略set和get方法 }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
Create a new TestController in the controller package, the content is as follows
@Api(value = "API - VehiclesController", description = "用户接口详情")
@RestController
@RequestMapping("/test") public class TestController { static Map<String, User> users = Collections.synchronizedMap(new HashMap<String,User>()); @ApiOperation(value="获取用户列表", notes="") @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful — 请求已完成"), @ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"), @ApiResponse(code = 401, message = "未授权客户机访问数据"), @ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"), @ApiResponse(code = 500, message = "服务器不能完成请求")} ) @RequestMapping(value={""}, method= RequestMethod.GET) public List<User> getUserList() { List<User> r = new ArrayList<User>(users.values()); return r; } ....此处省略n行代码 }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
Browse and change the address, visit the main page: http://localhost:8080/swagger-ui.html#
Browse and change the address, visit sagger's proprietary jsonAPI: http://localhost:8080/v2/api-docs
2 Description of common notes
Upper half
lower half
Lower bottom
3 List of all comments
The @Api
Api tag can mark a Controller class as a swagger document resource. How to use it
property name | Remark |
---|---|
value | url's path value |
tags | If this value is set, the value of value will be overwritten |
description | description of the api resource |
basePath | The base path can not be configured |
position | If you configure multiple APIs and want to change the order position of the display |
produces | For example, “application/json, application/xml” |
consumes | For example, “application/json, application/xml” |
protocols | Possible values: http, https, ws, wss. |
authorizations | Configured during advanced feature authentication |
hidden | Configure to true to hide in the document |
@ApiOperation definition of each url resource, usage
property name | Remark |
---|---|
value | url's path value |
tags | If this value is set, the value of value will be overwritten |
description | description of the api resource |
basePath | The base path can not be configured |
position | If you configure multiple APIs and want to change the order position of the display |
produces | For example, “application/json, application/xml” |
consumes | For example, “application/json, application/xml” |
protocols | Possible values: http, https, ws, wss. |
authorizations | Configured during advanced feature authentication |
hidden | Configure to true to hide in the document |
response | the returned object |
responseContainer | These objects are valid "List", "Set" or "Map". Others are invalid |
httpMethod | “GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS” and “PATCH” |
code | The status code of http defaults to 200 |
extensions | Extended properties |
@ApiParam标记
public ResponseEntity createUser(@RequestBody @ApiParam(value = “user”, required = true) User user)
property name | Remark |
---|---|
name | property name |
value | attribute value |
defaultValue | Default property value |
allowableValues | can not be configured |
required | Whether the attribute is required |
access | not too much description |
allowMultiple | Default is false |
hidden | hide this property |
example | for example |
@ApiImplicitParam's description of the container
property name | Remark |
---|---|
name | property name |
value | attribute value |
defaultValue | Defaults |
allowableValues | Can not be configured |
required | Whether the attribute is required |
access | Don't describe too much |
allowMutiple | Default is false |
dataType | type of data |
paramType | Parameter Type |
@ApiResponse
property name | Remark |
---|---|
code | http status code |
message | describe |
response | Default response class Void |
reference | Refer to the configuration in ApiOperation |
responseHeaders | 参考 ResponseHeader 属性配置说明 |
responseContainer | 参考ApiOperation中配置 |
@ResponseHeader(name=”head1”,description=”response head conf”)
属性名称 | 备注 |
---|---|
name | 响应头名称 |
description | 头描述 |
response | 默认响应类 Void |
responseContainer | 参考ApiOperation中配置 |
4文档编写规范建议
- entity的描述
@ApiModel(description = “我是描述”,value = “用户”)
对实体的描述
description:在v2/api-docs的实体看到描述,
value的值在@ApiImplicitParam注解中的dataType可用,
@ApiModelProperty(value = “用户姓名”,required = true,dataType = “String”)
private String name;
对字段的描述
value:1,入参和出参的ModelModel Schema选项卡可见,2,在v2/api-docs的实体字段描述可见
required:该属性是否必填写
dataType:该字段的数据类型
- controller的描述
@Api(value = “API”, description = “用户接口详情”,tags=”A”)
对controler的描述
value:访问某个controller的url的根路径值
description:对于该controller的的大概描述
tags:把api接口进行分分组
@ApiOperation(value = “获取用户详细信息”, notes = “根据url的id来获取用户详细信息”,httpMethod =”GET”)
对该方法的描述
value:主页面中对该接口的描述,位置在接口的最右边
notes:点开接口后,第一段描述。
httpMethod:HTTP请求的动作名,可选值有:”GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS” and “PATCH”。
@ApiImplicitParam(name = “id”, value = “用户ID”, required = true, dataType = “String”, paramType = “path”)
对参数的描述,如果多个参数需要用@ApiImplicitParams对其进行包裹
name:参数名称
value:参数的简短描述
required:是否必须传递的参数
dataType:参数类型,可以为类名,也可以为基本类型(String,int,Boolean)
paramType:参数的传入(请求)类型,可选的值有path, query, body, header or form。(如果在路径中提取参数用path比如:在/A/{XXX}路径中得到XXX的值)
@ApiParam(name = “user”, value = “userValue”, required = true)
对参数元信息的说明,一般这个注解只能被使用在JAX-RS 1.x/2.x的综合环境下,和ApiImplicitParam注解类似
required: whether the parameter is required
value: a brief introduction to the parameter
@ApiResponse(code = 200, message = "Successful - the request has been completed")
returns a description of the status code, if there are more than one, you can use the @ApiResponses annotation to wrap
code: the status code returned by the
server message: a brief description of the status code returned by the server
sample: pass the token in the header
@ApiImplicitParams({@ApiImplicitParam(name = "TOKEN", value = "Authorization token", required = true, dataType = "string", paramType = "header")})
- 1
5, Notes:
- For example, if the path parameter always passes {id}, you need to add prameType="path" to the ApiImplicitParam annotation
- The version problem needs to delete the jar package in m2. The swagger of 2.2.2 and the spring-boot-prent of 1.5.6 are the perfect match. I have tried many latest packages, and I feel that there are more or less problems!
- Both input parameters and output parameters can use an entity class, pay attention to check the value attribute of @ApiModel
6 Reference documents
There may be other reference documents not listed, sorry
https://gumutianqi1.gitbooks.io/specification-doc/content/tools-doc/spring-boot-swagger2-guide.html
http://www.jianshu.com/p/12f4394462d5
http://blog.didispace.com/springbootswagger2/
https://dzone.com/articles/spring-boot-restful-api-documentation-with-swagger
http://www.jianshu.com/p/b0b19368e4a8