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

Great conversation on this important topic. One thing I think hasn't been mentioned: JSON Schema was not designed with APIs in mind, it is primarily maintained for the NoSQL range of databases. As such, there are approaches accommodated which simply don't fit well with common/practical API usage scenarios. As noted, polymorphic responses are pretty rare (because they cause pain for everyone involved)...this begs the question: should handling the <1% case make the priorities? There are certainly other features in JSON Schema we all might benefit from supporting, my opinion is that anyOf/oneOf is full of pain and despair in practice, both in API usage and in tooling implementation.

I strongly echo Ron's opinions, and suggest the following approach:

  1. Approach polymorphism support as a separate issue, and investigate other potential solutions to accomodate the small crowd that really needs this support. As noted discriminator is in 2.0 to address this problem, and as far as I know, has really never been implemented due to it's inherent complexity (and perhaps lack of JSON Schema compliance). We had to take this same approach in order to tackle composition and inheritance support with allOf on the tooling side a while back...polymorphism discussions really drag down other important issues.
  2. Review features/fields in JSON Schema we should add toOAS, outside of the polymorphism issues. I think that's the original intent of this issue, and has been echoed in a number of other issues.

jharmn avatar Feb 08 '16 16:02 jharmn

The flexibility is required, and you'll continue to receive questions and issues regarding these problems.

Whether it's implemented using JSON Schema or BananaTech 2.0, is less important.

glen-84 avatar Feb 08 '16 18:02 glen-84

@jasonh-n-austin I'd love to see the data behind your assertion that:

polymorphic responses are pretty rare (because they cause pain for everyone involved)...this begs the question: should handling the <1% case make the priorities?

In the statically typed world that might be the case but in Ruby or JavaScript it's not uncommon.

drewish avatar Feb 08 '16 20:02 drewish

@drewish I wasn't commenting on language-specific, I'm just saying that it's a less popular pattern in API design. It's certainly arguable it's more common, I really should have said that I doubt it passes an 80/20 rule of priorities...i.e. it hardly effects the broad spectrum of API design. I don't argue it's important, but IMO the other issues in JSON Schema are probably more far reaching, and should be focused on in this issue, while polymorphism should be addressed distinctly. My only real intent is to move the discussion on broader JSON Schema support forward.

jharmn avatar Feb 08 '16 20:02 jharmn

I agree with you @webron, the main point is usability and Full JSON Schema compliance might not be required, but some little adjustments might be necessary.

