Humans like examples
People are awesome at making general conclusions based on examples.
[
{"href": "/tasks/78534", "status": "TODO"},
{"href": "/tasks/55541", "status": "DOING"}
]
Many of us would look at the example above and see general patterns which are not just based on what is part of the actual example but heavily influenced by individual experiences. For someone who is familiar with JSON APIs of a certain style there may be many things to expect about data that is similar to the example.
Maybe you would expect any JSON array like the one above to have an href property with a URI value. Maybe you would conclude that every URI value should start with /tasks/. Many of us would not expect a status property value of lower case and some would expect status to only have a few predefined values (e.g "TODO", "DOING", "DONE"…).
I is often harder for humans to understand data by only looking at a definition like a JSON Schema and creating a JSON Schema from scratch can be quite cumbersome. The example above is simple but may require quite a lot of JSON to be defined in a JSON Schema.
{
"items": {
"$ref": "/$defs/tasksItem"
},
"$defs": {
"tasksItem": {
"properties": {
"href": {
"maxLength": 100,
"type": "string",
"format": "uri"
},
"status": {
"type": "string",
"enum": [
"DOING",
"TODO"
]
}
},
"required": [
"href",
"status"
],
"type": "object",
"additionalProperties": false
}
},
"type": "array"
}
JSON Schema from example data without effort
I just released a schema generator which can be customized to understand example data as a person with knowledge about a certain API design style would. This makes it possible to generate schemas with less manual work when designing APIs and in other cases where we use JSON Schemas.
The JSON Schema generator in its first release is capable of generating JSON Schemas including:
- type (array, boolean, null, number, integer, object, string)
- required
- properties
- minLength
- maxLength
- minimum
- maximum
- minItems
- maxItems
- minProperties
- maxProperties
- const
- enum
- uniqueItems
- $ref
- $defs
The min<X> and max<X> keywords (e.g minItems and maxItems) are all configurable as default threshold values. A configuration of maxLength: [10, 100, 1000] would for example give a JSON Schema with maxLength: 10 for an example string of any length less or equal to 10 and it would give maxLength: 1017 for an example string of 1017 characters)
The simplest way to try the JSON Schema generator is online and it is also available as Java maven module: Zuunr JSON
If you find this useful or if you have any questions – please let me know!
//Niklas
niklas.eldberger@zuunr.com

Leave a comment