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

Extra JSON Reference properties ignored - reduces reusability of references

Open JimJafar opened this issue 10 years ago • 89 comments

Hi everyone.

I feel that the ignoring of extra properties when using JSON References goes against the goal of reusability.

Take this example from a fictional Swagger contract:

{
    addresses: [
        "homeAddress": {
            "description": "The premises at which electricity is provided.",
            "$ref": "#/definitions/Address"
        },
        "invoiceAddress": {
            "description": "The billing address - must be where the customer's credit card is registered.",
            "$ref": "#/definitions/Address"
        }
    ]
}

The "description" properties help to distinguish between the two uses of the "Address" Reference. Of course you could argue that better naming of the "homeAddress" and "invoiceAddress" properties could achieve this, but we are not always in control of property names in our data models and sometimes you need a more verbose description.

The Swagger editor (http://editor.swagger.io/#/) is an example of an application that could be improved by removing this limitation.

Is this something that has been raised previously? Please see here for a discussion on the Swagger Google Group: https://groups.google.com/forum/#!topic/swagger-swaggersocket/ewgimdO2cOI

JimJafar avatar Feb 08 '16 08:02 JimJafar

@nickreevesuk That's an easy to understand and compelling use case. We're ON IT.

You could get around this currentley by having two layers of references I believe.

Relequestual avatar Jun 19 '17 10:06 Relequestual

You could get around this currentley by having two layers of references I believe.

I don't think so ... each layer of $ref ignores all other properties.

What I've seen sometimes is misusing allOf:

Customer:
  type: object
  properties:
    billingAddress:
      description: "the address to which the bill is sent"
      allOf:
       - $ref: '#/definitions/Address'
    supplyAddress:
      description: The address where the electricity is supplied
      allOf:
       - $ref: '#/definitions/Address'

ePaul avatar Jun 19 '17 14:06 ePaul

mmm. I'm not sure quite what I was thinking =/

Relequestual avatar Jun 19 '17 16:06 Relequestual

I'm working on the .NET Swagger toolchain NSwag and I have the same issue (also see https://github.com/Azure/autorest/issues/2652).

Currently the toolchain produces

    supplyAddress:
      description: The address where the electricity is supplied
      allOf:
       - $ref: '#/definitions/Address'

Why is this a misuse? The description of the parameter is not an override but a description of the property - the description of the Address describes the schema/class itself.

My options are:

  • Use $ref with additional properties: Violates JSON Reference spec - invalid in swagger-editor, etc.
  • Use allOf: Valid Swagger spec but some tools cannot handle this (correctly) (e.g. they treat it as inheritance instead of reference).
  • Add an option in the toolchain to either produce $ref or allOf depending on the tool which is consuming the spec: I really want to avoid this because most users will not understand the option and for most spec consumers it is not that simple to find out how they handle this scenario (i.e. it is hard to decide what the correct option is).

I still think @IvanGoncharov proposal is the best solution. Its important for me to find consensus here so that we can invite all tools to behave the same way and we can link to this decision.

For example, we could define the following rules which everyone should follow:

  • For consumers (e.g. code generators):
    • If a property or parameter object has no direct type and allOf contains only one reference, then treat it like a $ref (not as inheritance, etc.)
    • If a property or parameter object has a $ref and additional properties do not ignore them but use them as if it where defined with an allOf (backward-compatiblity)
  • For producers (e.g. Swagger generators):
    • Only use $ref if the property or parameter object has no additional properties, otherwise use allOf instead of $ref with only one $ref and no type on the parameter or property object

I think it is important to define the rules for this scenario somewhere, so that every tool can be implemented in the same way. As it is currently, a Swagger spec is not really universally usable...

Has this been fixed with Open API 3?

RicoSuter avatar Oct 11 '17 09:10 RicoSuter

@RSuter and all: The forthcoming draft-07 of JSON Schema (hopefully next month) will have a bit more guidance on keywords like title, description, default, examples, readOnly, and secret, which we are calling annotation keywords. This isn't really a new mandatory implementation requirement, and is compatible with earlier drafts (for whatever keywords were present in the earlier drafts- only the first three of those were in draft-04, plus readOnly was in Hyper-Schema at the time).

We are defining how an implementation can and should collect multiple values of these keywords when they apply to the same part of the instance, and making it more clear that applications should interpret the results as needed.

For instance, a system could discard all descriptions except the top-most one (e.g. keeping the one outside of an allOf and ignoring the ones within it). Or a system could append them all into a multi-paragraph description. The JSON Schema spec does not determine this, so OpenAPI could choose a particular behavior on top of this basic value-collection behavior for consistency.

Then, if OpenAPI chooses something like "concatenate all descriptions in depth-first order", or even something more content-specific like "check for a section number and order them accordingly", OpenAPI document authors can write descriptions with those processing rules in mind.

The PR is https://github.com/json-schema-org/json-schema-spec/pull/424 if anyone would like to give feedback.

This is much simpler than defining schema-merging semantics, which continues to be a bitterly divisive topic. Hopefully it will be addressed in draft-08 (either added or definitively rejected, but either way not in a state of limbo anymore). Although I'm not sure who is going to run that draft on the core and validation side as I will be focusing on hyper-schema.

handrews avatar Oct 11 '17 15:10 handrews

I have a slightly different proposal to address this particular problem. And perhaps this should be in the JSON-Schema repo instead. Let me know @handrews

Considering the example shown by @RSuter above:

supplyAddress:
      description: The address where the electricity is supplied
      allOf:
       - $ref: '#/definitions/Address

and building on @nickreevesuk 's description of $ref as a relationship between what I'll call the source and target because I will keep confusing referee and referent :-)