In my opinion, the following changes can be very usefull for a lot of people:

  • nullable properties support. It's the combination of anyOf/oneOf support and null primary type support (#229)
  • The anyOf/oneOf pattern is not so uncommon. GeoJSON is still my example, it's a standard output format which is best described with oneOf (example: https://github.com/fge/sample-json-schemas/blob/master/geojson/geojson.json). OAS should allow to easily describe common mainstream formats out of the box, GeoJSON being one of them.
  • another use case for oneOf/anyOf is mixed lists which are not so uncommon.
  • anyOf/oneOf might also be usefull when you API support both ID and slug as URL identifier or query parameters (but it's not in the scope of schema objects)

A wider polymorphism support is far less important to me as the current pattern works (very well) for linear inheritance. But I agree mixins are a really common pattern, in both Python and JavaScript for example (my primary stack). I understand that it may be complex sometimes, but It's up to the developper to chose whether or not it's a good pattern for his case. Sometimes it's simply necessary.

There is already an open issue for anyOf: #377 but I think oneOf is also important.

noirbizarre avatar Feb 11 '16 13:02 noirbizarre

Hopefully this is on topic. I've been using Enum's for inheritance and unions. See this Gist: https://gist.github.com/fadeddata/32e0302d2a55e1392b9c

Specifically look at the questionType property in the Question definition.

      questionType: 
        type: object
        enum:
        - $ref: '#/definitions/ScaleQuestion'
        - $ref: '#/definitions/MultipleChoiceQuestion'
        - $ref: '#/definitions/TextQuestion'

The goal of the API is to sort of do what Google Forms does for questions.

This seems to work quite well and makes the documentation tool happy. Generated code is mostly junk but I don't use that anyways. Does this help solve anyones problems? Am I grossly misusing the tool?

fadeddata avatar Feb 26 '16 15:02 fadeddata

@fadeddata This really looks like misusing the tool. You are defining your questionType property to contain an object with just a $ref property, which contains one of the mentioned three strings.

From the relevant JSON Schema Spec section:

5.5.1. enum

5.5.1.1. Valid values

The value of this keyword MUST be an array. This array MUST have at least one element. Elements in the array MUST be unique.

Elements in the array MAY be of any type, including null.

5.5.1.2. Conditions for successful validation

An instance validates successfully against this keyword if its value is equal to one of the elements in this keyword's array value.

The elements of the enum array are not schemas, but JSON entities to be compared for equality.

(Also, at least in Swagger-UI, it doesn't really look like I guess you intend it to look.) Swagger-Editor shows it differently – it seems to follow the $refs, though I'm not sure the result is really what you meant here.

ePaul avatar Feb 28 '16 12:02 ePaul

Paolo,

Can you elaborate on how this is misusing the tool?

The value of the enum keyword is an array of objects ($ref pointers).

The array has at least one element.

The elements in the array are unique.

The elements are of the type $ref (object/pointer)

A schema is a json entity.

I've been struggling with a simiar issue and I'm looking for clarification here in terms of how this is misusing the tool.

-Mark

On Sun, Feb 28, 2016 at 6:49 AM, Paŭlo Ebermann [email protected] wrote:

@fadeddata https://github.com/fadeddata This really looks like misusing the tool. You are defining your questionType property to contain an object with just a $ref property, which contains one of the mentioned three strings.

From the relevant JSON Schema Spec section http://json-schema.org/latest/json-schema-validation.html#anchor76:

5.5.1. enum 5.5.1.1. Valid values

The value of this keyword MUST be an array. This array MUST have at least one element. Elements in the array MUST be unique.

Elements in the array MAY be of any type, including null. 5.5.1.2. Conditions for successful validation

An instance validates successfully against this keyword if its value is equal to one of the elements in this keyword's array value.

The elements of the enum array are not schemas, but JSON entities to be compared for equality.

(Also, at least in Swagger-UI http://petstore.swagger.io/?base_url=https://gist.githubusercontent.com/fadeddata/32e0302d2a55e1392b9c/raw/03ea06655deb2cc126cb89ca125ffb2f0e866792/enum.yaml, it doesn't really look like I guess you intend it to look.) Swagger-Editor shows it differently – it seems to follow the $refs, though I'm not sure the result is really what you meant here.

— Reply to this email directly or view it on GitHub https://github.com/OAI/OpenAPI-Specification/issues/333#issuecomment-189864341 .

gravesmedical avatar Feb 28 '16 21:02 gravesmedical

@webron has a lot of experience with this one. Can you please chime in?

fehguy avatar Mar 01 '16 00:03 fehguy

I don't think this does what you'd hope it does.

Following the gist, you're saying that the questionType property needs to have the value of (for example):

NumberValidation:
    allOf: 
    - $ref: '#/definitions/Validation'
    - type: object
    required:
    - comp1
    - comparison
    properties:
      comp1: 
        type: number
      comp2: 
        type: number
      comparison:
        type: string
        enum: [gt, gte, lt, lte, =, "!=", between, "!between", whole]

Not something that validates against that schema, but the value has to be the schema itself. enum just sets possible values for the defined schema.

webron avatar Mar 01 '16 23:03 webron

To give some perspective the backend that I'll be implementing this in is Scala. I will likely use the Play JSON Derived Codecs (https://github.com/julienrf/play-json-derived-codecs) to serialize/deserialize the messages. So this is going to be used with a statically typed environment. The code will look something like:

sealed trait QuestionType {
  val kind: String
}

case class ScaleQuestion(kind: String, fromLabel: Option[String], toLabel: Option[String], from: Int, to: Int) extends QuestionType

case class MultipleChoiceQuestion(kind: String, other: Boolean, choices: List[String], display: String) extends QuestionType

etc...

The Swagger def looks like:

  ScaleQuestion: 
    type: object
    required:
    - kind
    - from
    - to
    properties:
      kind:
        type: string
      fromLabel:
        type: string
      toLabel:
        type: string
      from: 
        type: number
      to: 
        type: number
    example:
      {
        "kind": "ScaleQuestion",
        "fromLabel": "I never cough",
        "toLabel": "I cough all the time",
        "from": 1,
        "to": 5
      }

  MultipleChoiceQuestion:
    type: object
    required:
    - kind
    - choices
    properties:
      kind:
        type: string
      other:
        type: boolean
      choices: 
        type: array
        items:
          type: string
      display:
        type: string
        enum:
        - radio
        - select
    example:
      {
        "kind": "MultipleChoiceQuestion",
        "other": false,
        "choices": ["Option 1", "Option 2", "Option 3"]
      }

fadeddata avatar Mar 02 '16 01:03 fadeddata

@webron I think I understand what you are saying. The enum, as the yaml is written, is specifying that it's value must conform to exactly as the ref is specified.

I need away to tell the reader of the documentation that the input can be one of a few things. I didn't find the discriminator functionality to be that useful in this endeavor.

What would you propose? A different path for each question type?

POST /question/multiple-choice-question POST /question/scale-question

fadeddata avatar Mar 02 '16 01:03 fadeddata

@gravesmedical While the example from @fadeddata is a valid OpenAPI (2.0) definition according to the Spec, it has not the same meaning as he seem to want it to have. Though maybe I misunderstood him there.

These are exactly the valid questionType values according to the definition:

  1. { "$ref": "#/definitions/ScaleQuestion" }
  2. { "$ref": "#/definitions/MultipleChoiceQuestion" }
  3. { "$ref": "#/definitions/TextQuestion" }

No others, specially nothing which I would take as a representation of some form of question.

If we assume that the refs are replaced here (nothing in the spec says so), these would be the valid values:

  1. { "allOf": [ { "$ref": "#/definitions/QuestionType" }, { "type": "object" } ], "required": [ "from", "to" ], "properties": {"fromLabel": {"type": "string"}, "toLabel": {"type": "string" }, "from": { "type": "number"}, "to": { "type": "number"} } }
  2. { "allOf": [ { "$ref": "#/definitions/QuestionType" }, { "type": "object" } ], "required": ["choices"], "properties": { "other": { "type": "boolean" }, "choices": { "type": "array", "items": { "type": "string" } }, "display": { "type": "string", "enum": [ "radio", "select" ] } } }
  3. { "allOf": [ { "$ref": "#/definitions/QuestionType" }, { "type": "object" } ], "properties": { "validation": { "type": "object", "enum": [ { "$ref": "#/definitions/NumberValidation"}, { "$ref": "#/definitions/TextValidation"}, { "$ref": "#/definitions/RegexValidation" } ] } } }

Still I don't assume one actually want your clients to send or receive one of these three objects – we want them to send/receive something which is described by this schema. But this is not what enum does – you want proper oneOf support as discussed further up in this issue.

ePaul avatar Mar 02 '16 20:03 ePaul

@ePaul Yes, that makes tons of sense. It seems that this is supported and valid syntax, but it is likely not accomplishing his intended purpose (presuming he is thinking of "instantiating" the references to validate them.

In the instance that it is actually validating against that schema, it would be correct.

Thanks for the clarification.

gravesmedical avatar Mar 03 '16 20:03 gravesmedical

Great thread, everyone, glad to see there is a lot of interest here. I'm a little late to the party, so apologies if I raise points that have already been noted. I've been loosely following Swagger and RAML for a few years from an architectural point of view. I am seeking a standard way to do design-first API development. Swagger was traditionally weak (IMHO) in this area and RAML rose to the challenge but was (is?) lacking in the tooling department and developer mindshare. The Swagger tooling I've used is great and I rarely encounter a fellow hacker that isn't familiar with Swagger at least by name.

I really like the spirit of OAI and I hope we will continue to see rapid evolution here. I also understand the concerns and tradeoffs necessary to satisfy the broad goals of the OAI specification. I think it would be helpful for the OAI to document and prioritize its use-cases in order to more formally guide the evolution of the spec. Certainly the ability to document any possible API and support code-generation for any possible language is too broad, but simply narrowing the possible APIs doesn't seem like the right approach to me.

When @fehguy says

ever wonder why there's no c++ generator for RAML?

I do wonder whether it was technically infeasible or there was simply no interest in having one in the first place.

Back to the issue at hand, let me share an payload example from one of the APIs I work on:

{
  "id": "85d8f8fc-15a5-40f4-93c9-6c09597fc403",
  "createdOn": "2015-10-21T18:28:06.123-04:00",
  "properties": {
    "singleValue": "value",
    "multiValue": [ "value1", "value2", "value3" ]
  }
}

In the above example, the properties id, createdOn and properties are formally declared and properties is an object which itself can have an arbitrary set of properties whose values can be either a single string, or an array of strings. We can validate this using JSON-schema as follows:

{
  "$schema": "http://json-schema.org/schema#",
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"
    },
    "createdOn": {
      "type": "string",
      "format": "date-time"
    },
    "properties": {
      "type": "object",
      "additionalProperties": {
        "oneOf": [
          {
            "type": "string"
          },
          {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        ]
      }
    }
  },
  "additionalProperties": false
}

This certainly presents a problem for code generation - how do you infer the narrowest type that can represent either a string or an array of strings - but it is trivial for someone to manually create a mapping in the language of their choice.

So, when @webron says

I'd say that if you can't generate code for an API, then that API is not usable

I wholeheartedly disagree.

I think this in a good example where oneOf neatly solves the issue and discriminator support in Swagger does not. I want to use basic types for the polymorphism, not something I can add a discriminator to. Please correct me if there is a way to accomplish this in Swagger as it is literally my only blocker to adopting Swagger for this API.

Thanks, everyone, for the work so far (and sorry for writing a novel here).

emattheis avatar Apr 05 '16 21:04 emattheis

@webron says

I was extremely frustrated with JSON Schema when I discovered that some things cannot be done (you simply cannot a JSON Shema that fully validates the Swagger object, for example - just can't be done) or it imposes an insane structure that actually forces you to do repetitions in some cases.

A bit late to the party here, but simillaly to @emattheis , I've been following both Swagger, RAML, and JSON Schema for over 2 years now. I've been trying to drive further work on JSON Schema, making draft 4 the standard, but there's lots going on behind the sceens that I can't or shouldn't talk about. I'm pretty sure that the people involved would LOVE your feedback, and any suggestions for improvment would be welcome. Not saying you haven't given feedback, I don't know. Realistically, the spec, and further development of, is all a bit of a mess / unclear right now, and has been for some time.

Relequestual avatar Apr 06 '16 12:04 Relequestual

@emattheis Your example could be described without oneOf, since JSON Schema Draft4 supports arrays as values of type properties:

The value of this keyword MUST be either a string or an array. If it is an array, elements of the array MUST be strings and MUST be unique. String values MUST be one of the seven primitive types defined by the core specification.

So you can write:

{
  "type": ["string", "array"],
  "items": {
     "type": "string"
  }
}

And it validates both string and array of strings.

And de jure it valid according to OpenAPI spec:

The following properties are taken directly from the JSON Schema definition and follow the same specifications: ...

  • type

It also passes validation with JSON Schema for OpenAPI spec, because of this. @fehguy @webron Was it an intentional decision to support this feature?

IvanGoncharov avatar Apr 06 '16 14:04 IvanGoncharov

@Relequestual Biggest problem with JSON Schema is it DSL for validation. It was meant to describing constraints on data and not data themselves. So it almost impossible to use it for something other than 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. Try to represent oneOf or anyOf in such UI without totally confusing a user.

@Relequestual @webron we can continue this discussion. But probably better to move it to different issue/forum/mailinglist since it diverge from the main topic of this issue.

IvanGoncharov avatar Apr 06 '16 15:04 IvanGoncharov

{
  "type": ["string", "array"],
  "items": {
     "type": "string"
  }
}

is invalid in 2.0. I know it's not clear from the spec itself, but it's not supported. type can only have a single value.

webron avatar Apr 06 '16 15:04 webron

@webron I suspected that because this behaviour is a subset of oneOf. I think we should discuss real-life problems caused by oneOf absence. And try to address at least most common ones.

IvanGoncharov avatar Apr 06 '16 15:04 IvanGoncharov