'Swagger - Link body description to enum parameter

I have developed an REST webservice in order to manipulate contracts. In order to interact with them, I would like to trigger two processes :

  • One process by providing list of IDs
  • One process by providing list of statuses

But, in order to simplify the swagger, I would like to expose a single endpoint which will rely on an enum (for exemple as request parameter). Each choice of this enum should lead to a different body description.

Problem: I don't know how to implement that behavior in Swagger (I am using Java/Spring)

Example:

  • /api/v1/contracts?type=BY_ID

The expected body is

@Getter
@Setter
public class RecoveryPayloadById {
    private List<Long> ids;
}
  • /api/v1/contracts?type=BY_STATUS

The expected body is more complex

@Getter
@Setter
public class RecoveryPayloadByStatus {
    private String minDate;
    private List<String> contractStatuses;
    private List<String> banks;
}

How can I do that in swagger (OpenAPI) ? I tried to play with @Schema, @RequestBody... but I didn't find any simple solution.

The only (and hugly) solution I found is :

@PostMapping
@ResponseStatus(HttpStatus.ACCEPTED)
@Operation(description = "Start stock recovery")
public void synchronizeContracts(
            @Parameter(description = "The type of process") @RequestParam(name = "type") RecoveryType type,
            @Parameter(schema = @Schema(oneOf = {RecoveryPayloadById.class, RecoveryPayloadByStatus.class})) @RequestBody String payload) throws Exception {

        switch (type) {
            case BY_ID -> processContractsById(JSONUtils.parse(payload, RecoveryPayloadById.class));
            case BY_STATUS -> processContractsByStatus(JSONUtils.parse(payload, RecoveryPayloadByStatus.class));
        }
}

I accept the body as String (JSon serialized) and have to parse it before being processed. I could add a @Valid to ensure that the string body can to be parsed into RecoveryPayloadById.class or RecoveryPayloadByStatus.class but I am not happy with this solution because the body is not typed.

Moreover, I tought it was possible to change the body example in Swagger UI when the type enum is changed.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source