如何指定属性可以为空或使用 swagger 引用 [英] How to specify a property can be null or a reference with swagger

查看:175
本文介绍了如何指定属性可以为空或使用 swagger 引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将属性指定为 null 或引用? 讨论了如何使用 jsonschema 将属性指定为 null 或引用.

How to specify a property as null or a reference? discusses how to specify a property as null or a reference using jsonschema.

我希望用 swagger 做同样的事情.

I'm looking to do the same thing with swagger.

总结一下上面的答案,使用 jsonschema,可以这样做:

To recap the answer to the above, with jsonschema, one could do this:

{
   "definitions": {
      "Foo": {
         # some complex object
      }
   },

   "type": "object",
   "properties": {
      "foo": {
         "oneOf": [
            {"$ref": "#/definitions/Foo"},
            {"type": "null"}
         ]
      }
   }
}

答案的关键在于oneOf的使用.

The key point to the answer was the use of oneOf.

我的问题的关键点:

  1. 我有一个复杂的对象,我想保持干燥,所以我把它放在一个在我的 swagger 规范中重用定义部分:其他属性的值;响应对象等

  1. I have a complex object which I want to keep DRY so I put it in a definitions section for reuse throughout my swagger spec: values of other properties; response objects, etc.

在我的规范中的不同地方属性可以是对此类对象的引用,也可以为 null.

In various places in my spec a property may be a reference to such an object OR be null.

如何使用不支持 oneOfanyOf?

How do I specify this with Swagger which doesn't support oneOf or anyOf?

注意:一些 swagger 实现使用 x-nullable(或 some-such)来指定属性值可以为 null,但是,$ref replaces 对象及其引用的内容,因此似乎忽略了对 x-nullable 的任何使用.

Note: some swagger implementations use x-nullable (or some-such) to specify a property value can be null, however, $ref replaces the object with what it references, so it would appear any use of x-nullable is ignored.

推荐答案

做到这一点并不容易.甚至几乎不可能.您的选择:

Not easy to do that. Even almost impossible. Your options :

关于这个的讨论很长,也许有一天它会完成...

There is a very long discussion about this point, maybe one day it will be done...

您可以使用 供应商扩展x-oneOfx-anyOf.我已经采取了这种艰难的方式:您必须升级所有使用的swagger 工具",以将这些供应商扩展考虑在内.

You can use vendors extensions like x-oneOf and x-anyOf. I have already taken this hard way: You must to upgrade all used 'swagger tools' to take into account these vendors extensions.

就我而言,我们只需要:

In my case, we needed 'only' to :

  • 使用自定义注释开发我们自己的 Jax-RS 解析器,以便从源中提取 swagger API 文件
  • 扩展 swagger-codegen 以将这些扩展考虑在内,以便为我们的客户生成 Java 代码
  • 开发我们自己的 swagger-ui:为了促进这项工作,我们添加了一个预处理步骤,将我们的 swagger 模式和我们的扩展转换为有效的 json 模式.与 javascript 中的 swagger 模式相比,更容易找到表示 json 模式的模块.由于缺点,我们放弃了使用尝试"按钮测试 API 的想法.

一年前,也许现在......

It was a year ago, maybe now ...

很多项目不需要 anyOf 和 oneOf,我们为什么不需要?

Many projects don't need anyOf and oneOf, why not us ?

这篇关于如何指定属性可以为空或使用 swagger 引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