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

I'm sorry but you called them edge cases. I followed your wording.

It's clear everything can't be supported but on the flip side it's essential to provide some sort of way to document these edge use cases.

There's a way to document a simple map, and we've covered that (elsewhere). There is a way to document polymorphism, perhaps not all polymorphism.

I agree about patience statement, but that goes both ways. I love that people have ideas and voice them. I love that people don't give up and insist. I believe that's crucial to make progress. There is absolutely nothing personal here if we say X or Y.

Some people have been with the process of the spec for a long time, and some for very little. I'm not saying that the voice of the new people is less important. On the contrary, it can be even more important because it may hit things others haven't, or some thing that were just 'accepted' and shouldn't have been. That said there's history. And history is not always documented, or not always easily accessible. It's very easy to critique decisions without understanding the background. We also try to bring a fuller experience here - we don't want to attend to a specific group of users if it hurts a much larger group of users. Given where we are now, I should hope that we've proven we do have a wide view on things and the entire ecosystem. When we object to something, it's not because 'we don't like it'. We may not agree on the points, which is okay too.

What I sometimes fail in doing is giving proper background and proper details. It's especially difficult when old issues get back to life. It also takes an insane amount of time, and we all have a job to do on top of this. However, specifically here, I believe we've covered the different angles on things.