Let's look at an example of a media type that already does transclusion much like we are trying to do. Consider a standard HTML page:

<html>
    <link rel="stylesheet" title="My bedazzling style" href="stylesheet.css" />
</html>

The link tag defines a relationship between the source HTML page and target CSS file to be transcluded. The additional attributes on the link tag further qualify the relationship. They DO NOT change the target CSS. In fact the attributes on the link tag are not related to the structure of the target object. They are native properties of the link itself.

My understanding is that much of the pain we are experiencing is related to us trying to modify the target of the $ref using properties in the source. Do we really need to do that? Could we annotate the object that contains the $ref property with additional metadata to describe the relationship?

e.g.

supplyAddress:
      $ref: '#/definitions/Address
      title: The address where the electricity is supplied

I realize this is not currently valid JSON Schema, and it looks very similar to what has already been proposed and what many people already do, ignoring the fact that it is currently invalid. However, the important distinction is that the property I have added would need to be a defined property of a "reference object". It is not an attempt to merge with the target object. It is an attribute of the relationship.

This approach addresses a major concern of mine that I haven't seen much conversation around. If I am writing tooling that loads an OpenAPI description into memory, when I have 1400 operations that all $ref a shared parameter, do I maintain that reference in the object graph, or do I inline the parameter definition? Obviously just maintaining the reference is ideal. However, if I have to merge a property that is overridden in every operation, I may have little choice but inline the parameter objects. Either that or create some fancy decorator object that wraps the target object.

If the reference object itself can maintain the additional annotations, then there only needs to be a single instance of the target object.

Now, what attributes are appropriate for this kind of reference object I don't know, but we do have some precedent on the subject in RFC5988.

darrelmiller avatar Oct 12 '17 00:10 darrelmiller

@darrelmiller let's keep the discussion here for just a bit, and if it really digs into $ref proposals I'll find the right JSON Schema issue for you to add to (or let you know if you should file a new one).

This approach addresses a major concern of mine that I haven't seen much conversation around. If I am writing tooling that loads an OpenAPI description into memory, when I have 1400 operations that all $ref a shared parameter, do I maintain that reference in the object graph, or do I inline the parameter definition? Obviously just maintaining the reference is ideal. However, if I have to merge a property that is overridden in every operation, I may have little choice but inline the parameter objects. Either that or create some fancy decorator object that wraps the target object.

Yeah, this about sums it up. There's some confusion here, too, as the old separate JSON Reference I-D allowed implementations to replace the reference with the target, that actually doesn't quite work in JSON Schema (due to base URI inhereitance and meta-schema working within the target file / structure rather than inheriting across the $ref).

Let me float a syntax here, in addition to the current syntax, and then explain it in the context of recent JSON Schema work:

$ref:
    href: "#/definitions/Address"
    title: "The address where the electricity is supplied."
    description: "Lots and lots of text here ..."

