0
votes

I have application in Spring and creating documentation for this in OpenAPI with annotations for controllers methods. For example I have method getById (simplified for readability):

@GetMapping("/{id}")
@ApiResponse(
    responseCode = "200", 
    description = "Successful operation.",
    content = @Content(
            mediaType = "application/json", 
            schema = @Schema(implementation = ScheduleResponse.class)
    )
)
@ApiResponse(
    responseCode = "404", 
    description = "The object with the specified ID does not exist in the system.",
    content = @Content(
            mediaType = "application/json", 
            schema = @Schema(implementation = ApiError.class)
    )
)
ScheduleResponse getById(@PathVariable Long id) throws EntityNotFoundException;

For 404 NOT_FOUND I returns my own ApiError with list of ApiErrorDetails interface:

@Getter
public class ApiError {

    private final LocalDateTime timestamp;
    private final String status;
    private final String message;
    private List < ApiErrorDetails > details;
}

public interface ApiErrorDetails {
}

In that case, I'm using a specific implementation of the interface:

@Getter
public class EntityNotFoundDetails implements ApiErrorDetails {

    private final String field;
    private final Object notFoundValue;
}

With the above implementation, I get JSON in the documentation with no specific field information inside details for example:

enter image description here

and for schema:

enter image description here

Instead, I'd like to prepare an example like this:

{
  "timestamp": "2021-08-08T13:32:10.875Z",
  "status": "string",
  "message": "string",
  "details": [
    {
      "field": "string",
      "notFoundValue": {}
    }
  ]
}

Of course, I need solution for that specific case. This means that I don't want to add the

@Schema(example = "value")

to the details list because I provide different implementations in different cases.

1

1 Answers

0
votes

I found a solution that is not perfect but sufficient for documentation purposes.

All that is needed is to add @Schema annotation with the property oneOf over ApiErrorDetails. For example for two interface implementations: EntityNotFoundDetails and ValidationErrorDetails:

@Schema(oneOf = {EntityNotFoundDetails.class, ValidationErrorDetails.class})
interface ApiErrorDetails {
}

In the documentation, it looks like this:

enter image description here

which suggests a slightly different shape of JSON than in reality, but the schema tab dispels doubts:

enter image description here

Probably the only way to provide one implementation of your choice is to simply use different classes and not extend the interface.