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

json-schema-org/json-schema-spec#98 updated.

I'm curious about the type usage, though- any patterns there?

They seem mainly to be type: object where the type property hasn't been defined in the referenced definition. I'm guessing they may be remnants of cut-and-pasting where a definition has been extracted for re-use? The larger number across the 50K definitions might not bear that out though.

MikeRalphson avatar Apr 04 '17 16:04 MikeRalphson

Having read all these comments, and being faced with a real-world desire to share definitions but make the description meaningful at the point of reference, I find myself aligning with @nickreevesuk's observation that treating OpenAPI as a superset of JSONSchema solves the immediate needs of the OpenAPI community without limiting existing tooling, nor future adherence to JSONSchema should it finally acquire a recognized method of mixing in / overriding shared references.

I appreciate the respective OpenAPI / JSONSchema teams wanting to 'get this right', but providing a stepping stone would help the client community now. At the end of the day, I just want to use Swagger as a single source of truth for API definition and documentation - as it stands, the current $ref is failing that charge. The community (myself included) appears to gravitate naturally to adding a description field to the referencing object, whether as override or mixin... I say treat that as the signal it is.

slhenty avatar May 11 '17 20:05 slhenty

I just think it's a tough one. If we go against JSON schema the expect that all JSON schema tooling will not work, and therefore we'd be better off building our own syntax, since the benefit of tooling reuse is zero.

I personally think the $ref stand-alone constraint in JSON schema is garbage, at least for our purposes. Makes for ugly definitions and causes too many tears.

fehguy avatar May 11 '17 20:05 fehguy

Here are all of the proposed solutions to date, including just allowing "definitions" and "title" alongside "$ref": https://github.com/json-schema-org/json-schema-spec/labels/additionalProperties (not all of these are strictly about additionalProperties, that's just the biggest complaint so I used it for the label)

Most people involve recognize the problem, the deadlock is on choosing the solution. I am pushing hard to resolve this in the next draft, as I view it as the "elephant in the room" of JSON Schema and one of the biggest barriers to further adoption.

handrews avatar May 11 '17 20:05 handrews

Anyway, please feel free to weigh in on the various proposals. Community support matters for these things.

handrews avatar May 11 '17 20:05 handrews

@handrews I would support putting this issue as 1st priority for draft-7. It's a clear issue, and something people want. I confess I have a LOT of catching up and other JSON Schema related work to do though... and I'll be at less than 100% strength for a while! ;)

But seirously, if this isn't on the draft-7 milestone, it should be. I'll avoid further thoughts as this is OAI issue and not in JScheam repo.

Relequestual avatar May 12 '17 15:05 Relequestual

I'm afraid to say I'm new to OAI having found my way here due to a difficulty I'm having with swagger. However, could I also suggest that you add "xml" to the list of items possibly supported alongside a $ref. The current approach means that XML overrides can only be applied to basic properties. As far as I can see, if a property is defined using a $ref, it is impossible for me to override its XML name. e.g. the example below would rename id to Id but not content to Content in the XML world.

"Document": {
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "xml": {
        "name": "Id"
      }
    },
    "content": {
      "$ref": "#/definitions/Content",
      "xml": {
        "name": "Content",
        "attribute": false
      }
    }
  }
 }

There is a similar issue with naming the elements within an array... if the "items" contains a $ref I can't change the name of the XML element that wraps each item in the array.

pierslawson avatar Jun 12 '17 17:06 pierslawson

Anyway, please feel free to weigh in on the various proposals. Community support matters for these things.

This is a tough one. On one hand, I have only ever had a need to overwrite the description column to date. Based on the feedback from @MikeRalphson, it looks like this is the most common use case. However, I can see why a schema creator may also want to overwrite example, required or readOnly... and once schema creators become used to the idea of overwriting descriptions of imported $refs, they will probably want that functionality for all the elements.

The key issue for me is ease-of-use of the two solutions, which is putting the overwrite value beside the ref (the fictional example from the top) vs using a specific overwrite object such as with.

Ultimately, I believe we should consider

  1. Ease of use for schema creators
  2. Ease of use for tool creators

For schema creators, the fictional contract design seems easier because it's intuitive, so long as all element can be overwritten. For example, if description can be overwritten but example cannot, that would seem counter-intuitive. On the other hand, adding an extra with element doesn't seem terribly burdensome to for schema creators, and the fact that it's more explicit may make schemas easier to maintain in the long run.

For tool creators, with seems much easier. It's an explicit overwrite element in the parsing tree, with a defined functionality. Simply overwriting in-line, like our fictional contract, requires a set of rules and exceptions to be programmed into every schema reader.

Given the pros and cons of both options, I would be OK with either, but would lean towards using the with element, or some equivalent. Hope that helps.

tadhgpearson avatar Jun 13 '17 13:06 tadhgpearson

@tadhgpearson do they have to be considered as overrides? A description alongside a $ref could be seen as an override of the referenced type's description or it could be viewed as a description of the property itself.