The idea here is that you would still be able to use $ref as you do now, with a string value that is a URI reference, for simple cases. But if you want to get full link functionality, then the value of $ref is an object letting you specify a lot more attributes. This particular syntax is a very, very stripped-down subset of Hyper-Schema's LDO, which will likely get some more target attributes defined that could be used here (might as well argue them in one place...)

To be absolutely clear: none of the URI templating or input description keywords would be allowed in this context. The idea is not to use Hyper-Schema itself, just a compatible subset. While rel is required in Hyper-Schema, it seems unlikely to be useful here, so I would probably assign it the default value of "related" (which is an IANA-registered relation). I suppose anchor could be used, but I can't imagine why it would be off the top of my head.

What I like about this is that it's not possible to confuse this with a schema merge strategy, and it suggests the correct mental model of web linking.

handrews avatar Oct 12 '17 02:10 handrews

If this gets any traction, we can file it as a proposal on JSON Schema. $ref changes are a source of contention, but this at least aligns $ref with an existing well-known concept.

handrews avatar Oct 12 '17 02:10 handrews

@handrews That approach works for me too. I was adding to the existing reference object just to reduce the nesting a bit, but your solution is definitely clearer as to what is going on.

darrelmiller avatar Oct 12 '17 03:10 darrelmiller

@darrelmiller cool! I'm going to think on it for a couple of days, and if it holds up, I'll file it in the JSON Schema repo. You're of course welcome to open an issue yourself if you'd rather. I've kind of exhausted the capacity of everyone else to review things at the moment with the top-to-bottom hyper-schema rewrite :-P

Anyone: feel free to remind me if I don't do something about it within a week.

handrews avatar Oct 12 '17 04:10 handrews

@handrews Did you make any suggestions on this within the JSON Schema repo? (I have nearly 2k github notification emails... forgive me for not knowing or checking ;) )

(I guess that means you should also probably notify me on slack or something if you reply!)

Relequestual avatar Nov 21 '17 09:11 Relequestual

@Relequestual I plan to file it this week or next. Draft-07 is out as of yesterday! I'm tidying up the web site and putting together migration notes and will announce it more broadly. Then this is one of several draft-08 backlog items I need to file that I was avoiding doing b/c I did not want to start a big discussion while wrapping up draft-07.

handrews avatar Nov 21 '17 15:11 handrews

@darrelmiller @Relequestual I've referenced this from a JSON Schema issue. The JSON Schema issue is rather abstract, focusing on how $ref should be processed. I'd like to see how that goes, as well as a separate proposal for deferred evaluation keywords that may solve a lot of re-use problems (warning- that issue is even more abstract, laying out a full JSON Schema processing model and proposing extensions).

With draft-07 we formally organized JSON Schema keywords by behavior into the (in some cases overlapping) classifications of applicability, assertions, and annotations. This has given us a better framework to talk about changes to JSON Schema behavior.

I'm hoping to get these processing model questions resolved early in draft-08 and then move into concrete discussions of what to do about specific ongoing re-use concerns. We'll see how that goes.

handrews avatar Nov 28 '17 21:11 handrews

