1. Overview
1.概述
Swagger is a set of specifications to document and describe REST APIs. It also provides example values for the endpoint parameters.
Swagger是一套用于记录和描述REST API的规范。它还提供了端点参数的示例值。
In this tutorial, we’ll show how to produce a default example value for String arrays, as this behavior is not enabled by default.
在本教程中,我们将展示如何为String数组产生一个默认的示例值,因为这一行为在默认情况下没有被启用。
2. Specify an Array of Strings as Body Parameters in Swagger
2.在Swagger中指定一个字符串数组作为主体参数
The issue arises when we want to specify an array of strings as body parameters in Swagger.
当我们想在Swagger中指定一个字符串数组作为主体参数时,问题就来了。
Swagger’s default Example Value is a bit opaque, as we can see in the Swagger editor:
Swagger的默认示例值有点不透明,我们可以在Swagger编辑器中看到。
So, here we see that Swagger doesn’t really show an example of what the array contents ought to look like. Let’s see how to add one.
所以,在这里我们看到,Swagger并没有真正展示一个数组内容应该是什么样子的例子。让我们看看如何添加一个。
3. YAML
3.YAML
Firstly, we start by specifying the array of strings in Swagger using YAML notation. In the schema section, we include type: array with items String.
首先,我们先用YAML符号指定Swagger中的字符串阵列。在模式部分,我们包括type: array with items String。
To better document the API and instruct the user, we can use the example label of how to insert values:
为了更好地记录API并指导用户,我们可以使用example标签来说明如何插入值。
parameters:
- in: body
description: ""
required: true
name: name
schema:
type: array
items:
type: string
example: ["str1", "str2", "str3"]
Let’s see how our display is now more informative:
让我们看看我们的显示现在是如何更有信息量的。
4. Springfox
4.Springfox
Or, we can achieve the same outcome using Springfox.
或者,我们可以使用Springfox达到同样的结果。
We need to use the dataType and example in the data model with @ApiModel and @ApiModelProperty annotations:
我们需要在数据模型中使用dataType和example的@ApiModel和@ApiModelProperty注解。
@ApiModel
public class Foo {
private long id;
@ApiModelProperty(name = "name", dataType = "List", example = "[\"str1\", \"str2\", \"str3\"]")
private List<String> name;
After that, we also need to annotate the Controller to let Swagger point to the data model.
之后,我们还需要对Controller 进行注释,让Swagger指向数据模型。
So, let’s use @ApiImplicitParams for that:
所以,让我们使用@ApiImplicitParams来实现。
@RequestMapping(method = RequestMethod.POST, value = "/foos")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
@ApiImplicitParams({ @ApiImplicitParam(name = "foo",
value = "List of strings", paramType = "body", dataType = "Foo") })
public Foo create(@RequestBody final Foo foo) {
And that’s it!
就这样吧!
5. Conclusion
5.总结
When documenting the REST APIs, we may have parameters that are string arrays. Ideally, we’d document these with Example Values.
在记录REST APIs时,我们可能有一些参数是字符串数组。理想情况下,我们会用实例值来记录这些参数。
We can do this in Swagger with the example property. Or, we can use the example annotation attribute in Springfox.
我们可以在Swagger中使用example property来做到这一点。或者,我们可以使用Springfox中的example annotation属性。
As always, the code is available over on GitHub.
像往常一样,代码可在GitHub上获得。