使REST API易于使用的真正关键是好的文档。 但是,即使您的文档做得不错,您也需要设置公司流程的权利,以正确,及时地发布它。 确保利益相关者按时收到是一回事,但是您也要负责API和文档中的更新。 自动完成此过程可轻松解决问题,因为您的文档不再是静态交付的,而变成了活物。 在上一篇文章中,我讨论了如何将Swagger与带有Jersey的Spring应用程序集成。 现在该向您展示如何创建文档并将其发布给其他人查看。
在深入了解实际文档之前,让我们从其形式和属性开始一些注意。 我们将使用批注为我们的API提供元数据,从而回答问题的方式。 但是为什么呢? 一方面,我们正在为已经存在注释的地方(如API端点或控制器)提供新的注释(与Spring MVC集成的情况下)。 但另一方面,这种方法在一次交付中绑定应用程序,API和文档的发布周期方面具有突出的优势。 使用这种方法,我们可以创建和管理小的内聚单元,从而确保对文档及其版本进行适当的分段。
创建端点文档
一切都从端点开始。 为了使Swagger知道您的端点,您需要使用@Api
注释对您的类进行注释。 基本上,您要做的就是命名端点并为用户提供一些说明。 这正是我在以下代码段中所做的。 如果您需要使用API文档进行更详细的介绍,请查看下面的@Api
注释说明。
package com.jakubstas.swagger.rest;/*** REST endpoint for user manipulation.*/
@Api(value = "users", description = "Endpoint for user management")
@Path("/users")
public class UsersEndpoint {...
}
要验证结果,只需从basePath
变量中输入URL,然后在浏览器中输入/api-docs
。 这是API资源清单所在的地方。 在注释了三个端点并访问http://[hostname]:[port]/SpringWithSwagger/rest/api-docs/
之后,您可能会看到类似于以下片段的内容:
{"apiVersion":"1.0","swaggerVersion":"1.2","apis":[{"path":"/users","description":"Endpoint for user management"},{"path":"/products","description":"Endpoint for product management"},{"path":"/employees","description":"Endpoint for employee listing"}]
}
但是,请注意,为了使API出现在API列表中,您必须至少使用Swagger注释来注释一个API方法。 如果没有注释任何方法(或尚未提供任何方法),则将不处理和发布API文档。
@Api批注
描述顶级API。 具有@Api
批注的类将包含在资源列表中。
注释参数:
-
value
– Api的简短说明 -
description
-此类的一般描述 -
basePath
–所有@Path
元素之前的基本路径 -
position
–资源清单中此Api的可选显式排序 -
produces
-此Apiproduces
内容类型 -
consumes
–此Apiconsumes
媒体类型 -
protocols
–该Api所需的协议(即https) -
authorizations
-此Api所需的授权
运营文件
现在,让我们进入API文档的关键部分。 操作文档基本上有两个主要部分-操作描述和响应描述。 让我们从操作说明开始。 使用注释@ApiOperation
提供了某些方法的详细说明,其响应,HTTP方法以及下面注释说明中提供的其他有用信息。 在以下代码示例中可以看到Swagger的操作声明的示例。
@ApiOperation批注
描述针对特定路径的操作或通常为HTTP
方法。 具有等效路径的操作在Api声明的数组中分组。
注释参数:
-
value
–操作简要说明 -
notes
–操作的详细说明 -
response
操作中的默认响应类 -
responseContainer
–如果响应类在容器内,请在此处指定 -
tags
–目前尚未在阅读器中实施,保留以备将来使用 -
httpMethod
–HTTP
方法,即GET
,PUT
,POST
,DELETE
,PATCH
,OPTIONS
-
position
–允许在Api声明中对操作进行显式排序 -
nickname
–操作的昵称,以覆盖注释扫描程序检测到的昵称 -
produces
-此Apiproduces
内容类型 -
consumes
–此Apiconsumes
媒体类型 -
protocols
–该Api所需的协议(即https) -
authorizations
-此Api所需的授权
您可能会注意到@ApiOperation
批注中使用了response参数,该参数指定了操作的响应类型(返回类型)。 如您所见,该值可以与方法返回类型不同,因为它仅用于API文档。
@GET
@Path("/{userName}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Returns user details", notes = "Returns a complete list of users details with a date of last modification.", response = User.class)
@ApiResponses(value = {@ApiResponse(code = 200, message = "Successful retrieval of user detail", response = User.class),@ApiResponse(code = 404, message = "User with given username does not exist"),@ApiResponse(code = 500, message = "Internal server error")}
)
public Response getUser(@ApiParam(name = "userName", value = "Alphanumeric login to the application", required = true) @PathParam("userName") String userName) {...
}
接下来,看看@ApiParam
。 向客户描述满足您的需求所需的内容总是很有用的。 这是@ApiParam
批注的主要目的。 无论您使用的是路径还是查询参数,都应始终提供此参数代表的含义。
@ApiParam批注
表示Api操作中的单个参数。 参数是操作的输入。
注释参数:
-
name
–参数名称 -
value
–参数说明 -
defaultValue
–默认值–如果没有给出JAX-RS@DefaultValue
-
allowableValues
–该端点接受的值的描述 -
required
–指定参数是否为必需 -
access
–指定一个可选的访问值以在Filter
实现中进行Filter
。 如果用户无权访问某些参数,则可以隐藏这些参数 -
allowMultiple
–指定参数是否可以提供多个值
最后,让我们看一下用消息和HTTP代码记录实际方法响应的方式。 Swagger带有@ApiResponse
批注,当使用@ApiResponses
包装器进行包装时,可以多次使用。 这样,您可以覆盖代码的所有替代执行流程,并为API客户端提供完整的API操作说明。 每个响应都可以用HTTP返回码,结果描述和结果类型来描述。 有关@ApiResponse
更多详细信息,请参见下面的描述。
@ApiResponse批注
ApiResponse
表示来自服务器的一种响应。 这可以用来描述成功代码以及错误。 如果您的Api具有不同的响应类别,则可以在此处通过将响应类别与响应代码相关联来描述它们。 注意,Swagger不允许单个响应代码具有多种响应类型。
注释参数:
-
code
–描述的响应代码 -
message
–响应中的人类可读消息 -
response
–描述消息有效负载的可选响应类
使用这些注释非常简单,并提供了结构良好的方法来描述API的功能。 如果要检查文档的外观,只需将@Api
批注中的参数value
的值附加到指向资源列表的URL上,输入指向端点之一的API文档的URL。 注意不要误输入@Path
注释的值(除非它们具有相同的值)。 在我的示例中,所需的URL是http://[hostname]:[port]/SpringWithSwagger/rest/api-docs/users
。 您应该能够看到类似于以下代码片段的输出:
{ "apiVersion":"1.0","swaggerVersion":"1.2","basePath":"http://[hostname/ip address]:[port]/SpringWithSwagger/rest","resourcePath":"/users","apis":[ { "path":"/users/{userName}","operations":[ { "method":"GET","summary":"Returns user details","notes":"Returns a complete list of users details with a date of last modification.","type":"User","nickname":"getUser","produces":[ "application/json"],"authorizations":{ },"parameters":[ { "name":"userName","description":"Alphanumeric login to application","required":true,"type":"string","paramType":"path","allowMultiple":false}],"responseMessages":[ { "code":200,"message":"Successful retrieval of user detail","responseModel":"User"},{ "code":404,"message":"User with given username does not exist"},{ "code":500,"message":"Internal server error"}]}]}],"models":{"User":{"id":"User","properties": {"surname":{"type":"string"},"userName":{"type":"string"},"lastUpdated":{"type":"string","format":"date-time"},"avatar":{"type":"array","items":{"type":"byte"}},"firstName":{"type":"string"},"email":{"type":"string"}}}}
}
创建模型文档
通过向前面的示例中的几个批注的响应参数提供User
类,我设法在API文档中引入了新的未记录元素。 Swagger能够提取有关User
类的所有结构性数据,而无需考虑与API的相关性。 为了抵消这种影响,Swagger提供了两个注释,以向API用户提供其他信息并限制模型的可见性。 要标记由Swagger处理的模型类,只需将@ApiModel
放在类的顶部。 与往常一样,您可以提供描述以及继承配置。 有关更多信息,请参见下面的@ApiModel
描述。
@ApiModel批注
REST-api中使用的bean类。 假设您有一个接口@PUT @ApiOperation(...) void foo(FooBean fooBean)
,没有直接的方法来查看FooBean
将具有哪些字段。 该注释旨在给出FooBean
的描述,然后使用@ApiModelProperty
字段进行注释。
注释参数:
-
value
–提供此类的提要 -
description
–提供对该类的详细说明 -
parent
–为模型提供超类,以允许描述继承 -
discriminator
–对于具有基类的模型,可以为多态用例提供鉴别符 -
subTypes
您需要做的最后一件事是使用@ApiModelProperty
注释对类成员进行注释,以为每个类成员提供文档。 在下面的类中可以看到一个简单的例子。
package com.jakubstas.swagger.model;@ApiModel
public class User {private String userName;private String firstName;private String surname;private String email;private byte[] avatar;private Date lastUpdated;@ApiModelProperty(position = 1, required = true, value = "username containing only lowercase letters or numbers")public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}@ApiModelProperty(position = 2, required = true)public String getFirstName() {return firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}@ApiModelProperty(position = 3, required = true)public String getSurname() {return surname;}public void setSurname(String surname) {this.surname = surname;}@ApiModelProperty(position = 4, required = true)public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@JsonIgnorepublic byte[] getAvatar() {return avatar;}public void setAvatar(byte[] avatar) {this.avatar = avatar;}@ApiModelProperty(position = 5, value = "timestamp of last modification")public Date getLastUpdated() {return lastUpdated;}public void setLastUpdated(Date lastUpdated) {this.lastUpdated = lastUpdated;}
}
如果您需要提供有关模型的更多详细信息,请检查@ApiModelProperty
以下描述:
@ApiModelProperty批注
ApiModelProperty描述了模型类中的属性。 根据模型扫描仪的配置和使用方式,注释可以应用于方法,属性等。
注释参数:
-
value
–提供此属性的易于理解的摘要 -
allowableValues
–如果可以设置的值受到限制,则可以在此处设置它们。 以逗号分隔的列表形式registered, active, closed
-
access
–指定一个可选的访问值以在Filter
实现中进行Filter
。 如果用户无权访问某些参数,则可以隐藏这些参数 -
notes
–物业的详细说明 -
dataType
–数据类型。 请参阅文档以获取受支持的数据类型。 如果数据类型是自定义对象,请设置其名称,或不设置任何名称。 如果是枚举,请为枚举常量使用'string'和allowableValues -
required
–是否required
该属性,默认为false -
position
–允许在模型中显式排序属性。 由于反射不能保证顺序,因此应指定属性顺序,以使模型在不同的VM实现和版本之间保持一致
如果您仔细遵循这些说明,那么您应该在前面提到的URL的json中获得完整的API文档。 以下仅是结果json中与模型相关的部分,现在提供了文档。
{..."models":{ "User":{ "id":"User","description":"","required":[ "userName","firstName","surname","email"],"properties":{ "userName":{ "type":"string","description":"username containing only lowercase letters or numbers"},"firstName":{ "type":"string"},"surname":{ "type":"string"},"email":{ "type":"string"},"lastUpdated":{ "type":"string","format":"date-time","description":"timestamp of last modification"}}}}
}
下一步是什么?
如果按照所有步骤进行操作,您现在应该拥有可以由自动化工具发布或进一步处理的有效API文档。 在我的下一篇名为Swagger的Spring Rest API –公开文档中,我将展示如何使用Swagger UI模块展示API文档。 该微型系列中使用的代码在GitHub上发布,并提供了所有讨论的功能和工具的示例。 请享受!
翻译自: https://www.javacodegeeks.com/2014/10/spring-rest-api-with-swagger-creating-documentation.html