I've been trying to add examples to my Swagger API according to the official docs (see last codeblock of Request and Response Body Examples) but it does not seem to work as expected.
Considering the following minimal example:
swagger: "2.0"
info:
description: Desc
version: "1"
title: Title
paths:
/stuff:
post:
produces:
- application/json
responses:
201:
description: It worked
content:
application/json:
schema:
$ref: "#/definitions/StatusMessage"
examples:
Success without message:
value:
code: "00000"
Success with message:
value:
code: "00000"
message: "All right"
definitions:
StatusMessage:
type: object
description: Response with code and optional message
properties:
code:
type: string
message:
type: string
required:
- code
I want to provide to sample responses, one with the optional property message
present and the other one without. However, the aforementioned YAML file yields wrong results in the generated API Class:
@ApiOperation(value = "", nickname = "stuffPost", notes = "", tags={ })
@ApiResponses(value = {
@ApiResponse(code = 201, message = "It worked") })
@RequestMapping(value = "/stuff",
method = RequestMethod.POST)
default ResponseEntity<Void> stuffPost() { /*default implementation*/ }
The produces
property is not present and the return type is wrong! Furthermore, this does not compile in the Swagger Editor: the responses
property should NOT have additional properties
.
I'v changed it to get a "valid" example in the Swagger Editor but the generated code is also wrong. See below:
paths:
/stuff:
post:
produces:
- application/json
responses:
201:
description: It worked
schema:
$ref: "#/definitions/StatusMessage"
examples:
Success without message:
code: "00000"
Success with message:
code: "00000"
message: "All right"
The generated method is:
@ApiOperation(value = "", nickname = "stuffPost", notes = "", response = StatusMessage.class, tags={ })
@ApiResponses(value = {
@ApiResponse(code = 201, message = "It worked", response = StatusMessage.class) })
@RequestMapping(value = "/stuff",
produces = { "application/json", "Success without message", "Success with message" },
method = RequestMethod.POST)
default ResponseEntity<StatusMessage> stuffPost() { /*default implementation*/ }
This time, the produces
property is there but completely off!
How can I get this to work? It works if I use the second version with application/json
as key for the example title but that prevents me from adding more examples because of duplicated key.
From Helen's comment:
A workaround I've found for this problem in OpenAPI 2.0 is as follows:
This shows both examples (with
0
and1
as title) and does not break Codegen.