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

@mm-gmbd I would like to see OpenAPI remove the direct dependency on json-schema and allow API creators to use whatever type of schema mechanism they want. That would mean you could use draft-4, draft-5, or something completely different like JSON Content Rules It would be the job of tooling to declare what type of schema formats they support. It would no longer be a concern of the OpenAPI spec. The OpenAPI spec would only be concerned with identifying the type of schema used and pointing to the instance document.

Having said this, I do not yet have a full understanding of the implications of taking that direction. I may be dreaming in technicolor :-)

darrelmiller avatar Jun 29 '16 16:06 darrelmiller

I have seen some biased/constrained opinions in this thread.

A schema that cannot be mapped to statically-typed languages is not bad at all. Not every schema has to be mapped to a POCO. That's vanilla programming. There are more complex cases outside the business software world. I state that as an industrial software developer.

Code autogeneration is not a mandatory feature of an API-First tool, as documentation or validation are not. Even in case of a tool is not able to auto-generate code (for whatever reason), an auto-generated documentation is still valuable for others to produce a customized code generation tool (I do that frequently with visual studio's T4 scripts), and the raw API spec file may be useful for validating messages in a test phase. In worst case, we also can just write code manually, by reading the API spec. That is still API-First development.

That said, I can confirm that RAML did the job with my 2 unsupported use-cases with Swagger: pattern properties and multi-typed arrays, in a very straight and concise way, so I am switching to it.

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

@darrelmiller - maybe there is a middle-ground here, although it may be tough to support. Consider a "schemaType" property that describes what schema is being used to describe the schemas throughout the API.

This would allow full support of JSON Schema v4, and the "schemaType" would be json-schema-v4, and when passing the API to a code-generator, it would know, based on the "schemaType", whether it did, did not, or partially support the schema definitions throughout the API.

That could satiate the request of this issue, while supporting other schemas in the future.

Maybe that's my technicolor dream :)

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

@mm-gmbd Many people want to support different media types, e.g. Xml as well as JSON, so they may want to use both JSON-Schema and XSD Schema in the same API.

darrelmiller avatar Jun 29 '16 17:06 darrelmiller

@darrelmiller - isn't there a slight difference between JSON-Schema and XSD Schema?

The difference I see, and maybe I'm getting it wrong, is that XSD Schema is specifically for describing the structure of an XML element. Whereas, JSON-schema describes an element, whether it is just a number, a string, a boolean, or an array or object of those elements, which allows JSON-schema to describe general data structures that are not necessary Javascript Object specific.

However, to your point, maybe the middle ground is to allow the schemas throughout the API to each define what type of "schemaType" parsers should utilize (i.e. json-schema-v4 or xsd-schema), to allow for both to be present in the same API.

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

@mm-gmbd I don't really see any difference between the goals of XML Schema and JSON Schema. From the first paragraph in the JSON Schema spec,

JSON Schema defines the media type "application/schema+json", a JSON based format for defining the structure of JSON data

Open API does blur the line by introducing the xml property to allow the Schema Object to also describe xml documents, but that doesn't change the intent of JSON Schema.

darrelmiller avatar Jun 30 '16 00:06 darrelmiller

@darrelmiller, but, as I mentioned in my last comment JSON data can simply be a number, a string, a boolean, or an array or object of those primitives, which are basic constructs in several languages outside of just being "JSON data".

Maybe this is a capability of XML Schema as well? I figured XML Schema was solely for describing XML data/structures, which aren't as directly applicable to primitives/structures in other languages. I'm assuming here, so I could easily be wrong, but I think that gets the point across of what the "difference" is between the two (that I see).

mm-gmbd avatar Jun 30 '16 12:06 mm-gmbd

I like the idea of a schemaType property, and would prefer to have this on the response level as my APIs support both JSON and Atom/XML via content negotiation. So I'd link to a JSON Schema for one content-type value, and to an XML Schema for the other content-type value.

ralfhandl avatar Jun 30 '16 14:06 ralfhandl

Tackling PR: #741

webron avatar Jul 21 '16 21:07 webron

I'd like to chime in as one of the people ok with a discriminator to be deterministic, but do not want a 1:1 mapping between discriminator values and definition model names.

I'm working with an API method that can return a list of connections to other people in the form of profiles (of other users on the site) or contacts (lightweight contact data that doesn't belong to a registered user).

{
  "links": [
    {"linkType": "profile", "id": "x2fx", "profileType": "creator", "name": "A Registered User"},
    {"linkType": "contact", "name": "An Unregistered Contact", "email": "[email protected]"}
  ]
}

