Skip to content

Determining whether a property is required/mandatory #1568

Closed

Description

@evantoli

Feature Description

JSON properties are incorrectly specified as required if they have been annotated with both @Null and any of @NotNull, @NotEmpty and @NotBlank.

This situation occurs when using Java constraint validation groups along with Spring to set the validation groups to constrain whether a property is required or not for certain scenarios.

For example, when a client must supply some value on create but is not permitted to change that value later on update.

To Reproduce

Using:

  • spring-boot-dependencies 2.5.4
  • springdoc-openapi-ui 1.6.6

For example, in a model class declare properties with annotations like:

public class SomeModel {

  @Null(
      groups = GroupA.class,
      message = "Must not be provided in scenario A")
  @NotBlank(
      groups = GroupB.class,
      message = "Must be provided in scenario B")
  @Schema(
      description = """
          Some description of this property.
          
          Notes:
          
          - Must not be provided in scenario A
          - Must be provided in scenario B""",
      required = false)
  private String someProperty;
  ...

For the above code, SpringDoc will generate an OpenAPI spec with something like the following:

"components": {
  "schemas": {
    "SomeModel": {
      "required": [
        "someProperty"
       ],

Expected behaviour

Do not specify that a JSON property is required if it has been annotated with both @Null and any of @NotNull, @NotEmpty and @NotBlank.

Activity

  1. bnasslahsen commented on Mar 22, 2022

    @bnasslahsen
    Collaborator

    @evantoli,

    Duplicate of #1374 and #1486
    There is no plan to support groups.
    Feel free to propose a PR for it and we will review it.

  2. changed the title [-]Bug when determining whether a property is required/mandatory[/-] [+]Determining whether a property is required/mandatory[/+] on Mar 22, 2022
  3. added
    duplicate
    on Mar 22, 2022
  4. evantoli commented on Mar 23, 2022

    @evantoli
    Author

    Hi @bnasslahsen,

    I have a PR that I can submit. What is the process?

    I don't have permission to push my branch and I can't see any advice in the process in the CONTRIBUTING.adoc file.

    BTW, I fully appreciate that you're not going to support validation groups. And my ticket isn't really about validation groups.

    My desired behaviour is that the set of require properties should not contain any properties that may have contradictory validation annotations associated with them. Perhaps I didn't quite make that as clear as I could have.

    Also, thanks so much for responding to this ticket so quickly. Much appreciated 🙏

  5. JamesPace-Carta commented on Oct 21, 2022

    @JamesPace-Carta

    Is it possible to disable the handling of the validation annotations?

    We have a lot of code that uses groups and the swagger output it currently generates is incorrect. I can't seem to be able to provide an inline schema for the request, so I'm pretty much stuck.

  6. ML-Marco commented on Nov 14, 2024

    @ML-Marco
    Contributor

    Here is a workaround for this issue. It doesn't look like as if the Swagger project is actively maintained any more.

    I know it's ugly but better than nothing:

    private final HashMap<String, Set<String>> optionalProperties = new HashMap<>();
    
    @Bean
    public ModelConverter collectWrongNotNullPropertiesModelConverter() {
    	return (type, context, chain) -> {
    		Schema<?> schema = null;
    		if (chain.hasNext()) {
    			schema = chain.next().resolve(type, context, chain);
    			if (type.getCtxAnnotations() != null) {
    				boolean propertyIsOptional = Arrays.stream(type.getCtxAnnotations())
    						.filter(a -> ModelResolver.NOT_NULL_ANNOTATIONS.contains(a.annotationType().getSimpleName()))
    						.anyMatch(this::hasGroupsAttribute);
    				if (propertyIsOptional) {
    					optionalProperties.computeIfAbsent(type.getParent().getName(), v -> new HashSet<>()).add(type.getPropertyName());
    				}
    			}
    		}
    		return schema;
    	};
    }
    
    @Bean
    public OpenApiCustomiser fixRequiredProptiesOpenApiCustomiser() {
    	return openApi -> openApi.getComponents().getSchemas().entrySet().stream()
    			.filter(e -> optionalProperties.containsKey(e.getKey()))
    			.forEach(e -> optionalProperties.get(e.getKey()).forEach(propertyName -> e.getValue().getRequired().remove(propertyName)));
    }
    
    private boolean hasGroupsAttribute(Annotation annotation) {
    	return Arrays.stream(annotation.annotationType().getDeclaredMethods())
    			.filter(m -> "groups".equals(m.getName()))
    			.findFirst()
    			.map(m -> getGroups(annotation, m))
    			.filter(g -> g.length > 0)
    			.isPresent();
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    duplicate

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions