OpenAPI-Specification icon indicating copy to clipboard operation
OpenAPI-Specification copied to clipboard

Make schema object compatible with JSON Schema draft4

Open IvanGoncharov opened this issue 11 years ago • 131 comments

According to spec swagger inside schema object support only limited subset of JSON Schema draft4 and extend it with custom keywords.

This isssue was hidden, before 68c6777dc5eba98dc1eb791983693f089e9d3366 commit any swagger model with arbitrary JSON schema was valid(against Swagger schema).

These create a problem, because in reality most of tools use standard JSON schema validators(for e.g. swagger-tools use z-schema, swagger-express-middleware use tv4). And I didn't found any true Swagger 2.0 validator in the wild.

Another problem is that you can't reference existing schemes inside your swagger files. It became real problem, if you want to use some standard scheme or simply reuse your existing validation scheme. For example if you make API that return swagger definitions and want to reuse existing schema, you can't simply use '$ref' or even copy-paste it.

Finally it brake compatibility with all tooling around JSON Schema not only validators but also documentation generators, UI form generators, etc.

On technical side, this is list of Draft4 keywords doesn't supported by Swagger: id, $schema, additionalItems, definitions, patternProperties, dependencies, anyOf, oneOf, not.

Also there are "discriminator" and "readOnly" Swagger specific keywords that don't supported by JSON Schema validators. "discriminator" could be safely substitute with "oneOf" construction, as for "readOnly" same behaviour could be achieved by using "allOf" with "write part" and "read-only part". My proposal it either to remove these keywords or make them optional to support.

Also there are "safe" custom keywords namely "example" and "externalDocs", they shouldn't cause any serious trouble, but should be submitted as requests for Draft5 to ensure future compatibility.

Last keyword is "xml", I didn't make any research about it, so I can't say if it used in any Swagger related project or if it brake JSON schema compatibility.

IvanGoncharov avatar Apr 18 '15 12:04 IvanGoncharov

@IvanGoncharov thanks for the tip, I never realized that about JSON schema~~, but I'm not sure I like it - oneOf seems less ambiguous~~. Anyway, looks like a non-starter in 2.0, per @webron.

Per your comments:

It was meant to describing constraints on data and not data themselves. So it almost impossible to use it for something other than validation.

This is what I was getting at in my previous post - it should be made clear that the schema construct in the OAI spec is not intended solely for validation.

I think it needs more clear support for inheritance and polymorphism. And it needed not only to generate SDKs for statically typed languages but for example to generate nice UI with input forms solely out of JSON Schema.

This is a pretty tall order and clearly JSON Schema alone is not up to the task. This is the same realization the RAML folks had, I think, when they decided to make a clean break from XML/JSON Schema with their new data type system.

Try to represent oneOf or anyOf in such UI without totally confusing a user.

Doesn't discriminator impose the same challenges? Is it supported in current tooling?

emattheis avatar Apr 06 '16 15:04 emattheis

@IvanGoncharov @webron For the record, my real-life problem is limited to the desire to have polymorphic behavior with 'primitive' types - I don't really need or want full support for oneOf. For custom types, I am almost satisfied with the discriminator support since that's generally how we deal with polymorphism in JSON payloads, anyway.

emattheis avatar Apr 06 '16 15:04 emattheis

Doesn't discriminator impose the same challenges? Is it supported in current tooling?

IMHO, discriminator has many problems and only few tools support it. But it definitely easier(for something other than validation) to support it than unconstrained oneOf. With that said I think incompatibilities with JSON Schema is HUGE problem for OpenAPI spec.

Example of discriminator support, see petType field: http://rebilly.github.io/ReDoc/#operation/addPet Disclaimer: I'm working as OpenAPI consultant for ReDoc project. So my opinion is based mostly on this project, and I don't have any background in OpenAPI code generation.

IvanGoncharov avatar Apr 06 '16 15:04 IvanGoncharov

My problem with the discriminator is that it needs to be 1:1 with a definition. Which makes it very hard to adapt to an existing API even if it's already returning fields with record types:

{
  "id": "cuavyyna8lg8",
  "object": "transaction",
  ...
}
{
  "error": {
    "type": "transaction",
    "message": "The security code you entered does not match. Please update the CVV and try again.",
  ...
  }
}

