How to set Additional Properties to boolean

Viewed 3592

I am trying to set Additional Properties element into the Open API Schema 3.X but unfortunatel I was not able to find anything in the documentation that help me on it. I have a Application in Spring boot and it is using Spring doc OAS that relies on Swagger OAS as transitive dependency. Let me pick some code snippet here:

@GetMapping("/{accountId}")
@Operation(summary = "Get account by account id", tags = TAG)
@ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "Return a specific account queried by path",
                content = { @Content(mediaType = "application/json",
                        schema = @Schema(implementation = AccountDetailsDTO.class)) }),
        @ApiResponse(responseCode = "404", description = "No accounts found",
                content = @Content) })
public ResponseEntity<AccountDetailsDTO> getAccountDetailsByClientId(@PathVariable("accountId") Integer accountId) { }

This attribute is default to true and What I would like to see is as false like that below: enter image description here

2 Answers

If you want explicitly set the attribute to false you can a TransformationFilter (annoted @Component for Spring) to set additionalProperties to false for each component of you specification if you are using Springfox.

If you are using Springdoc, you can add a OpenApiCustomiser bean, see examples

Example with Springdoc OpenAPI

    @Bean
    public OpenApiCustomiser openApiCustomiser() {
        return openApi -> openApi.getComponents().getSchemas().values().forEach( s -> s.setAdditionalProperties(false));
    }

Example with Springfox framework

@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class OpenApiTransformationFilter implements WebMvcOpenApiTransformationFilter
{
    public boolean supports(@NotNull DocumentationType delimiter)
    {
        return SwaggerPluginSupport.pluginDoesApply(delimiter);
    }

    @Override
    public OpenAPI transform(OpenApiTransformationContext<HttpServletRequest> context)
    {
        OpenAPI openApi = context.getSpecification();
        openApi.getComponents().getSchemas().values().forEach(schema -> schema.setAdditionalProperties(false));
        return openApi;
    }
}

One workaround might be define a dummy class that contains the type information, then use that as the @Schema#implementation class in your @APIResponse.

static class YourTypeMap extends java.util.HashMap<String, YourType> {};

Then:

@APIResponse(
  responseCode = "200",
  content = @Content(
    mediaType = "application/json", 
    schema = @Schema(implementation = YourTypeMap.class)))

Credits: MikeEdgar

Related