In @JimSangwine original example, I think the descriptions he provides are better considered as a description of the property rather than a replacement for the address type's description (i.e. in addition to the address's own description). For example, if an address has a description "5 lines of free form text with a UK postcode", that is still valid, alongside the additional "The premises at which electricity is provided" that is describing this particular usage of the type.

In my case of having a problem with xml, the information held within xml is definitely referring to the property, not the type of the property (i.e. not the $ref)... in which case it certainly isn't meant to be an override of any xml information within the referenced type.

Does this enhancing the property (rather than overriding the type) effect whether you think introducing with is best or not?

Another thought...

It seems to me that the "path of least surprise" would push more towards the description having a common location regardless of whether a property happens to have a type or a $ref. By which I mean, given this example:

{
    addresses: [
        "homeAddress": {
            "type": "string",
            "description": "The premises at which electricity is provided."
        }
    ]
}

If I wanted to change it from type based to $ref based, I would probably assume that I would only have to change one line:

{
    addresses: [
        "homeAddress": {
            "$ref": "#/definitions/Address",
            "description": "The premises at which electricity is provided."
        }
    ]
}

Finding I have to introduce a whole new node (with) and move values into it would be a surprise to me at least ;-)

pierslawson avatar Jun 13 '17 16:06 pierslawson

As someone who wants a clear, consistent behavior for my specification, I think that having a rule that appends 2 descriptions, like you described, very weird. In this case, a set of rules would be determining how to separately defined fields, potentially far from each other in the specification file, are merged. I don't think that's an obvious behavior, especially in the context of JSON Schema & Swagger, where each field tends to be explicitly defined.

Regarding the location of the fields, I agree with you @pierslawson - with nothing specified today, as we can see from @MikeRalphson's example, specification creators do put the description in the same node as the $ref. There are so many examples of it that I think we can consider it to be intuitive or unsurprising behavior.

The question I would ask from here is, if the spec was changed to define a with sub-node that allows specification creators to overwrite properties from the $referred object, would that still feel intuitive? Or would they constantly be looking at the manual, trying to figure out why it's not working? To me, I think the with specification is actually quite good: I don't find it burdensome to remember, it forces me to bundle the overwriting elements together, and gives me a keyword to find where overwrites occur. However, that's just my own little opinion!

tadhgpearson avatar Jun 13 '17 18:06 tadhgpearson

@tadhgpearson I wouldn't necessarily expect the descriptions to be appended... I'd leave it down to the UI to decide how they should be displayed as it can access them both. It appears to me that swagger ui could, for example, just display the property level description where it currently displays the description of a primitive property and continue to show the referenced type's description within its model section.

I guess my thoughts come from not thinking of this as "overwriting" the referenced type's properties... rather it is documenting this use of the referenced type. If it was "overwriting" then either it is indicating this is a "sub class" of the referenced type (which doesn't feel right as we aren't intending to change its inherent makeup) or it is changing the global definition of the referenced type (which doesn't feel right either as each $ref to the referenced type would change that global definition, in turn leaving only one as the winner).

pierslawson avatar Jun 14 '17 14:06 pierslawson

My worry about the proposal to limit the additional elements allowed alongside a $ref (as mentioned above by @handrews) is that won't help me with my xml issue and somebody is bound to want to add more items to the list... such as readonly etc. that are extensions to the underlying JSON Schema.

Does anyone know the reasoning behind the restriction being there in the first place?

pierslawson avatar Jun 14 '17 14:06 pierslawson

I believe the restriction was initially to keep the JSON Schema specification simple.

It's actually pretty complex in terms of rule making to determine what behaviour should be expected when merging elements under various conditions. I won't go into details as that's been done a few times now already over on the JSON Schema repo issues. BUT, it is something we want to solve. (I believe we've added it to the draft-7 milestone) What would be most useful for now is if you could document exactly and as simply as possible, what your use case is.

Relequestual avatar Jun 14 '17 14:06 Relequestual

Originally, JSON Reference was a separate specification intended for use independent from JSON Schema. This general problem is definitely a top priority for draft-07.

handrews avatar Jun 14 '17 14:06 handrews

Funnily enough I went back to look at when I was last involved with the JSON Schema back in 2010... and my contributions then were around $ref!

I think at the time JSON references were just a concept rather than something somebody had tried to specify in their own specification. Version 04 dropped my wording to simply refer to the 2011 draft specification for JSON Reference. The even later draft specs for JSON Schema seem to have adopted a more stringent usage.

I'm not sure what thinking went into the change between versions 03 and 04... whether it was a well thought through adoption of the JSON Reference draft spec or just an assumption that the JSON Reference spec must capture the same concept that had been in version 03 of the JSON Schema spec. Either way... I think life might have been easier if we had adopted a type: schema alongside string, number etc. Then the reference could have been encapsulated in its own node.

Enough on that... I'll work on a use case.

