I am trying to generate OpenAPI (version 3.0.1) specification for my Java code. In order to achieve this I use Swagger Annotations (version 2.0.8) and Swagger Maven Plugin.
I have a problem with Enums. Say, I have two methods returning the very same Enum. In OpenAPI specification, I would like to have the single schema definition for this Enum and $ref
link in both API operations. But instead I have duplicated Enum definitions in each API operations. How do I avoid this duplication without editing specification file manually?
Here is Java code with two methods returning the same Enum:
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/properties")
@Produces("application/json")
public class TestService {
@GET
@Path("/enum1")
@Operation
@ApiResponses({
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Color.class)))
})
public Color getColor1() {
throw new UnsupportedOperationException();
}
@GET
@Path("/enum2")
@Operation
@ApiResponses({
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Color.class)))
})
public Color getColor2() {
throw new UnsupportedOperationException();
}
public enum Color {
RED,
GREEN,
BLUE
}
}
Here is specification I would like to get:
openapi: 3.0.1
components:
schemas:
Color:
type: string
enum:
- RED
- GREEN
- BLUE
paths:
/properties/enum2:
get:
operationId: getColor2
responses:
200:
content:
application/json:
schema:
$ref: '#/components/schemas/Color'
/properties/enum1:
get:
operationId: getColor1
responses:
200:
content:
application/json:
schema:
$ref: '#/components/schemas/Color'
And here is specification I do get:
openapi: 3.0.1
paths:
/properties/enum2:
get:
operationId: getColor2
responses:
200:
content:
application/json:
schema:
type: string
enum:
- RED
- GREEN
- BLUE
/properties/enum1:
get:
operationId: getColor1
responses:
200:
content:
application/json:
schema:
type: string
enum:
- RED
- GREEN
- BLUE
$ref
is what I need but I would like to express it in via Swagger Java annotations. – Pigtail$ref
is what I need. But there is one more thing I need — a schema definition this$ref
will refer to. Thank you for your links, but there is a little different kind of issue. It is about how to refer (with$ref
) to existing schema. As for me, I need this schema to be generated (not inside operation definition, but in reusable way). – Pigtail