The data works fine under a deterministic model (with linkType being a discriminator), however I do not want to be forced to rename #/definitions/ProfileLink to #/definitions/profile because that could conflict with definitions elsewhere like the definition for the full Profile model; nor do I like the idea of being forced to change "linkType": "profile", to "linkType": "ProfileLink".

Even worse, my full swagger.json is made by merging multiple versioned documents (ie: I have a v1.json, v2.json, etc... that merge to create a swagger.json exposing multiple /v#/ versioned endpoints), this works perfectly fine and definitions could even be handled by renaming references to include a version (ie: {"$ref": "#/definitions/ProfileLink"} would become {"$ref": "#/definitions/V1ProfileLink"} and Swagger would work fine. But discriminator is the only part of OAI/Swagger that is incompatible with that, because it would make it so only "linkType": "V1ProfileLink" will validate and next version data will be "linkType": "V2ProfileLink".


As a side suggestion; I can't offer an idea on how to deal with the non-deterministic models, but I did have an idea related to discriminator and oneOf/anyOf.

What about supporting something like the following:

{
  "definitions": {
    "CatModel": {
      "identifier": "cat",
      ...
    },
    "DogModel": {
      "identifier": "dog",
      ...
    },
    "Pet": {
      "type": "object",
      "discriminator": "type",
      "required": [
        "type"
      ],
      "properties": {
        "type": {
          "type": "string",
          "enum": [
            "cat",
            "dog"
          ]
        }
      },
      "anyOf": [
        {"$ref": "#/definitions/CatModel"},
        {"$ref": "#/definitions/DogModel"},
      ]
    }
  }
}

As I can tell this is still deterministic, and a little better than what we currently have.

  • discriminator still defines what property determines the model to use
  • identifier when paired with discriminator means that the values are no longer locked into model name; "cat" can be mapped to PetCat for a Pet model and mapped to CatHair in an Allergen model
  • As long as anyOf is a $ref to a definition code generators can still create named models in typed languages
  • When anyOf is used this way it's possible for a JSON Schema validator to validate this even if it doesn't know what discriminator is

dantman avatar Sep 06 '16 07:09 dantman

Just my $0.02.

First, I love standards and am very happy that swagger exists. Well done to the team. Thank you. But this issue needs to be fixed and full support for JSON schema v4 accepted.

Now, I am very happy to be corrected. But just to illustrate how really ridiculous and broken swagger is without this full support.

Because of this limitation you cannot actually use swagger to document an API that produces swagger JSON.

What??!! A JSON specification for documenting APIs cannot actually document an API that produces itself ...

An API that produces swagger JSON is just an API right? And swagger is for documenting APIs right? And giving other systems a means to interrogate machine-readable API specs via an API isn't so weird a notion. And as an API it should also be documented in the same way as the other APIs right? - in this case the schema for the response JSON is the swagger 2.x schema.

.... which fails validation against itself. Correct. The schema fails JSON that includes the swagger schema to describe a response.

So, using swagger it is not possible to correctly document an API response that produces swagger JSON. Swagger schema does not support documenting responses that are valid swagger JSON (according to swagger schema).

Like, whoever thought that was a good idea.

If the argument for not fully supporting schema is based around statically typed languages then just how do you get to deciding that the swagger schema is a special case and should be excluded from this.

I should be able include verbatim the swagger schema in swagger JSON to describe such an API response. And no, using a remote $ref reference to an external schema is not the answer to this.

Or am I totally wrong? Like I said, happy to be corrected here.

StrayAlien avatar Dec 06 '16 22:12 StrayAlien

There are some efforts in progress to support polymorphic data with oneOf and anyOf which I believe are going to appear in the next revision of the spec.

You touch on a topic that is close to my heart though. Way back in swagger 1.x I could use full json schema to validate the input and specify the swagger data model. This was mostly because swagger wasn't very ambitious about the data model spec and largely left that alone. During the creation of swagger spec 2.0 it was decided that the spec would only be extensible via special naming convention x-blah. That was a decision that put an end to the ability to use full json schema which took away much of the descriptive power of swagger 1.x. The decision to explicitly deny attributes that do not conform to the spec means it's unlikely you will see that full descriptive power return as they would need to include everything in the spec, much of which is outside of the things swagger should concern itself with.

I would love to see swagger in some incarnation allow extensibility in the spec without any naming convention restrictions, thus allowing one to use valid json-schema again.

paulhill avatar Dec 06 '16 23:12 paulhill

Thanks Paul,

I think a lot of people would like to see that. I'm not sure whether it is just me, but the idea of an API documentation specification that can't describe an API for itself is near on lunacy. It sounds harsh, but on that basis it can only really be described as a toy.

Imagine if JSON schema or XML schema could not validate themselves ...

It is unfortunate, but, where I am, because of this we have now got to drop swagger. In large organisations you get handed schemas you have to support. Not being able to even use a 'definitions' block in your own schemas is pretty lame.

It is a shame as this area of technology really needs good long-lived standards. This lack of flexibility means swagger can only get limited uptake on the large scale and thus will have limited life. And if it doesn't get full schema support it will be replaced by something that really does the job.

Like I said. A bit of a shame really.

StrayAlien avatar Dec 07 '16 00:12 StrayAlien

Validation and modeling are different beasts. JSON schema was designed for validation, not modeling. Thus supporting everything that it has for validation does not make sense for modeling in many cases.

3.0 has greatly increased support for JSON schema draft 4.

Decide what you want the spec to do. If it's just validate, then yes, there are constructs that may make sense outside the goals of design.

fehguy avatar Dec 07 '16 00:12 fehguy

Thanks fehguy. Where can I find out more about v 3.0? If there a published draft, or a repo?

StrayAlien avatar Dec 07 '16 02:12 StrayAlien

It's right here in this repo. From the home page there is a link to the branch where we're working on 3.0.

https://github.com/OAI/OpenAPI-Specification/blob/OpenAPI.next/README.md

The in-progress spec is here, if you don't feel like reading the README:

https://github.com/OAI/OpenAPI-Specification/blob/OpenAPI.next/versions/3.0.md

fehguy avatar Dec 07 '16 02:12 fehguy

Thanks fehguy - I did see that branch but wasn't sure I was in the right place. (though I did see your name on it which made me think I was . :-) )

The big question is ... can it describe itself? Off for a read.

If it can, what kind of release timeframe is v3.0 set for?

Thanks again.

StrayAlien avatar Dec 07 '16 03:12 StrayAlien

"can it describe itself?". No.

No apparent schema support for id keyword and a schema having its own definitions. As v3 is at the moment I still could not use it to describe an API that produces swagger JSON ....

It there a separate v3 discussion area that you could point me to?

StrayAlien avatar Dec 07 '16 03:12 StrayAlien

@StrayAlien

Imagine if JSON schema or XML schema could not validate themselves ...

From wikipedia's article on XML schema

Practical limitations of expressibility: XSD cannot require a specific root element (so extra information is required to validate even the simplest documents). Content and attribute declarations cannot depend on attributes or element context (this was also listed as a central problem of DTD). [Therefore] It is not 100% self-describing ... even though that was an initial design requirement.

MikeRalphson avatar Dec 07 '16 07:12 MikeRalphson

Hah! Oh that made me lough out loud! Very well done Mike. :-) I read this an hour ago and I am still smiling :-) Nice.

