Define array of different objects with max count 5 in swagger - documentation

I have completed a Node.js app using LINE APIs.I have the following request object. How can I define the array of different objects, here the messagesfield which contains different object structure for different message types. I hope swagger permits this very common scenario.
Request Body:
{
"to": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"messages":[
{
"type":"text",
"text":"Hello, world1"
},
{
"type": "audio",
"originalContentUrl": "https://example.com/original.m4a",
"duration": 240000
}
{
"type": "location",
"title": "my location",
"address": "〒150-0002 東京都渋谷区渋谷2丁目21−1",
"latitude": 35.65910807942215,
"longitude": 139.70372892916203
}
]
}
My swagger definition for messages array.
"Messages Object": {
"type": "array",
"items": {
"allOf": [
{
"$ref": "#/definitions/multicast Message Error Response"
},
{
"$ref": "#/definitions/multicast Message Error Response"
}
]
}
}
And this is the rendered messages array. It has only one entry. I want to include many different entries
"messages": [
{
"code": 500,
"httpCode": 400,
"name": "string",
"message": "string"
}
]

Related

Enum inside the Array is not validting in json-schema

I am validating the json with json_schema.
Allowed values for ghrBillingCode should be only "I9NOT"
expected result should be error as 2nd and 3rd node is not I9NOT but it is validating json as correct.
What is wrong in json-schema i am using
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"items": [
{
"type": "object",
"properties": {
"invoiceLineInfo": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"ghrBillingCode": {
"type": "string",
"enum": [
"I9NOT"
]
},
"quantity": {
"type": "integer"
}
}
}
]
},
"invoiceNumber": {
"type": "string"
}
}
}
]
}
json:
[
{
"invoiceLineInfo":[
{
"ghrBillingCode":"I9NOT",
"quantity":1
},
{
"ghrBillingCode":"I9NOTRU",
"quantity":2
},
{
"ghrBillingCode":"I9PSUP",
"quantity":1
}
],
"invoiceNumber":"202203010100301"
}
]
In your schema, you have extra brackets [] around the items array type. This means that the enum is checked for the first array element only and your example validates because the first item happens to be "I9NOT".
From your sample document, it seems like you expect the enum to apply to all array elements. To achieve this, simply drop the [] from the items value.
For the array / items syntax, have a look here:
https://json-schema.org/understanding-json-schema/reference/array.html#items

reference multiple types in json schema array

I am trying to define an array property of an object in a json schema v7, but validation isn't working. How can I correctly reference multiple type definitions to be used in an array? Here an array for Directory can contain more directories or routes:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "RootDirectory",
"title": "Directory",
"description": "Build a directory for javascript app routing.",
"type": "object",
"definitions": {
"Route": {
"type": "object",
"description": "A simple endpoint declaration.",
"additionalProperties": false,
"properties": {
"path": {
"type": "string",
"description": "An endpoint without forward slashes.",
"examples": ["welcome"],
"minLength": 1
},
"variableSuffix": {
"description": "A string that is appended to the path variable name during build.",
"type": "string"
}
},
"required": ["path"]
},
"Directory": {
"type": "object",
"description": "Contains child directories or routes for recursive tree building.",
"additionalProperties": false,
"properties": {
"path": {
"type": "string",
"description": "An endpoint without forward slashes.",
"examples": ["welcome"],
"minLength": 1
},
"variableSuffix": {
"description": "A string that is appended to the path variable name during build.",
"type": "string"
},
"childNodes": {
"minItems": 1,
"type": "array",
"description": "An array of routes, linkedRoutes, subDirectories, or linkedSubDirectories.",
"contains": {
"type": "object",
"oneOf": [
{"$ref": "#/definitions/Route"},
{"$ref": "#/definitions/Directory"}
]
}
}
},
"required": ["path", "childNodes"]
},
},
"properties": {
"directories":{
"type": "array",
"contains": {
"type": "object",
"allOf": [{"$ref": "#/definitions/Directory"}]
},
"minItems": 1
},
"rootPath": {
"type": "string",
"default": ""
}
},
"required": ["directories"]
}
for instance, this is valid and shouldn't be since it contains an object with invalid properties:
{
"rootPath": "api",
"directories": [
{
"path": "a",
"childNodes": [
{
"path": "a",
"variableSuffix": "s"
},
{
"invalidProperty" : "a"
}
]
}
]
}
Is the problem that the property /directories/0/childNodes/1/invalidProperty should not be permitted? The schema does not state that all the array items in childNodes must be valid -- it only specifies that childNodes must contain a valid item, and item #0 does validate, therefore the overall schema validates.
To assert that all the items in childNodes must be valid, change contains at /definitions/Directory/properties/childNodes/contains to items -- the items keyword specifies a schema that must be validated against all array items, whereas contains only asserts that at least one array item must validate.