Since the ~~type~~ discriminator field needs to be unique. Again, a very frustrating "solution". It would be almost useable if there was some translation layer where you could distinguish how the discriminator values mapped to definitions.

drewish avatar Apr 06 '16 18:04 drewish

I just looked a little closer at the discriminator spec. I agree with @drewish that it would be a lot more usable if it were possible to declare how a discriminator value maps to a schema type instead of requiring a 1:1 relationship.

Also, I just noticed that the discriminator property must be required. This could be slightly problematic. We generally only include discriminators when there is ambiquity.

If I have an endpoint /animals then I expect something like

[
  { "type": "cat", "name": "fluffy" },
  { "type": "dog", "name": "buster" }
]

But I may also have an endpoint /animals/cats where the following is sufficient:

[
  { "name": "fluffy" }
]

emattheis avatar Apr 07 '16 20:04 emattheis

And here is my question regarding the missing oneOf and property handling.

I have this C# code:

public class TestClass
{
    [Required] // <= not nullable
    public ReferencedClass RequiredProperty { get; set; }

    public ReferencedClass NullableProperty { get; set; }
}

public class ReferencedClass
{
    public string Test { get; set; }
}

Both properties reference the same ReferencedClass (i.e. it must be a reference in the generated schema). The generated schema would look like this (JSON Schema draft4):

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "additionalProperties": false,
  "required": [
    "RequiredProperty"
  ],
  "properties": {
    "RequiredProperty": {
      "oneOf": [
        {
          "$ref": "#/definitions/ReferencedClass"
        }
      ]
    },
    "NullableProperty": {
      "oneOf": [
        {
          "$ref": "#/definitions/ReferencedClass"
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "definitions": {
    "ReferencedClass": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "Test": {
          "type": [
            "null",
            "string"
          ]
        }
      }
    }
  }
}

As you can see, the schema for ReferencedClass cannot have a type of object AND null because it would be wrong for the first property (RequiredProperty). Also the required array does not express nullability but if the field must be defined in JSON or not (it still can be null).

How would you express this with the Swagger "special" JSON Schema?

RicoSuter avatar Jun 04 '16 15:06 RicoSuter

Btw: allOf is not an option:

Schema:

{
  "type": "object",
  "required": [
    "foo"
  ],
  "properties": {
    "foo": {
      "type": [
        "null",
        "object"
      ],
      "allOf": [
        {
          "type": "object",
          "required": [
            "name"
          ],
          "properties": {
            "name": {
              "type": "string"
            }
          }
        }
      ]
    }
  }
}

This is valid:

{
  "foo": {
    "name": "test"
  }
}

This doesn't work because this not valid:

{
  "foo": null
}

And adding the property schema directly to the property is not possible because you can either have $ref or other properties and the property schema must be referenced so that it can be shared...

RicoSuter avatar Jun 04 '16 15:06 RicoSuter

@rsuter OpenAPI 2.0 doesn't support null at all (see e.g. #297 for an explanation) – the way to represent your TestClass would be by using the required property to indicate that RequiredProperty is required, and you could then omit NullableProperty from the JSON representation of your TestClass object if it is null.

TestClass:
   type: object
   properties:
     RequiredProperty:
       $ref: '#/definitions/ReferencedClass'
     NullableProperty:
       $ref: '#/definitions/ReferencedClass'
   required:
     - RequiredProperty

Nullability is a separate topic discussed in #229.

ePaul avatar Jun 05 '16 08:06 ePaul

Ok thanks for the heads up. I'm rewriting my library (NSwag.org) with an option to handle nullability this way... But how can I express a nullable HTTP response without oneOf? There is no required field there...

RicoSuter avatar Jun 05 '16 09:06 RicoSuter

phew that took a while to read through.

@webron I've seen you call for use cases a number of times (https://github.com/OAI/OpenAPI-Specification/issues/333#issuecomment-205989679, https://github.com/OAI/OpenAPI-Specification/issues/333#issuecomment-173475240). While a few have been presented I'm finding a serious lack of documentation/discussion on the prohibitive factors of supporting json-schema v4 in full - aside from a number of vague references to code generation. There seems to be a clearly expressed interest in supporting json schema more thoroughly here, and it also seems to me that a very easy way to drive this conversation is to get the technical hurdles out in the open quickly so we're not boiling down to preferences.

I'd like to echo @gravesmedical (specifically), and others (probably), in asking for a succinct reasoning for the exclusion of these parts of JSON schema v4. If it's just an issue with code then perhaps we can work towards a solution (@fehguy I haven't seen a C++ validator for RAML, but I suspect thats because of a smaller community. valijson supports json schema v4 validation including anyOf/oneOf for C++ as one example). If, on the other hand, you guys just don't like json schema (as it is, for this purpose, because of its hairdo etc) then that's totally reasonable as well - we should just clear that up IMHO.

Cheers!

mbroadst avatar Jun 20 '16 17:06 mbroadst

It's not really about liking or disliking JSON Schema. JSON Schema, much like any other specification (yes, the OAS as well), is not without faults. It wasn't really written with the mindset of APIs. You can see in other tickets that we may want to include support for other formats as well, but it's unlikely that we'll drop support for JSON Schema. The challenges are not just with code generation, and they would appear in code in general in some cases. There challenges are also with validation and documentation visualization.

The need for full JSON Schema support is clear. At the end, it boils down to whether it's more important to describe more APIs or making sure there's robust support in the tooling, no matter which tool it is. Even if we choose that the latter is more important, it doesn't mean we won't lift some of the current restrictions. It's definitely one of the more challenging aspects and I'm hopeful we can improve it wisely.

webron avatar Jun 20 '16 17:06 webron

Apologies if the last bit about not liking json-schema came off like my main point, but I'm still unclear as to what specific technical hurdles surround full json-schema support.

  • Can we start to build a list so that developers who are interested in helping the cause could potentially chip in? (is there already some sort of documentation about the challenges?)
  • Is there any existing work to fully support json-schema in your tooling that you could point to?

I'm very keen to use OpenAPI for my product, however the lack of full json-schema support is limiting in my case. I'd like to help out on this effort in any way I can, and from what I'm reading here it seems like I'm not the only one.

mbroadst avatar Jun 21 '16 13:06 mbroadst

Matt, let me know if you want to chat sometime about this. I'm interested in supporting this endeavor.

-Mark

On Tue, Jun 21, 2016 at 6:46 AM, Matt Broadstone [email protected] wrote:

Apologies if the last bit about not liking json-schema came off like my main point, but I'm still unclear as to what specific technical hurdles surround full json-schema support.

  • Can we start to build a list so that developers who are interested in helping the cause could potentially chip in? (is there already some sort of documentation about the challenges?)
  • Is there any existing work to fully support json-schema in your tooling that you could point to?

I'm very keen to use OpenAPI for my product, however the lack of full json-schema support is limiting in my case. I'd like to help out on this effort in any way I can, and from what I'm reading here it seems like I'm not the only one.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/OAI/OpenAPI-Specification/issues/333#issuecomment-227444162, or mute the thread https://github.com/notifications/unsubscribe/AApkoffCS9a1iq3xFl5egsr64o0JDz1aks5qN-sZgaJpZM4EDVZG .

gravesmedical avatar Jun 22 '16 05:06 gravesmedical

Just for another perspective, in our company we are thinking about supporting cases where OpenAPI can't describe what is actually needed (mainly for oneOf, I think) in this way:

  • We have the OpenAPI definition with its OpenAPI schema (which might be a looser approximation to what is actually allowed)
  • The OpenAPI schema has an extension property with the actual JSON schema
  • This is for now ignored by tooling, but can be read by humans (and copied for use by validators).

ePaul avatar Jun 22 '16 14:06 ePaul

I also have severe limitations for defining an API, which is based on the DicomWeb API (already existing, and the new de-facto standard for medical imaging). The thing is that, it doesn't matter if you think it is well or wrongly designed. I have a big problem trying to provide a Swagger definition file for it. At the end, if I cannot find a solution, I will be forced to switch to RAML or other standard that supports a full JSON schema definition. I will put an example here about a typical DicomWeb response (again, this is already a standard, please don't suggest modifications to it):

{ 
  "00080005": { "vr": "CS",  "Value": ["ISO_IR 100"] },
  "00080020": { "vr": "DA",  "Value": ["20160602"] },
  "00080030": { "vr": "TM",  "Value": ["171855.7490"] },
  "00080050": { "vr": "SH",  "Value": ["1234"] },
  "00080090": { "vr": "PN",  "Value": [ {"Alphabetic":"Parikh MD^Anush^M"} ] }
}

So, I am having issues with two features here:

  • The first-level attribute names have not fixed names, but have a 8-digit pattern. This is supported in JSON Schema with patternProperties, but couldn't make it work in the Swagger editor (2.0)
  • The second-level Value attribute has an array of items with multiple types (can be string, integers or an embedded object). This is supported in JSON Schema with explicit or implicit anyOf, but couldn't find a way with Swagger

What is really ironic is that the Swagger schema uses patternProperties for describing the ˆx- and the http response codes. So, it is good when you use it, but bad for others? I think you should not feel entitled for lecturing people what is good or not from a well-known standard like JSON.

Let me know if I am wrong. I placed a question in StackOverflow for the first issue and found deceptive answers there for the second one: http://stackoverflow.com/questions/38088771/swagger-yaml-schema-definition-for-object-without-a-fixed-property-list/38091369#38091369

jaime-olivares avatar Jun 29 '16 05:06 jaime-olivares

Please read my previous comment before. This is just the supporting evidence for my previous statement: the Swagger/OpenAPI language schema uses JSON Schema features that are not supported by Swagger. So, it is good for them, but a "bad practice" for us.

"responses": {
  "type": "object",
  "description": "Response objects names can either be any valid HTTP status code or 'default'.",
  "minProperties": 1,
  "additionalProperties": false,
  "patternProperties": {       <—— 
    "^([0-9]{3})$|^(default)$": {
      "$ref": "#/definitions/responseValue"
    },
    "^x-": {
      "$ref": "#/definitions/vendorExtension"
    }
  },
  "not": {
    "type": "object",
    "additionalProperties": false,
    "patternProperties": {     <—— 
      "^x-": {
        "$ref": "#/definitions/vendorExtension"
      }
    }
  }
},
"responseValue": {
  "oneOf": [    <—— 
    {
      "$ref": "#/definitions/response"
    },
    {
      "$ref": "#/definitions/jsonReference"
    }
  ]
},

jaime-olivares avatar Jun 29 '16 06:06 jaime-olivares

@jaime-olivares You are right, the set of valid OpenAPI definitions can't be described with an OpenAPI schema.

It also can't be fully described using JSON Schema either, you have to read the specification text in addition to know whether it is actually valid. But JSON Schema allows a better approximation (like the one in the JSON schema document you cited).

There is a reason for this discrepance: JSON Schema is made for validation, while Swagger/OpenAPI is made for defining the API, and allowing to map the definition to constructs in (beside others) statically typed programming languages. It is not that easy to map e.g. patterned properties of a JSON object to e.g. a Java class, therefore it was left out.

ePaul avatar Jun 29 '16 12:06 ePaul

@ePaul, I haven't followed the entirety of the conversation so I apologize if I am missing something already covered, but the reasoning in the last comment seems odd (to me).

Swagger/OpenAPI is made for defining the API -- an API contains a number of routes which accept/return data, and the thought is that, without fully supporting JSON Schema, there are limitations to how that can that data can be defined.

The argument of "it is not that easy to map" seems like it should be outside of the this particular discussion -- Swagger/OpenAPI defines the API, whereas other tools like Swagger Codegen are the ones that should bear the burden of how easy/tough it is to map from the API to a particular language.

Regardless of easy/tough, fully supporting JSON Schema at least gives code generators a chance.

mm-gmbd avatar Jun 29 '16 13:06 mm-gmbd

@mm-gmbd It has been my experience that when selecting features to include in OpenAPI that the viability of tooling support has been a significant consideration. Nobody wants a spec that is difficult to implement because then you end up with non-compliant and varying implementations which defeats the purpose of having a spec in the first place.

darrelmiller avatar Jun 29 '16 14:06 darrelmiller

@darrelmiller, good point. However, rather than limit everybody because it is tough to implement for one, or some, languages, wouldn't the better (subjective) option be to support something that, again, gives code generators a chance?

Also, to contrast your comment, "Nobody wants a spec...", just based on the discussion in this thread, I can definitely tell that somebody wants to have this supported because it can immediately begin more fully describing their data and types.

Is there going to be a schema (JSON Schema or not) that perfectly describes everything that makes it easy for all languages and tooling? Sounds like a unicorn. Rather than wait, maybe something is better than nothing?

mm-gmbd avatar Jun 29 '16 15:06 mm-gmbd