With Springdoc you can create a Swagger UI and generate the OpenAPI spec file. In a project it is a good practice to support version n - 1 of the API for backwards compatibility. The problem is that some objects have the same name and then the last parsed object is used for all versions in the OpenAPI spec. In this post the solution with definitions is shown.

In the following example there are two API versions defined:

@RestController
public class V1Controller {
    @GetMapping("/v1/{id}")
    public ResponseEntity<ActionResponse> getAction(@PathVariable(name = "id") UUID id) {
        return ResponseEntity.ok(new ActionResponse("OK"));
    }

    public record ActionResponse(String action) {
    }
}
@RestController
public class V2Controller {
    @GetMapping("/v2/{id}")
    public ResponseEntity<ActionResponse> getAction(@PathVariable(name = "id") UUID id) {
        return ResponseEntity.ok(new ActionResponse(true));
    }

    public record ActionResponse(Boolean action) { // <-- version 2 changed to a boolean
    }
}

The first version where the action parameter is a String and in the second a Boolean. The openAPI definition will only use the ActionResponse with the Boolean action for both URIs without any warning when starting the application.

version 1 contains the wrong response with a Boolean instead of a String

Also in the exported OpenAPI spec there is only one schema object.

components:
  schemas:
    ActionResponse:
      type: object
      properties:
        action:
          type: boolean

The solution is to define a group per version:

@Configuration
public class OpenApiConfiguration {
    @Bean
    public GroupedOpenApi apiV1() {
        return GroupedOpenApi.builder()
                .group("v1")
                .packagesToScan(V1Controller.class.getPackageName())
                .build();
    }

    @Bean
    public GroupedOpenApi apiV2() {
        return GroupedOpenApi.builder()
                .group("v2")
                .packagesToScan(V2Controller.class.getPackageName())
                .build();
    }
}

As a result the definition selection on top shows the defined groups. When changed the other schema models are shown and the OpenAPI spec can be exported per definition/version.

Select the defintion in the dropdown
The openAPI spec in yaml is sometimes better readable, add .yaml to the openAPI spec URL: /v3/api-docs.yaml/nameOfTheDefinition

Written with Springdoc 1.6.12.

shadow-left