Spring Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:


1. Overview

Swagger is a set of specifications to document and describe REST APIs. It also provides example values for the endpoint parameters.

In this tutorial, we'll show how to produce a default example value for String arrays, as this behavior is not enabled by default.

2. Specify an Array of Strings as Body Parameters in Swagger

The issue arises when we want to specify an array of strings as body parameters in Swagger.

Swagger's default Example Value is a bit opaque, as we can see in the Swagger editor:

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.


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.

To better document the API and instruct the user, we can use the example label of how to insert values:

  - in: body
    description: ""
    required: true
    name: name
      type: array
        type: string
      example: ["str1", "str2", "str3"]

Let's see how our display is now more informative:

4. Springfox

Or, we can achieve the same outcome using Springfox.

We need to use the dataType and example in the data model with @ApiModel and @ApiModelProperty annotations:

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.

So, let's use @ApiImplicitParams for that:

@RequestMapping(method = RequestMethod.POST, value = "/foos")
@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

When documenting the REST APIs, we may have parameters that are string arrays. Ideally, we'd document these with Example Values.

We can do this in Swagger with the example property. Or, we can use the example annotation attribute in Springfox.

As always, the code is available over on GitHub.

Spring bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Comments are closed on this article!