pierslawson avatar Jun 15 '17 14:06 pierslawson

@Relequestual - quick background: I have an existing API that can provide HTML, JSON and XML representations. I'm migrating it to ASP.Net Core and decided to take advantage of https://github.com/domaindrivendev/Swashbuckle.AspNetCore to create a resource that would expose a swagger.json document. It worked great except when I looked at the sample XML generated by swagger.io.

So here is the full contents of swagger.json for a pretty basic API that mixes up string based properties and object based properties:

{
  "swagger": "2.0",
  "info": {
    "title": "People Service",
    "version": "v1"
  },
  "basePath": "/",
  "paths": {
    "/parents/{id}": {
      "get": {
        "tags": [ "Parents" ],
        "summary": "Retrieves a specific parents.",
        "consumes": [],
        "produces": [ "application/xml", "application/json" ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "Parent retrieved.",
            "schema": { "$ref": "#/definitions/parent" }
          }
        }
      }
    }
  },
  "definitions": {
    "parent": {
      "type": "object",
      "properties": {
        "childStr": {
          "type": "string",
          "xml": {
            "name": "ChildStr"
          }
        },
        "childObj": {
          "$ref": "#/definitions/childObject",
          "xml": {
            "name": "ChildObj"
          }
        },
        "childStrings": {
          "type": "array",
          "items": {
            "type": "string",
            "xml": { "name": "ChildString" }
          },
          "xml": {
            "name": "ChildStrings",
            "wrapped": true
          }
        },
        "childObjects": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/childObject",
            "xml": { "name": "ChildObject" }
          },
          "xml": {
            "name": "ChildObjects",
            "wrapped": true
          }
        }
      },
      "xml": {
        "name": "Parent"
      }
    },
    "childObject": {
      "type": "object",
      "properties": {
        "value": {
          "type": "string",
          "xml": {
            "attribute": true
          }
        }
      }
    }
  }
}

The sample XML produced by swagger.io is currently:

<?xml version="1.0" encoding="UTF-8"?>
<Parent>
	<ChildStr>string</ChildStr>
	<childObj value="string">
	</childObj>
	<ChildStrings>
		<ChildString>string</ChildString>
	</ChildStrings>
	<ChildObjects>
		<ChildObjects value="string">
		</ChildObjects>
	</ChildObjects>
</Parent>

As per the current spec, there are two warnings about two of the xml values being ignored as they are alongside a $ref.

I would like to see the following XML generated (i.e. those xml nodes not being ignored and simply treated the same way as the xml nodes alongside the string based values are treated):

<?xml version="1.0" encoding="UTF-8"?>
<Parent>
	<ChildStr>string</ChildStr>
	<ChildObj value="string">
	</ChildObj>
	<ChildStrings>
		<ChildString>string</ChildString>
	</ChildStrings>
	<ChildObjects>
		<ChildObject value="string">
		</ChildObject>
	</ChildObjects>
</Parent>

In case you can't spot the differences:

  1. childObj is now ChildObj
  2. ChildObjects contains a list of ChildObject not a list of ChildObjects

This is pretty similar use case to the original one highlighted by @JimSangwine

pierslawson avatar Jun 15 '17 15:06 pierslawson

@pierslawson I can't speak to what happened between drafts 03 and 04. No one who was active with JSON Schema at the time is still involved.

For draft-05, the goal with core and validation was improved clarity, so it just pulled in exactly what the separate JSON Reference draft specified. And we did not significantly change that for draft-06. The only real change that resulted from pulling it into the JSON Schema spec (again) is that we specified that it can only be used where a schema is expected (there is also a proposal for draft-07 hyper-schema to allow it where a link description object is expected as well).

Loosening the $ref rules is one of several proposals on the table for draft-07.

handrews avatar Jun 15 '17 15:06 handrews

@pierslawson Is the xml part something designated by swagger? not seen it before in a json schema.

Relequestual avatar Jun 15 '17 15:06 Relequestual

@Relequestual it is part of the Open API Specification https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#xml-object which swagger is built against.

pierslawson avatar Jun 15 '17 16:06 pierslawson

They key issue is that $ref represents a BINARY relationship with two ends the referee and the referent. There are many genuine needs to attach meta data describing the referee not the referent. So if Customer entity has a reference to an Address you need a descriptions such as "this address is the billing address" or "this address is the electricity supply address". These are not overriding the description of the referent (what an address is), but giving information about the specific use in the referee (what this address instance represents). This goes beyond description to many other pieces of meta data describing the use in the referee (whether that reference is mandatory, what version it was introduced at ...) which can legitimately vary between references to the same referent.

Thus any complaints around not being able to allow other sibling properties to $ref because they would conflict with ones on the referent are specious. You simply need to define the semantics of these properties as applying to the specific use in the referee, leaving the referent unchanged. If you want to add properties relating to the referent those would be done in the referent at its point of definition.

nickreevesuk avatar Jun 19 '17 09:06 nickreevesuk