reusing an object for multiple JSON schemas - jsonschema

I have two separate JSON schemas (used to validate HTTP request endpoints for a REST API) where they both accept the same exact object, but have different required fields (this is a create vs update request). Is there a way I can reuse a single definition of this object and only change the required fields? I know how to use $ref for reusing an object as a property of another object, but I cannot figure out how to reuse an entire object as the top-level object in a schema. My failed attempt so far:
event.json
{
"id": "event",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"start_date": {
"type": "integer"
},
"end_date": {
"type": "integer"
},
"description": {
"type": "string"
}
},
"additionalProperties": false
}
event-create.json
{
"id": "event-create",
"type": "object",
"$ref": "event",
"additionalProperties": false,
"required": [ "name", "description" ]
}
Obviously that doesn't work. It seems like it tries to insert the entirety of 'event' into the definition of 'event-create', including the ID and such. I tried referincing event#/properties to no avail. I can't seem to do a $ref as the sole value inside a properties property either. Any ideas?

Any members other than "$ref" in a JSON Reference object SHALL be ignored.
- https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03#section-3
This is why your example doesn't work. Anything other than the $ref field is supposed to be ignored.
Support for $ref is limited to fields whose type is a JSON Schema. That is why trying to use it for properties doesn't work. properties is a plain object whose values are JSON Schemas.
The best way to do this is with allOf. In this case allOf can sort-of be thought of as a list of mixin schemas.
{
"id": "event-create",
"type": "object",
"allOf": [{ "$ref": "event" }],
"required": ["name", "description"]
}

I found some syntax that seems to work, but I'm not terribly happy with it:
{
"id": "event-create",
"allOf": [
{ "$ref": "event" },
{ "required": [ "name", "description" ] }
]
}
Seems like an abuse of the allOf operator, particularly for another case where there are no required fields (thus only one element insid the allof). But it works, so I'm going with it unless someone has a better idea.

Related

In JSON schema, define and reference a reusable enum type?

I noticed the following: Reusable enum types in json schema , which talks about defining a reusable enum type in JSON schema.
I would have assumed USING this reusable enum type would be trivial, simply specifying (in this case) the value of "MyEnum" for a "type" value.
I don't know if the results from Oxygen XML are authoritative, but I tried something like the following:
{
"$schema": "https://json-schema.org/draft/2019-09/schema#",
"type": "object",
"properties": {
"content": {"$ref": "#/definitions/content_type"}
},
"additionalProperties": false,
"definitions": {
"costCategory_type": {
"type": "object",
"enum": ["VH", "H", "M", "L"]
},
"allowedDevices_type": {
"type": "object",
"properties": {
"costCategory": {
"type": "costCategory_type"
},
On the line near the bottom of this, where I reference "costCategory_type", Oxygen gives me a syntax error, saying
#/definitions/allowedDevices_type/properties/costCategory/type: unknown type: [costCategory_type]
What am I missing?
Yes, the type keyword can only have values from the list null, boolean, object, array, string, number, integer. You can reference definitions with the $ref keyword:
...
"properties": {
"costCategory": {
"$ref": "#/definitions/costCategory_type",
}
}
(incidentally, your definition won't ever evaluate successfully as-is since you define it as being the "object" type, but the list of values in the enum are all strings.)

Extend $ref object properties

I am using JSON schema to build a form and I have an object in "definitions" which I am referencing using $ref in two different places on the schema. At one of the instances I need to have one more property added to the referenced object, how can I achieve this?
{
"definitions": {
"settingsProperties": {
"$id": "#/definitions/settingsProperties",
"type": "object",
"properties": {
"thickness": {
"$id": "#/properties/defaultLayerSettings/thickness",
"type": "number",
"title": "Thickness:",
}
}
}
},
"properties": {
"layerSettings": {
"$id": "#/properties/layerSettings",
"type": "array",
"title": "Dynamic Layer Settings:",
"items": {
"title": "Dynamic Settings",
"type": "object",
"$ref": "#/definitions/settingsProperties", PLUS startLayer PROPERTY!!!!!!!!!!!!!!
"required": [
"startLayer"
]
}
}
}
Just add "properties": { "startLayer": { ... } } underneath the required keyword.
Note that if you are using any specification version earlier than draft 2019-09 (the current latest version), you will have to nest the $ref keyword inside an allOf. Additionally, the use of fragments (strings that include #) are not permitted in the $id keyword, although some outdated tools are generating schemas with this structure.

How do I subclass a JSON schema

How do I subclass in JSON-Schema?
First I restrict myself to draft-07, because that's all I can find implementations of.
The naive way to do sub-classing is described in
https://json-schema.org/understanding-json-schema/structuring.html#extending
But this works poorly with 'additionalProperties': false?
Why bother with
additionalProperties': false?
Without it - nearly any random garbage input json will be considered valid, since all the
'error' (mistaken json) will just be considered 'additionalProperties'.
Recapping https://json-schema.org/understanding-json-schema/structuring.html#extending
use allOf(baseClass)
then add your own properties
The problem with this - is that it doesn't work with 'additionalProperties' (because of
unclear but appantly unfortunate definitions of additionalProperties that it ONLY applies
to locally defined (in that sub-schema) properties, so one or the other schema will fail validation.
Alternative Approaches:
meta languages/interpretters layered on top of JSONSchema
(such as https://github.com/mokkabonna/json-schema-merge-allof)
This is not a good choice as the scehma can only be used from javascript (or the
language of that meta processor). And not easily interoperable with other tools
https://github.com/java-json-tools/json-schema-validator/wiki/v5%3A-merge
An alternative I will propose as a 'solution' / answer
How do I subclass in JSON-Schema?
You don't, because JSON Schema is not object oriented and schemas are not classes. JSON Schema is designed for validation. A schema is a collection of constraints.
But, let's look at it from an OO perspective anyway.
Composition over inheritance
The first thing to note is that JSON Schema doesn't support an analog to inheritance. You might be familiar with the old OO wisdom, "composition over inheritance". The Go language, chooses not to support inheritance at all, so JSON Schema is in good company with that approach. If you build your system using only composition, you will have no issues with "additionalProperties": false.
Polymorphism
Let's say that thinking in terms of composition is too foreign (it takes time to learn to think differently) or you don't have control over how your types are designed. For whatever reason, you need to model your data using inheritance, you can use the allOf pattern you're familiar with. The allOf pattern isn't quite the same as inheritance, but it's the closest you're going to get.
As you've noted, "additionalProperties": false wreaks havoc in conjunction with the allOf pattern. So, why should you leave this out? The OO answer is polymorphism. Let's say you have a "Person" type and a "Student" type that extends "Person". If you have a Student, you should be able to pass it to a method that accepts a Person. It doesn't matter that Student has a few properties that Person doesn't, when it's being used as a Person, the extra properties are simply ignored. If you use "additionalProperties": false, your types can't be polymorphic.
None of this is the kind of solution you are asking for, but hopefully it gives you a different perspective to consider alternatives to solve your problem in different way that is more idiomatic for JSON Schema.
I struggled with that, especially since I had to use legacy versions of JSON Schema. And I found that the solution is a tiny bit verbose but quite easy to read and understand.
Let's say that you want describe that kind of type:
interface Book {
pageCount: number
}
interface Comic extends Book {
imageCount: number
}
interface Encyclopedia extends Book {
volumeCount: number
}
// This is the schema I want to represent:
type ComicOrEncyclopedia = Comic | Encyclopedia
Here is how I can both handle polymorphism and forbid any extra-prop (while obviously enforcing inherited types in the "child" definitions):
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"bookDefinition": {
"type": "object",
"properties": {
"imageCount": {
"type": "number"
},
"pageCount": {
"type": "number"
},
"volumeCount": {
"type": "number"
}
}
},
"comicDefinition": {
"type": "object",
"allOf": [{ "$ref": "#/definitions/bookDefinition" }],
"properties": {
"imageCount": {},
"pageCount": {},
"volumeCount": {
"not": {}
}
},
"required": ["imageCount", "pageCount"],
"additionalProperties": false
},
"encyclopediaDefinition": {
"type": "object",
"allOf": [{ "$ref": "#/definitions/bookDefinition" }],
"properties": {
"imageCount": {
"not": {}
},
"pageCount": {},
"volumeCount": {}
},
"required": ["pageCount", "volumeCount"],
"additionalProperties": false
}
},
"type": "object",
"oneOf": [
{ "$ref": "#/definitions/comicDefinition" },
{ "$ref": "#/definitions/encyclopediaDefinition" }]
}
This isn't a GREAT answer. But until the definition of JSONSchema is improved (or someone provides a better answer) - this is what I've come up with as workable.
Basically, you define two copies of each type, the first with all the details but no additionalProperties: false flag. Then second, REFERENCING the first, but with the 'additionalProperties: false' set.
The first you can think of as an 'abstract class' and the second as a 'concrete class'.
Then, to 'subclass', you use the https://json-schema.org/understanding-json-schema/structuring.html#extending approach, but referencing the ABSTRACT class, and then add the 'additionalProperties: false'. SADLY, to make this work, you must also REPEAT all the inherited properties (but no need to include their type info - just their names) - due to the sad choice for how JSONSchema draft 7 appears to interpret additionalProperties.
An EXAMPLE - based on https://json-schema.org/understanding-json-schema/structuring.html#extending should help:
https://www.jsonschemavalidator.net/s/3fhU3O1X
(reproduced here in case other site
/link not permanant/reliable)
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://TEST",
"definitions": {
"interface-address": {
"type": "object",
"properties": {
"street_address": {
"type": "string"
},
"city": {
"type": "string"
},
"state": {
"type": "string"
}
},
"required": ["street_address", "city", "state"]
},
"concrete-address": {
"allOf": [
{
"$ref": "#/definitions/interface-address"
}
],
"properties": {
"street_address": {},
"city": {},
"state": {}
},
"additionalProperties": false
},
"in-another-file-subclass-address": {
"allOf": [
{
"$ref": "#/definitions/interface-address"
}
],
"additionalProperties": false,
"properties": {
"street_address": {},
"city": {},
"state": {},
"type": {
"enum": ["residential", "business"]
}
},
"required": ["type"]
},
"test-of-address-schemas": {
"type": "object",
"properties": {
"interface-address-allows-bad-fields": {
"$ref": "#/definitions/interface-address"
},
"use-concrete-address-to-only-admit-legit-addresses-without-extra-crap": {
"$ref": "#/definitions/concrete-address"
},
"still-can-subclass-using-interface-not-concrete": {
"$ref": "#/definitions/in-another-file-subclass-address"
}
}
}
},
"anyOf": [
{
"$ref": "#/definitions/test-of-address-schemas"
}
]
}
and example document:
{
"interface-address-allows-bad-fields":{
"street_address":"s",
"city":"s",
"state":"s",
"allow-bad-fields-this-is-why-we-need-additionalProperties":"s"
},
"use-concrete-address-to-only-admit-legit-addresses-without-extra-crap":{
"street_address":"s",
"city":"s",
"state":"s"
},
"still-can-subclass-using-interface-not-concrete":{
"street_address":"s",
"city":"s",
"state":"s",
"type":"business"
}
}

Are there more examples of readOnly being used at several levels of a schema to clarify the semantics?

I've been using the readOnly keyword in my schemas and I just realized that I was just making up my own semantics. Now I'm cleaning up a bunch of my designs and trying to validate that I was using this annotation as it was intended. The validation spec is what I'm basing this question on but I'd like to be aware of more example usage scenarios.
Let me give three examples. In this first example I mean to say the entire resource is read only. Nothing can be mutated at any level.
{
"type": "object",
"readOnly": true,
"properties": {
"name": {
"type": "string",
},
"members": {
"type": "object",
"properties": {
"member1": { "type" : "string" },
"member2": { "type" : "string" }
}
}
}
}
I don't think that's too controversial. But originally, my own mental model was that readOnly at the top level meant you couldn't replace this resource with a new resource. The server would prevent that. But the internal members were still mutable. So I sprinkled readOnly at the name sub-schema and each member sub-schema. I think removing all of those was correct. (My mental model was maybe loosely based on how I interpret const variables in JavaScript. If my const var is an object, I can't change the value of the variable, but I can mutate its members or even add members to it.)
In the second example I leave readOnly out of the schema completely. So it's not too controversial to take that to mean anything is mutable in the resource.
{
"type": "object",
"properties": {
"name": {
"type": "string",
},
"members": {
"type": "object",
"properties": {
"member1": { "type" : "string" },
"member2": { "type" : "string" }
}
}
}
}
In the third example, I want to mix and match
{
"type": "object",
"properties": {
"name": {
"type": "string",
"readOnly": true
},
"members": {
"type": "object",
"properties": {
"member1": { "type" : "string", "readOnly": true },
"member2": { "type" : "string", "readOnly": true },
"member3": { "type" : "string"},
"member4": { "type" : "string"}
}
}
}
}
In this example the name, member1 and member2 are immutable. member3 and member4 can be modified.
So the question is, is there anything wrong about my interpretation of readOnly?
The spec, as you linked defines the following for readOnly...
If "readOnly" has a value of boolean true, it indicates that the value
of the instance is managed exclusively by the owning authority, and
attempts by an application to modify the value of this property are
expected to be ignored or rejected by that owning authority.
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-02#section-9.4
If you take the JSON defined meaning of value, it's the bit to the right of the key followed by colon. Therefore I would read this as any part of the value.
The OpenAPI specification only really defines readOnly as being applicable to individual properties.

Dredd (gavel) : Begin a Json Schema with an array (bug ?)

I am using Markdown for Generate documentation (aglio), generate mocks (api-mock) and check the integrity constraints (dredd).
With Dredd, no problem for check an object, no problem for PUT or POST, but I have a problem with lists.
My lists are arrays, but when I write this schema :
{
"title": "Videos List",
"type": "array",
"items": {
"type":"object",
"required":false,
"properties": {
"id": {
"type": "string",
"required": true
}
},
"required": true
}
}
I get same error all the time: body: JSON schema is not valid! invalid type: object (expected [object Object]/array) at path "/items"
I've tried, again and again, 3 hours, but I failed.
Please help!
PS : sorry for my English, I'm french.
Yes, your data is correct again that schema.
It might be a specific problem of the validator your are using (you did not mention which). You can try to enclose your data with {}. I guess it is expecting allways a JSON like this:
{
[
{
"id": "ninon-retrouve-rudy",
"title": "Ninon retrouve Rudy edited"
},
{
"id": "ninon-retrouve-rudy-1",
"title": "Ninon retrouve Rudy"
}
]
}
Be aware also that your are using Draft03 of Json-schema. I suggest you to use Draft04 (your validator might be obsolete).