[Apologies for some duplicate info in various issues as I update with JSON Schema developments- I'm never sure if people, particularly lurkers, are following all the issues or just selected ones]

@darrelmiller it looks like we will probably go with something more like your proposal for adjacent keywords.

Specifically:

  • $ref is being defined as delegation (its results are the results of the target schema)
  • we have clarified how annotations like title, description, default, etc. are returned through schema results alongside of the validation outcome
  • this clarification also provides more guidance on what additional semantics an application can define, such as "a title adjacent to $ref applies to the relation rather than the target."

Basically, we'll define the process so that it's easier to figure out how the information is arranged in the schema, and avoid defining the usage semantics too closely to give downstream systems the ability to define a wide range of reasonable semantics.

As for the link serialization approach, I think it's still reasonable to think of $ref as a hyperlink, but moving to a specific syntax related to hyper-schema LDOs adds complexity without adding much functionality. Let's see how things work with the simpler approach first.

handrews avatar Dec 27 '17 01:12 handrews

That sounds good @handrews, but could you give us a specific example of how this would look in practice?

tadhgpearson avatar Jan 05 '18 15:01 tadhgpearson

@tadhgpearson this isn't finalized yet, but the general idea is that in addition to the boolean validation outcome, JSON Schema implementations should also return annotation data (although disabling annotation collection for optimizing validation-only should probably be allowed). Then, applications (in this context, all OpenAPI-based tools are applications) can make their own choices about how to handle things.

So let's have a schema:

{
    "type": "object",
    "properties": {
        "foo": {
            "title": "Title adjacent to reference",
            "description": "Lots of text",
            "readOnly": true,
            "$ref": "#/definitions/fooDef"
        }
    },
    "definitions": {
        "fooDef": {
            "title": "Title in reference target",
            "description": "Even more text"
        }
    }
}

With an instance of:

{
    "foo": "whatever"
}

The annotation results might look like this (it's still up in the air, for instance I literally made up how $ref appears in the JSON Pointer-ish thing while typing this comment):

{
    "/foo": {
        "title": {
            "/properties/foo/$ref/title": "Title in reference target",
            "/properties/foo/title": "Title adjacent to reference"
        },
        "description": {
            "/properties/foo/$ref/description": "Even more text",
            "/properties/foo/description": "Lots of text"
        },
        "readOnly": true
    }
}

"/foo" is the instance pointer- this is the place in the instance to which the annotations apply.

Under that, the property names are the names of each annotation. All of these are also the keyword names that produced them, but in theory you could do something that doesn't map directly (please allow me to wave my hands on that- it's related to a complicated proposal that's under discussion and may not end up being relevant).

Under each annotation, the format is determined by the annotation.

readOnly just has a boolean, because it's explicitly stated (as of draft-07) that the overall value of readOnly is a logical OR of all applicable values. So there's no need to keep track of which value came from where- just let the application know the final outcome.

On the other hand, the way "title" and "description" are shown here is probably the default behavior. For those, "/properties/foo/... are schema pointers, more or less. Pointing across $ref is a bit weird and I need to figure out if that's the right approach. But however it ends up looking, you will be able to tell where the annotation came from so your application can decide how to use it.

So let's say your application decides that a local title always wins over a referenced title, but descriptions should just be concatenated as if each were a paragraph. There is enough information in the above format that you can tell that "Title adjacent to reference" is the title that wins, and then you can construct "Lots of text\n\nEven more text" from the various descriptions.

This is because there are many ways that an application might want to handle multiple titles / descriptions / defaults / etc: closest to root wins, most specific wins, combine them somehow, throw an error, whatever. Depending on the application and the keyword, any of these could be reasonable.

I would expect a system like OpenAPI to pick strategies for consistency. So then an OpenAPI implementation could use a regular old JSON Schema implementation to gather the annotations, then examine them to resolve any ambiguities however OpenAPI thinks they should be resolved. And then other applications can still use JSON Schema and resolve ambiguities differently.

There will no doubt be further debate about how much to standardize and how much to defer to applications, but that's a lot better than the current situation where there's not even any guidance on what sort of decisions are valid to make, much less any implementation requirements to facilitate making them.

handrews avatar Jan 05 '18 21:01 handrews

@tadhgpearson & everyone:

json-schema-org/json-schema-spec#523 discusses keywords alongside of $ref json-schema-org/json-schema-spec#530 discusses more of the process of annotation collection

Both are targeted for draft-08, hopefully by the end of May.

handrews avatar Mar 12 '18 19:03 handrews

Keywords alongside $ref now has an open PR against. So I can't imagine it won't be included in draft-8.

Relequestual avatar Apr 19 '18 09:04 Relequestual

I found this thread, and for me it should be possible to added description sibling next to a ref$ tag. This is mainly usefull if you reference a simple types and not objects.

If you define a base type like for example:

  IPAddressV4:
    type: string
    format: ipv4
    pattern: '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'

And you use this type in a object, for example

  DualPortServer:
    type: object
    description: Server with two ports     
    required:
      - ipAddress1
    properties:
      managementPort:
        $ref: '#/definitions/IPAddressV4'
        description: LAN management port for configuring the server
      ipAddress1:
        $ref: '#/definitions/IPAddressV4'
        description: Primary (mandatory) transfer ethernet IP address.
      ipAddress2:
        $ref: '#/definitions/IPAddressV4'
        description: Secundary (optinal) transfer ethernet IP address.

Maybe I am not doing this the right way? But if so it would be nice to be able to set a specific description.

sgeeroms avatar Jul 27 '18 11:07 sgeeroms

@sgeeroms please see this comment.

hkosova avatar Jul 27 '18 11:07 hkosova