Skip to content

Make require-default configurable #2926

Closed

Description

@spalberg

Is your feature request related to a problem? Please describe.

We have a strict no-null policy for all of our spring boot based java applications.
This means that we use javas Optional<T> everywhere where a value does not have to be, even in our api layer and records.
Since all properties are not required by default when generating the openapi spec using springdoc, we have to annotate almost everything in our api layer with @NotNull. This is very verbose and only needed for our api layer which leads to many properties that are not nullable in our application but are nullable in our openapi spec since the @NotNull annotation was forgotten.

Describe the solution you'd like

It would be great if we could specify a default required mode, i.e. everything is required unless stated otherwise.
Perfect would be if a field with Optional<?> would result in a not required property in the openapi spec.

Describe alternatives you've considered

We dabbled in extending springdoc using ModelConverts and so on but did not manage to achieve the desired behavior.
We are also looking into migrating to graphql simple because code generation from a graphql schema seems to be much easier, especially when combined with sealed types in java (algebraic data types) that have to be mapped to discriminated unions in typescript.

Activity

  1. Mattias-Sehlstedt commented on Mar 2, 2025

    @Mattias-Sehlstedt
    Contributor

    Making everything optional by default I believe can be realized by following this example and then overriding this definition with:

    @Override
    protected io.swagger.v3.oas.annotations.media.Schema.RequiredMode resolveRequiredMode(io.swagger.v3.oas.annotations.media.Schema schema) {
        if (schema != null && !schema.requiredMode().equals(io.swagger.v3.oas.annotations.media.Schema.RequiredMode.AUTO)) {
            return schema.requiredMode();
        } else if (schema != null && schema.required()) {
            return io.swagger.v3.oas.annotations.media.Schema.RequiredMode.REQUIRED;
        }
        return Schema.RequiredMode.REQUIRED;
    }

    I was not able to find an easy way to define an explicit behavior for certain wrappers (Optional<T>) since swagger-core doesn't really pass around that type information outside of the main method.

    To achieve that one would most likely have to copy and adjust the whole class so that it can adjust the required annotation based upon the JavaType type variable.

  2. added
    question
    on Mar 22, 2025
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

    question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions