3

This is pretty much the same as this other question for Swagger 1, except it's related to Swagger 2.

In short, I have an implementation i'm trying to annotate in order to generate an OpenApi 3 spec. One of the models has a map property, and I want to generate a nice meaningful sample for it.

For example, looking at the containerCreate Docker API, under HostConfig, there's a PortBindings object, which has one entry "22/tcp":

{
    "HostConfig": {
        "PortBindings": {
          "22/tcp": [    <== niceeee
            {
              "HostPort": "11022"
            }
          ]
        }
    }
}

Unfortunately, the doc generated from my sources is somewhat similar but less useful. While the PortBinding example is correct and helpful, the "additionalProp1" doesn't really mean anything:

{
    "HostConfig": {
        "PortBindings": {
          "additionalProp1": [    <== not so nice
            {
              "HostIp": "127.0.0.1",
              "HostPort": "8080"
            }
          ]
        }
    }
}

HostConfig implementation

@Schema(description = "Container configuration that depends on the host we are running on")
public class HostConfig implements Serializable {
    @Schema(description = "A map of exposed container ports and the host port they should map to.")
    @Nullable
    @JsonProperty("PortBindings")
    private Map<String, List<PortBinding>> portBindings;
}

PortBinding implementation

@Schema(description = "Host IP and port to which to bind a container port")
public class PortBindingDefinition implements Serializable {
    @Schema(description = "The host IP address", nullable = true, example = "127.0.0.1")
    @Nullable
    @JsonProperty("HostIp")
    private String hostIp;

    @Schema(description = "The host port number, as a string", example = "8080")
    @NotEmpty
    @JsonProperty("HostPort")
    private String hostPort;
}

I can paste a json in there as an example, but this seems more of a hack, and it has to be kept in sync with the structure of the actual objects that are in the map:

@Schema(description = "A map of exposed container ports and the host port they should map to.",
        example = "{\"PortBindings\": {\"22/tcp\": [{\"HostPort\": \"11022\"}]}}")

Other than that I can't figure out how to achieve the same, and the Swagger examples haven't been of too much help so far.


Bottom line, is there any elegant way to achieve this?

Morfic
  • 15,178
  • 3
  • 51
  • 61

1 Answers1

-2

I made some research on this topic and came to no satisfying conclusion either. The documentation of the @Schema.pattern field (here) states:

When associated with a specific media type, the example string shall be parsed by the consumer to be treated as an object or an array.

So I assume your "hack" is the only way to go..