jsonSchema attribute conditionally required based on uri parameter

Consider an API with an endpoint in which you pass a parameter foo as part of the URL-path, and pass some parameters as json in the body of a POST request.
This uri parameter foo must have one of the values fooBar and fooBaz. Otherwise the request gest a 404.
If the value of foo is fooBar then the body attribute bar is required.
If the value of foo is fooBaz then the body attribute baz is required.
How do I specify a jsonSchema for such an endpoint?
An example for such a request would be:
POST /path/to/endpoint/fooBar HTTP/1.1
Accept: application/json
Content-Type: application/json
Content-Length: 20
{"bar":"something"}
So far I came up with the following based on this and that but I have no idea if this is correct.
{
"$schema": "http://json-schema.org/draft-03/schema#",
"id": "http://json-schema.org/draft-03/schema#",
"definitions": {
"foo": { "enum": ["fooBar", "fooBaz"] }
},
"type": "object",
"properties": {
"foo": { "$ref": "#/definitions/foo" },
"bar": { "type": "string" },
"baz": { "type": "string" }
},
"links": [{
"rel": "self",
"href": "/path/to/endpoint/{foo}",
"hrefSchema": {
"properties": {
"foo": {"$ref": "#/definitions/foo"}
}
}
}],
"anyOf": [
{
"properties": {
"foo": { "enum": ["fooBar"] }
},
"required": ["bar"]
},
{
"properties": {
"foo": { "enum": ["fooBaz"] }
},
"required": ["baz"]
},
]
}
JSON Schema validation is not aware of the URI that the data being validated came from (if any). You can use JSON Hyper-Schema to tell your users how to send that data in the way you expect, but you will still need to do an additional check on the server-side to validate that the request was sent properly.
Before I get into the solution, I want to point out a couple things. Your $schema is set to "draft-03". If you really need "draft-03", this solution won't work. anyOf, allOf and the array form of required were added in "draft-04". hrefSchema was added in "draft-06". Since "draft-06" is brand new and is not well supported yet and you don't need hrefSchema anyway, I'm going to assume "draft-04" ("draft-05" was effectively skipped).
The next thing to mention is that you are using id wrong. It should be the identifier for your schema. You usually don't need this, but if you do, it should be the full URI identifying your schema. That is how my solution uses it.
Last thing before I get into the solution. If you are using the link keyword, you are using JSON Hyper-Schema and your $schema should reflect that. It should have "hyper-schema" instead of "schema" at the end of the URI.
Now the solution. I broke it into two parts, the schema that you put through the validator and the hyper-schema that tells users how to make the request. You've got the first one right. I only fixed the $schema and id.
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "http://example.com/schema/my-foo-schema",
"type": "object",
"properties": {
"foo": { "enum": ["fooBar", "fooBaz"] },
"bar": { "type": "string" },
"baz": { "type": "string" }
},
"anyOf": [
{
"properties": {
"foo": { "enum": ["fooBar"] }
},
"required": ["bar"]
},
{
"properties": {
"foo": { "enum": ["fooBaz"] }
},
"required": ["baz"]
}
]
}
Next is the hyper-schema. You can't reference anything external (href, instance data) in a request schema, but you can write your schema so that it matches your href. The duplication is unfortunate, but that's the way you have to do it.
{
"$schema": "http://json-schema.org/draft-04/hyper-schema#",
"links": [
{
"rel": "http://example.com/rel/my-foo-relation",
"href": "/path/to/endpoint/fooBar",
"method": "POST",
"schema": {
"allOf": [{ "$ref": "http://example.com/schema/my-foo-schema" }],
"properties": {
"foo": { "enum": ["fooBar"] }
}
}
},
{
"rel": "http://example.com/rel/my-foo-relation",
"href": "/path/to/endpoint/fooBaz",
"method": "POST",
"schema": {
"allOf": [{ "$ref": "http://example.com/schema/my-foo-schema" }],
"properties": {
"foo": { "enum": ["fooBaz"] }
}
}
},
{
"rel": "self",
"href": "/path/to/endpoint"
}
]
}
Usually when I come across something that is difficult to model with hyper-schema, it means that I am doing something overly complicated with my API and I need to refactor. I suggest taking a few minutes to think about alternative designs where this switching on an enum isn't necessary.

How do I indicate which "oneOf" API response will use?

I have an API where the basic response of one key will have an array of identifiers. A user may pass an extra parameter so the array will turn to an array of objects from an array of strings (for actual details rather than having to make a separate call).
"children": {
"type": "array",
"items": {
"oneOf": [{
"type": "string",
"description": "Identifier of child"
}, {
"type": "object",
"description": "Contains details about the child"
}]
}
},
Is there a way to indicate that the first type comes by a default and the second via a requested param?
It's not entirely clear to me what you are trying to accomplish with the distinction. Really that sounds like documentation; maybe elaborate in the descriptions of each oneOf subschema.
You could add an additional boolean field at the top level (sibling of children) to indicate whether detailed responses are returned and provide a default value for that field. The next step is to couple the value of the boolean to the type of the array items, which I've done using oneOf.
I'm suggesting something along the lines of:
{
"children": {
"type": "array",
"items": {
"oneOf": [
{
"type": "string",
"description": "Identifier of child",
"pattern": "^([A-Z0-9]-?){4}$"
},
{
"type": "object",
"description": "Contains details about the child",
"properties": {
"age": {
"type": "number"
}
}
}
]
}
},
"detailed": {
"type": "boolean",
"description": "If true, children array contains extra details.",
"default": false
},
"oneOf": [
{
"detailed": {
"enum": [
true
]
},
"children": {
"type": "array",
"items": {
"type": "object"
}
}
},
{
"detailed": {
"enum": [
false
]
},
"children": {
"type": "array",
"items": {
"type": "string"
}
}
}
]
}
The second oneOf places a further requirement on the response object that when "detailed": true the type of items of the "children" array must be "object". This refines the first oneOf restriction that describes the schema of objects in the "children" array.

Is it possible to inline JSON schemas into a JSON document? [duplicate]

For example a schema for a file system, directory contains a list of files. The schema consists of the specification of file, next a sub type "image" and another one "text".
At the bottom there is the main directory schema. Directory has a property content which is an array of items that should be sub types of file.
Basically what I am looking for is a way to tell the validator to look up the value of a "$ref" from a property in the json object being validated.
Example json:
{
"name":"A directory",
"content":[
{
"fileType":"http://x.y.z/fs-schema.json#definitions/image",
"name":"an-image.png",
"width":1024,
"height":800
}
{
"fileType":"http://x.y.z/fs-schema.json#definitions/text",
"name":"readme.txt",
"lineCount":101
}
{
"fileType":"http://x.y.z/extended-fs-schema-video.json",
"name":"demo.mp4",
"hd":true
}
]
}
The "pseudo" Schema note that "image" and "text" definitions are included in the same schema but they might be defined elsewhere
{
"id": "http://x.y.z/fs-schema.json",
"definitions": {
"file": {
"type": "object",
"properties": {
"name": { "type": "string" },
"fileType": {
"type": "string",
"format": "uri"
}
}
},
"image": {
"allOf": [
{ "$ref": "#definitions/file" },
{
"properties": {
"width": { "type": "integer" },
"height": { "type": "integer"}
}
}
]
},
"text": {
"allOf": [
{ "$ref": "#definitions/file" },
{ "properties": { "lineCount": { "type": "integer"}}}
]
}
},
"type": "object",
"properties": {
"name": { "type": "string"},
"content": {
"type": "array",
"items": {
"allOf": [
{ "$ref": "#definitions/file" },
{ *"$refFromProperty"*: "fileType" } // the magic thing
]
}
}
}
}
The validation parts of JSON Schema alone cannot do this - it represents a fixed structure. What you want requires resolving/referencing schemas at validation-time.
However, you can express this using JSON Hyper-Schema, and a rel="describedby" link:
{
"title": "Directory entry",
"type": "object",
"properties": {
"fileType": {"type": "string", "format": "uri"}
},
"links": [{
"rel": "describedby",
"href": "{+fileType}"
}]
}
So here, it takes the value from "fileType" and uses it to calculate a link with relation "describedby" - which means "the schema at this location also describes the current data".
The problem is that most validators do not take any notice of any links (including "describedby" ones). You need to find a "hyper-validator" that does.
UPDATE: the tv4 library has added this as a feature
I think cloudfeet answer is a valid solution. You could also use the same approach described here.
You would have a file object type which could be "anyOf" all the subtypes you want to define. You would use an enum in order to be able to reference and validate against each of the subtypes.
If the sub-types schemas are in the same Json-Schema file you don't need to reference the uri explicitly with the "$ref". A correct draft4 validator will find the enum value and will try to validate against that "subschema" in the Json-Schema tree.
In draft5 (in progress) a "switch" statement has been proposed, which will allow to express alternatives in a more explicit way.