'Is it possible to configure spring-openapi to generate predictable order output in v3 api-docs?

When producing the output for the springdoc OpenAPI v3 api-docs, any slight change would cause this to produce quite different order in the generated v3 api docs.

It would be handy to keep this order predictable, especially for debugging when using the .yaml output. For this reason, if anyone knows a way for this to be ordered I'd be appreciative.



Solution 1:[1]

springdoc-openapi is based on io.swagger.v3.oas.models.OpenAPI objects.

The Paths elements are of type LinkedHashMap and the order is preserved when using this type. If you declare all your parameters in a particular order using @Parameters annotation or @Operation annotation, the order will be preserved.

You have also some properties on the swagger-ui side. For example:

springdoc.swagger-ui.operationsSorter=method
springdoc.swagger-ui.tagsSorter=alpha

For debuging/test/comparing results, you can use JSONAssert library for comparison.

And finally, you can use OpenAPICustomiser to sort as wish all the elements of the OpenAPI object.

Solution 2:[2]

The following example shows how you can get full control over your paths ordering with OpenAPICustomiser.

@Configuration
public class OpenApiConfiguration {

    private static final List<String> PATHS_ORDER = List.of(
        "/api/test2",
        "/api/test3",
        "/api/test1"
    );

    @Bean
    public OpenApiCustomiser sortPaths() {
        return openApi -> {
            Paths paths = openApi
                .getPaths()
                .entrySet()
                .stream()
                .sorted(Comparator.comparing(entry -> PATHS_ORDER.contains(entry.getKey()) ? PATHS_ORDER.indexOf(entry.getKey()) : Integer.MAX_VALUE))
                .collect(Paths::new, (map, item) -> map.addPathItem(item.getKey(), item.getValue()), Paths::putAll);

            openApi.setPaths(paths);
        };
    }

}

(Any better alternatives would be appreciated)

Sources

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

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 István Békési