首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用springdoc-openapi使可选的OpenAPI参数为空?

如何使用springdoc-openapi使可选的OpenAPI参数为空?
EN

Stack Overflow用户
提问于 2021-09-24 06:39:58
回答 1查看 568关注 0票数 2

在生成的OpenAPI文档中,springdoc-openapi库自动将某些属性标记为required。例如,注释为@NotNull的属性将包含在所生成的YAML文件中的必需属性列表中。

该库不做的一件事是将可选属性标记为nullable: true。但是,默认情况下,Spring Boot应用程序将接受请求中的null,并在可选属性的响应中返回null。这意味着OpenAPI文档和端点的行为之间存在差异。

手动将任何单个属性标记为可为空很简单:只需将@Schema(nullable = true)添加到字段或访问器即可。但是,在具有多个属性的大型模型中,我希望以与required属性相同的方式自动确定这一点。也就是说,如果该属性不是必需的,我希望它为nullable,反之亦然。

如何在由springdoc-openapi生成的OpenAPI文档中将我的可选属性标记为nullable: true

示例

代码语言:javascript
复制
import io.swagger.v3.oas.annotations.media.Schema;
import javax.validation.constraints.NotNull;

public class RequiredExample {
    @NotNull
    private String key;

    private String value;

    public String getKey() { return key; }
    public void setKey(String key) { this.key = key; }
    public String getValue() { return value; }
    public void setValue(String value) { this.value = value; }
}

生成的OpenAPI文档:

代码语言:javascript
复制
"components": {
  "schemas": {
    "RequiredExample": {
      "required": [
        "key"
      ],
      "type": "object",
      "properties": {
        "key": {
          "type": "string"
        },
        "value": {
          "type": "string"
        }
      }
    }
  }
}

所需的OpenAPI文档:

代码语言:javascript
复制
"components": {
  "schemas": {
    "RequiredExample": {
      "required": [
        "key"
      ],
      "type": "object",
      "properties": {
        "key": {
          "type": "string"
        },
        "value": {
          "type": "string"
          "nullable": true
        }
      }
    }
  }
}
EN

回答 1

Stack Overflow用户

发布于 2021-09-24 06:39:58

一种解决方案是创建一个springdoc-openapi OpenApiCustomiser Spring bean,它将所有属性设置为nullable,除非它们在required属性列表中。这种方法得益于内置的springdoc-openapi对@NotNull和其他此类注释的支持,因为required属性将根据这些属性的存在以标准方式进行计算。

代码语言:javascript
复制
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
import org.springdoc.core.customizers.OpenApiCustomiser;
import org.springframework.stereotype.Component;
import java.util.Map;

@Component
public class NullableIfNotRequiredOpenApiCustomizer implements OpenApiCustomiser {
    @Override
    @SuppressWarnings({"rawtypes", "unchecked"})
    public void customise(OpenAPI openApi) {
        for (Schema schema : openApi.getComponents().getSchemas().values()) {
            if (schema.getProperties() == null) {
                continue;
            }

            ((Map<String, Schema>) schema.getProperties()).forEach((String name, Schema value) -> {
                if (schema.getRequired() == null || !schema.getRequired().contains(name)) {
                    value.setNullable(true);
                }
            });
        }
    }
}
票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69310598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档