Though, that still doesn't change my feeling that a technology for describing APIs should be able to describe an API that produces those descriptions. Kinda makes sense I reckon.

I'll explain my situation: We're not talking about a guy here wanting to describe his shopping cart app. I am part of a API standards movement in a (very) large financial organisation. Part of those standards is that going forward, all APIs should have machine readable descriptions of themselves - part of a mindset move from SOAP/WSDL and a 'service enablement' of the org and mainframe systems so on. Indeed, there is a legislative requirement looming to publicly expose a number of financial APIs and that effort is now underway. This swagger limitation means that some APIs now have to be 'special cases'

What is also means is that when some part of the organisation that is designing an API using JSON schema to describe payloads hands over their interface spec it will not be able to be described in swagger. They'll have used ids, and #/definitions and oneOf/anyOf and friends (coming in swagger v3) and whatever they need to describe the payload / param structural correctness.

If we can't use those schemas in API docs then we're sunk with swagger.

It means that existing APIs to be exposed that have not taken swagger's limitations into account may not be able to be described.

Now, I have been heard many times saying "a bad standard is better than no standard". I do honestly believe that. We need standards. But even a bad standard has to actually achieve the functionality that you need or have decent workarounds. I dearly dearly want standards like swagger to succeed. But to succeed, it must be able to describe APIs - you simply cannot ask an organisation this large with such complex APIs to dumb down their objects and schemas to something swagger can describe.

It absolutely has to be the other way around. The API description tool has to fits people needs. It cannot be people working to fit the needs of the API description tool.

And again. Nice one. Still smiling at that. :-)

StrayAlien avatar Dec 07 '16 09:12 StrayAlien