To me, the points that you and @drewish (and possibly others, it's a long thread) have made are not really about providing full support for JSON Schema, but providing support for specific cases which we may want to do, and we may be able to do without anyOf. Now, we can continue talking about the process, about the past, about semantics and all that. We can also decide that we want to be practical and explore the actual problem and not a specific possible solution. We may end up realizing that we have to add support for anyOf and we may not.

I'll be the first to say that the current solution is less than perfect and would love it if we can have a productive discussion on what kind of APIs you'd expect to be able to describe and then discuss the options of practical implementations. Give us a chance, we may surprise you. If we do this now, it'll greatly help the next version of the spec. If we wait, we may end up with an impractical solution again, whether by not supporting common API designs or by introducing unusable specs.

Now, I mean absolutely no offense here, but I've spent a lot of time on this topic, whether here or other places. Unless I feel this is headed into a more productive discussion, I will have to let it be until the official talks on the version begin. I think that everything 'meta' that could have been discussed and covered has been already (and probably multiple times).

webron avatar Jan 21 '16 02:01 webron

The first scenario I've run into where having oneOf would be useful in on a rails based API I've been working on documenting. All the GET routes that fetched data were pretty easy, but now that I'm trying to document the POSTs and PUTs I'm finding it very hard to describe the inputs. One example is an endpoint to save personal information which has two different formats for the JSON body:

  • fields for: name, address, phone, etc
  • a single token_id that references data sent in a separate request to a different endpoint

The former has several required fields, the later only requires token_id. This seems like an ideal case for a oneOf. For workarounds I guess I've got a couple options:

  • It's not being used externally yet so I could split the functionality up into two separate endpoints and document them separately. But that doesn't seem like a great answer.
  • Maybe I can get the discriminator working for this use case? It definitely seems like a long way to do it.
  • I'll probably just end up spelling out the required fields in the description in a non-machine readable manner.

I think one reason this seems so frustrating is because JSON Schema was used as a starting point for the Swagger spec and then parts of it were deliberately removed/ignored (in the spec itself it's not clear why). If Swagger was a clean slate that just never had that as a possibility, it'd feel different than looking and seeing a ready made solution explicitly ruled out.

I'm half joking when I say this: maybe you could solve this by just removing the references to JSON Schema. Then there'd be no expectation that it'll have the same level of functionality.

I'm not trying to be rude when I say this but it think if the focus is so strongly on a code gen friendly spec you should call that out in the spec itself and the other promotional material. It took me working with Swagger for a month or two to really understand how opinionated it is. Looking at the home page, getting started guide, and spec itself, I'd think it's a just general purpose format for documenting any type of APIs. Let's state these assumptions about how it's to be used clearly.

drewish avatar Jan 21 '16 06:01 drewish

@webron If you haven't read it Gödel, Escher, Bach is definitely worth your time. I think his dialog on a building a record player that can play all sounds is an apt analogy for this topic: http://genius.com/Douglas-hofstadter-contracrostipunctus-annotated

drewish avatar Jan 21 '16 06:01 drewish

I have looked all over, but I have not yet seen a reason why "oneOf" is not supported.

Could someone please point me in the right direction to a succinct reasoning for this choice?

gravesmedical avatar Feb 02 '16 01:02 gravesmedical

Looking at the home page, getting started guide, and spec itself, I'd think it's a just general purpose format for documenting any type of APIs. Let's state these assumptions about how it's to be used clearly.

@drewish is spot on. Many of us are not developing a green field api and are looking for tools that will allow us to document existing apis that may not conform to the ideals set forth currently by this spec. Many of us are also leveraging different forms of polymorphism and have no intention of changing the design of our apis to satisfy the tools we use to document them.

If the intention is to force developers into specific patterns for their apis then that should be clearly called out and proclaimed in documentation and on the homepage.

Prestaul avatar Feb 03 '16 01:02 Prestaul

I admit I've yet to have a chance to read @drewish's comment (sorry about that), but @Prestaul's comment caught my eye.

Many tools don't allow you to do various things. JSON Schema has things that it doesn't really support itself, or doesn't support well, and it doesn't fit all use cases. They don't go and state any assumptions or anything of that sort.

There's no intention to force developers into specific patterns, but there's also no intention to support all patterns. There's no contradiction there. Not every tool fits every job, and that's not really a problem. There's always a balance of what to do and what to support, and that's what we chose for 2.0. As such, there's no room for any kind of proclamations - the spec is available for you to read, and you can decide if it suits your needs or not. Instead of proclaiming what we don't do, the spec just proclaims what it does support.

Nobody is expecting you to change your API to satisfy the tool. Choose the tool that satisfies your needs.

webron avatar Feb 03 '16 01:02 webron

@webron, I just reread my comment and certainly didn't mean for it to come across argumentative. I simply think this thread reflects a common frustration from those of us who were eager adopters that later found swagger too restrictive for our needs. That frustration is magnified in those of us who already had experience with JSON-Schema, found it to be sufficient to describe any api fully, and were initially encouraged to see that swagger had adopted much of JSON-Schema.

@drewish, pointed out the frustration:

It took me working with Swagger for a month or two to really understand how opinionated it is.

He also pointed out what is probably the source of that opinionated nature: code-gen tools. It seems as though a tool designed for documentation first would never be built with such restrictions and if code-gen were offered later you might set restrictions around polymorphism depending on the destination language. I understand that polymorphic entities in an api make generating code in strongly typed languages very difficult, but many (probably most?) adopters are not using code generation and many are simply looking for a powerful set of tools for documenting their APIs.

I think what I was trying to say (and, at the risk of putting words in his mouth, I believe @drewish was saying as well) is that I read the spec, I spent time assessing it, I spent time implementing it, I wrote tools integrating it into my process, and was still surprised later by the limitations. At the least it seems we could identify limitations that have become common frustrations (e.g. polymorphism) and find ways to improve clarity around what is not supported.

Prestaul avatar Feb 03 '16 17:02 Prestaul

My exhaustion with being unable to describe polymorphism in swagger 2.0 led me to look around for alternatives and RAML fit the bill nicely.

RAML 1.0 just crushes swagger with their rich type system. http://docs.raml.org/specs/1.0/#raml-10-spec-types

Like @webron says

Nobody is expecting you to change your API to satisfy the tool. Choose the tool that satisfies your needs.

RAML was that tool for me

ghost avatar Feb 03 '16 17:02 ghost

@Prestaul I think you've summed up my issues very clearly. The only thing I'd add is that it feels like there's a lot of momentum behind Swagger and few alternatives. If it's going to be the only choice it needs to allow for more possibilities.

@norbew I'm excited to check out RAML.

drewish avatar Feb 03 '16 17:02 drewish

To be perfectly clear, swagger is not designed just to be a documentation tool. It's a description of the API interface, intended to be used with tools like documentation systems or code generators. It has never strived to model all possible APIs, period.

If that has ever been confusing then I apologize, hopefully it is not now.

If we supported everything that JSON Schema draft 4 had to offer, then the universe of tooling that can actually do something with the spec would dwindle and we would be nothing other than a modeling syntax like RAML. Then we would have the extremely limited practical usage of RAML, and that's certainly not the goal (ever wonder why there's no c++ generator for RAML?)

That said, there is not a hesitation to support more, but our goals are not simply to describe arbitrary APIs. We want to support tooling constructs as well, and codegen is one of, if not the most important of them. Adding more supported constructs that makes tooling overly difficult or even impossible is not an option.

fehguy avatar Feb 03 '16 17:02 fehguy

@fehguy that is all clear now but that is after months of usage and a day of reading through these GH issues... Did you have a comment about my last statement?

At the least it seems we could identify limitations that have become common frustrations (e.g. polymorphism) and find ways to improve clarity around what is not supported.

Prestaul avatar Feb 03 '16 17:02 Prestaul

@fehguy Please put that on the front page then. I pull up https://openapis.org and first thing I read is:

The OAI is focusing on creating, evolving and promoting a vendor neutral API Description Format based on the Swagger Specification.

There's nothing on there at all about code gen.

Flipping through the pages I get to https://openapis.org/specification and I finally discover some hints at it (I added bolding for emphasis):

The goal of the OAI specification is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service.

Again totally a worthwhile goal. It makes sense why c++ users would accept that restriction in exchange for those benefits. But as someone working primarily in untyped languages it's not helpful, and actively hobbles my usage. At this point I'm not even saying you should change it, just warn people about that trade off so they go into it with eyes open.

drewish avatar Feb 03 '16 17:02 drewish

OK, if nothing else, your time on this will help with documentation for others. I do think we have tried to make it clear what is supported in the specification, which is intentionally not a time commitment like reading the bible:

https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schema-object

The Schema Object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. This object is based on the JSON Schema Specification Draft 4 and uses a predefined subset of it. On top of this subset, there are extensions provided by this specification to allow for more complete documentation.

In addition there is an online, hosted schema validator which uses the JSON Schema representing the specification that should tell you specifically what is not supported:

swagger: '2.0'
info:
  version: 1.0.1
  title: Modeling Samples
paths:
  /foo:
    get:
      parameters: []
      responses:
        default:
          description: success
definitions:
  Sample:
    oneOf:
      - type: object
        properties:
          id:
            type: string
      - type: object
        properties:
          name:
            type: string

response via online validator:

$ curl -X POST --data-binary @sample.yaml -H content-type:application/yaml https://online.swagger.io/validator/debug | pretty
{
    "messages": [
        "attribute definitions.Sample.oneOf is unexpected",
        "attribute definitions.Sample.properties is missing"
    ],
    "schemaValidationMessages": [
        {
            "domain": "validation",
            "instance": {
                "pointer": "/definitions/Sample"
            },
            "keyword": "additionalProperties",
            "level": "error",
            "message": "object instance has properties which are not allowed by the schema: [\"oneOf\"]",
            "schema": {
                "loadingURI": "http://swagger.io/v2/schema.json#",
                "pointer": "/definitions/schema"
            }
        }
    ]
}

So I'm sorry it took so long to get to this point, but I think the tooling is there to avoid this. I think docs can always be improved, of course.

fehguy avatar Feb 03 '16 18:02 fehguy

@Prestaul this is a pretty long issue so I'm guessing you've described your questions about polymorphism in here. I would suggest moving those discussions to a different issue as this has become really around "supporting all of JSON Schema Draft 4" and not "limitations in Polymorphism".

fehguy avatar Feb 03 '16 18:02 fehguy

My 2 cent contribution because I think this issue is major.

I totally agree with @drewish and @Prestaul : Swagger was described everywhere (swagger.io, openapi.org...) as a tool for describing ANY API in a Language Agnostic way but clearly, after using it for a very long time, developping some tooling around it: it's not.

The oneOf, anyOf... is not about polymorphism (which is by the way not language agnostic at all) but about real world usages, most of the time not related to polymorphism.

To me, JSON Schema v4 is about compatibility and reusability.

  • We can find JSON Schema v4 validator in any language, this is not the case for Swagger specific subset.
  • If some people design JSON schema to describe any models, there a reason. This is the 4th draft with a lot of maturity. Choosing a subset of this work is like saying: we know better, you won't need this.
  • It's standardised so it allow to import existing schemas for commonly used data types. Having a subset of JSON schema forbid model import (GeoJSON is still very complicated to describe with Swagger, I can testify, I design a lot of spatial APIs)

By the way, most of the time, my server-side can expose full v4 models, my client can consume full v4 models, but I'm struggled with the swagger models not allowing me.

My point is that Swagger is meant to describe APIs (and it does it very well) but there is some caveat on the model part. JSON Schema provide the model part and it's doing well, there's an ecosystem (tooling, documentation, libraries, testers...). Why reinvent the wheel on the model part ?

If I'm understanding well, the main point is that tooling won't be able to support every case. It's not bad: just announce it: "This tool don't support XXX, YYY and ZZZ". But clearly some other tools support it and need it.

It seems to me that codegen is really tiny use case: you generate code once on a project start if you are in a spec to code approach. Documentation has to be for the entire product life. What a deceptive surprise when after month working on and maintaining a swagger documentation when you discover you can't describe anymore your new features.

Please support the full JSON Schema V4 specifications for models, it will unlock the full Swagger potential !

noirbizarre avatar Feb 03 '16 20:02 noirbizarre

I'm really happy to see everyone's involvement on this ticket. It shows that people care and want to see improvements, which is great.

@noirbizarre - I can't think of a single place where it says that Swagger aims to be a tool that can describe ANY API. In fact, I can point you to dozens of times that we have stated that Swagger does not aim to cover all APIs, but rather provide a comprehensive ecosystem for the APIs it is able to describe.

@Prestaul - Any tool has its limitations. 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. It may be the best of what's out there, but I'll be the first one to drop support for it at all if we could find an alternative (no plans for it, no worries). However, even with those limitations, I continued working with it and worked with the limitations. It's fine. I really can't and don't expect it to cover everything.

The spec clearly states that JSON Schema is not fully supported. I'm open to feedback as to how it can be clarified further, and I've modified the spec in the past to make portions of it clearer. I get the frustration of discovering it at a later stage, but I don't see how that's different than any other tool. Was I frustrated by JSON Schema? I was, because I assumed things at first as well. But the JSON Schema specification is also documented and the limitations can be derived from the spec. That's just how things work. We don't normally document what can't be done, but rather what can.


To me, code generation is not the real issue but it's a sign for the issue. I'd say that if you can't generate code for an API, then that API is not usable. It's not about the automated process, it's about the ability to write code that processes it. If you can write it manually, you should be able to generate it to speed up the process, that's all. Granted, this does not apply all the time, but in most cases it would. And before you say that you may not necessarily care about languages that can't use the API (easily or at all), please read the next point.


In my personal opinion, the specification should be such that when a user encounters the API description, they can feel confident that they can actually use it and implement it. There are many benefits for the API description - you can get documentation, validation, testing, monitoring, and yes, even code generation. The idea behind the wording of it being language agnostic is that you really should be free to use whatever you want, and still end up being able to use the API. It is my opinion that it's more important to be able to "describe some APIs that can be used by everyone" over being able to "describe all APIs that can be used by someone". When it comes to APIs, the consumers are more important than the producers - without consumers, there's no need for the API. If we can't make the consumers confident they can always use the description we are missing a major part of the goal.


Kindly remember that there are plenty of others out there who don't voice their opinion here. Some are definitely aligned with the opinions stated by users here, and some definitely feel things should stay as-is. We're trying to take everyone's opinion into account, whether voiced here or through other means.


Last, but absolutely not the least - I feel we're concentrating on solutions and not problems. That sounds off, doesn't it? We want solutions! Well, yes. However, just because everyone is sticking to a specific solution, doesn't mean it's the only solution or the right solution. I honestly believe we can solve quite a few of the issues raised with other means, given the chance to do so. For example, 'Incomplete support for polymorphism' is definitely an issue, and one that we should address. Can we solve it by supporting full JSON Schema? Sure, but there are costs. Can we solve it by doing something outside the scope of JSON Schema without those extra drawbacks? Possibly, but we haven't even given it a chance. Yes, there are numerous benefits to using JSON Schema directly, as @noirbizarre kindly mentioned. However, if we can find a solution that would satisfy both aspects (and I can think of a few) without being a direct usage of the full JSON Schema, wouldn't that be better? Please note that I'm not trying to start a discussion on that right now, but rather just raising the point that it seems many are fixated on a specific solution, which may not be the only one. And it applies to other tickets opened on the spec, not specifically the JSON Schema one. I'd ask people to take the time, isolate the problem they are trying to solve, and open tickets specifically for those issues. Once we start the process of work on the next spec, I just want us to keep that in mind and be creative when needed. I know it may seem that 'we' are against support for full JSON Schema, but that's not really the case. We're pretty much wearing multiple hats here and try to represent the voices of others as well. If we can do it in a smart way, I'd be more than happy to accommodate for more API descriptions.

webron avatar Feb 03 '16 21:02 webron

@webron (longest post ever).

fehguy avatar Feb 03 '16 23:02 fehguy

@fehguy challenge accepted.

webron avatar Feb 03 '16 23:02 webron

It seems as though a tool designed for documentation first would never be built with such restrictions and if code-gen were offered later you might set restrictions around polymorphism depending on the destination language.


If I'm understanding well, the main point is that tooling won't be able to support every case. It's not bad: just announce it: "This tool don't support XXX, YYY and ZZZ".

I completely agree with the above comments. Why restrict the specification, and provide no support for common patterns like JSON patch, just for the sake of code generation?

Something with the name "Open API Specification" may not be able to cover all possible scenarios, but it surely needs to cover a large percentage of them? Patching, describing spatial APIs, multiple response schemas, etc. are not far-out crazy ideas used by 0.5% of APIs in the wild.

The specification should be as flexible as is technically possible. It should be up to the API designer to decide which features to use depending on their specific requirements for code generation and other tooling.

If there are alternative solutions, then propose them and they can be discussed, but it seems to me that if you're already using a subset of JSON Schema, you might as well use more of it to provide these features.

glen-84 avatar Feb 07 '16 16:02 glen-84

The specification should be as flexible as is technically possible. It should be up to the API designer to decide which features to use depending on their specific requirements for code generation and other tooling.

That's where we disagree. The ability to provide tooling (and not necessarily code-generation) is what makes the specification even relevant in the first place. If that means it's not as flexible, so be it. Yes, the API designer should decide to use whichever tool fits their needs, including the spec itself.

webron avatar Feb 08 '16 16:02 webron