How to add different @Schema descriptions on OpenApi Spring?

Viewed 952

I'm having some issues defining my API using OpenApi with Spring. I'm using this dependency:

<dependency>
   <groupId>org.springdoc</groupId>
   <artifactId>springdoc-openapi-ui</artifactId>
   <version>1.5.2</version>
</dependency>

My problem is that I want to define a @Schema on different Api Responses but use a different description and example in each one of the responses.

Now I have one response that looks like this:

public class LoginResponse {

    @Schema(description = "User identifier", example = "12")
    private Long id;
    @Schema(description = "User balance", example = "{"type":"COINS","amount":1000}")
    private Balance balance;
...

and other response that looks like this...

public class ModifyBalanceResponse {

    @Schema(description = "User identifier", example = "12")
    private Long id;
    @Schema(description = "Added balance", example = "{"type":"COINS","amount":500}")
    private Balance addedBalance;
    @Schema(description = "Updated balance", example = "{"type":"COINS","amount":1500}")
    private Balance updatedBalance;
...

So, I have the object "Balance" with three different descriptions and examples, but when it generates the documentation, all the responses and fields using this object takes the same description and example.

I have seen that in the generated file that I get all this items with a "$ref" tag to Balance schema and this is generated with only one of the description/example defined, like this:

addedBalance:
   $ref: '#components/schemas/Balance'

I have tried to edit the file manually and I made possible to see the swagger doc as I want by replacing this with...

addedBalance:
   title: Balance
   description: Added balance
   example: '{"type":"COINS","amount":500}'

There is any way to do something like this with the Spring annotations provided by openapi? Something like ignoring the schema object and taking literally the description and the example. I don't mind if it is not referenced to the schema object.

Thanks on advantage.

2 Answers

It's lame but you can solve this by making a different response class for each item.

public class AddedBalance extends Balance {}
public class UpdatedBalance extends Balance {}

There must be a better solution...

You can also use a Generic on your class to force SpringDoc to think it's a different Type.

public static class Balance<T> {
   ...
}

public static class ModifyBalanceResponse {

    @Schema(description = "User identifier", example = "12")
    private Long id;
    @Schema(description = "Added balance", example = "{"type":"COINS","amount":500}")
    private Balance<Added> addedBalance;
    @Schema(description = "Updated balance", example = "{"type":"COINS","amount":1500}")
    private Balance<Updated> updatedBalance;
}

public static class Added {}
public static class Updated {}
Related