Define exact custom Properties in openAPI 3.1 - json

I have a JSON schema I am trying to describe, a JSON object which has a additionalProperties node which contains an array of key value pairs.
{
"additionalProperties": [
{
"key": "optionA",
"value": "1"
},
{
"key": "optionB",
"value": "0"
},
{
"key": "optionC",
"value": "1"
}
],
}
Whilst I can use quite a generic schema for this like this
additionalProperties:
properties:
key:
type: string
value:
type: string
required:
- key
- value
type: object
I ideally wish to explain what the various keys that can appear and what they mean. I.e. optionA means this and OptionB means that. Is there a way I can describe the exact options which will appear in the array?

The description field is used when you want to provide additional information or context to the reader that isn't necessarily explained by schema alone.
additionalProperties:
description: Your explanation goes here. Note that you can use markdown formatting if desired.
properties:
key:
type: string
value:
type: string
required:
- key
- value
type: object
You can also more accurately describe your options in the schema if they are all known values using oneOf, allOf, or anyOf. (Documentation here)
additionalProperties:
properties:
anyOf:
- $ref: '#/components/schemas/optionA'
- $ref: '#/components/schemas/optionB'
- $ref: '#/components/schemas/optionC'

Related

Json datatype constant in swagger

I have a swagger spec like this:
'''
loading_method:
type: "object"
title: "Loading Method"
oneOf:
- title: "Standard Inserts"
additionalProperties: false
required:
- "method"
properties:
method:
type: "string"
const: "Standard"
- title: "ABC XYZ"
additionalProperties: false
required:
- "method"
properties:
method:
type: "string"
const: "ABC XYZ"
order: 0
...
Now when I am passing my json in the request payload,
'loading_method': {'method': 'ABC XYZ'}, the JSON Validator keeps on failing with the below error:
Errors: json schema validation failed when comparing the data to the json schema. \\nErrors: $.loading_method.method: must be a constant value Standard, $.loading_method.method: must be a constant value ABC XYZ
Any idea how should I pass the json payload. I cannot control the swagger schema as it is 3rd party. It seems it is validating against both of the methods.

Validating JSON payload with AVRO schema particularly for "fixed" datatype

JSON Payload:
{
"BILLING_EVENT_RULE_MET_DT": "lsks",
"PlanType":"hhh"
}
AVRO Schema:
{
"name": "Subscription",
"type":"record",
"doc": "Subscription details",
"fields":
[
{ "name": "BILLING_EVENT_RULE_MET_DT", "type":[ "null","string"],"default": null },
{"name": "PlanType",
"type":
{
"name":"PlanType",
"type": "fixed",
"size": 4
}
}
]
}
ERROR:
The value [hhh] for field [PlanType] should be [FixedType <size: 4, name: PlanType, namespace: None, aliases: None>].
While validating its giving me the following error, what I am supposed to write in the json payload for PlanType field?
Actually this all I am exploring as I want to define the maxlength and minlength for a field in AVRO schema similar to XML schema.
If the field size of "PlanType" is not a constant you cannot use the 'fixed' type.
You can either use 'string' type if the data is string or 'bytes' type if the data type is any bytes sequence.
Note that using 'string' or 'bytes' means it cannot have no characters/ zero bytes.
For enabling null value, you shall use union type (i.e. union of 'null' and 'string' or union of 'null' and 'bytes').
There is not way to have min size or max size as part of avro schema. See avro specification for that.

Schema validation, how to enforce the existance of property at top level based on condition in lower level

I'm trying to write a schema to validate a yaml file after parsing it into JSON.
Supposing that this is my .yml file with 2 top level properties, cars and garage.
cars is optional while garage is required.
However, one of garage's sub-properties is cars. If cars under garage is defined, I want the schema to make sure that cars at the top level is also defined. Otherwise, the schema is not going to be valid
cars:
- BMW
- Mercedes-Benz
- Audi
garage:
location: Miami
cars:
- BMW
- Audi
My Schema:
{
properties: {
cars: {
type: 'array',
items: {
type: 'string'
}
},
garage: {
type: 'object',
properties: {
location: {
type: 'string'
},
cars: {
type: 'array'
}
},
required: ['garage']
}}
So I tried doing an if-else at the top level
{
if: { properties: { garage: { cars: {type: 'array'}}}},
then: {required:['cars']},
properties: {
cars: {
type: 'array',
items: {
type: 'string'
}
},
garage: {
type: 'object',
properties: {
location: {
type: 'string'
},
cars: {
type: 'array'
}
},
required: ['garage']
}}
But it seems that I'm doing it wrong or it doesn't serve that purpose.
Also doing anyOf at the top level to match sub-schemas didn't work for me..
Any help ?
You can specify the referential integrity constraint (together with all the other requirements) using the "JSON Extended Structure Schema" language, JESS.
Here is the complete JESS schema presented as a single JSON document:
[ "&",
["&",
{"::>=": {"garage": {"location": "string", "cars": [ "string" ] } } }
],
{"ifcond": { "has": "cars" },
"then": ["&", { "forall": ".[cars]", "schema": ["string"] } ]
},
{"setof": ".[garage]|.[cars][]", "subsetof": ".[cars][]"}
]
The first "&" introduces the conjunction of the three requirements, the last of which is the referential integrity constraint.
The JESS repository has a schema conformance checker, which I used to verify your sample (expressed as JSON) against the above schema.
The value of if must be a JSON Schema.
If you take the value of if as a JSON Schema on it's own and test the validation result of applying it to the correct location in your JSON instance, it may help you debug this type of issue.
In your if block, you need to put nest cars under properties, just like you've done in your main schema.
You may also want to make both garage and cars required in your if block.]
You cannot however define that you want the values from garage.cars to be included in your cars array.

How to document multiple content types in successful GET response in swagger

Let's say we have an example json swagger spec:
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Some API"
},
"basePath": "/api/v1",
"consumes": [
"application/json"
],
"produces": [
"application/json",
"text/csv"
],
"paths": {
"/some/endpoint": {
"get": {
"parameters": [
{
"in": "body",
"name": "body",
"required": false,
"schema": {
"$ref": "#/definitions/BodyParamsDefinition"
}
}
],
"responses": {
"200": { ?? } ...
There are two content types that can be produced:
application/json
text/csv
Default response for GET /some/endpoint is a csv file, but if the format query param is used like this /some/endpoint?format=json, the response would be in json format.
I have trouble finding how should I finish my specification with proper responses.
When I use this approach: https://swagger.io/docs/specification/describing-responses/ i get a validation error: ...get.responses['200'] should NOT have additional properties
You are almost there, you just need to define a schema for the response. This schema defines the response structure for all content types associated with this status code.
For example, if the operation returns this JSON:
[
{
"petType": "dog",
"name": "Fluffy"
},
{
"petType": "cat",
"name": "Crookshanks"
}
]
and this CSV:
petType,name
dog,Fluffy
cat,Crookshanks
you would use:
# YAML
responses:
200:
description: OK
schema:
type: array
items:
type: object
properties:
petType:
type: string
name:
type: string
More info: Describing Responses
In OpenAPI 3.0, content type definitions were improved and schemas can vary by content type:
openapi: 3.0.0
...
paths:
/some/endpoint:
get:
responses:
'200':
description: OK
content:
# JSON data is an object
application/json:
schema:
type: object
properties:
message:
type: string
# CSV data is a string of text
text/csv:
schema:
type: string
Default response for GET /some/endpoint is a csv file, but if the format query param is used like this /some/endpoint?format=json, the response would be in json format.
There's currently no way to map specific responses to specific operation parameters, but there are several related proposals in the OpenAPI Specification repository:
Accommodate legacy APIs by allowing query parameters in the path
Querystring in Path Specification
Support an operation to have multiple specifications per path
Overloading

JSON Schema - multiple types

I have this schema. It checks comments, and works fine at the moment.
var schema = {
id: '',
type: 'object',
additionalProperties: false,
properties: {
text: {
type: 'string',
minLength: 1,
required: true
},
author: {
type: 'number',
required: true
}
}
};
My comment structure is:
{
text: "Hello world!",
author: 1
}
But now, I need to validate an array of objects like this. So I can get something like:
[
{
text: "Hello world! Im comment #1",
author: 1
},
{
text: "Super awesome comment #2!",
author: 0
}
]
Sometimes I get one comment only so I get one object, and need to use first schema, but sometimes I get an array of comments, and my schema does not fit.
I heard about json schema anyOf, but I dont know how to do it.
Some like:
anyOf
schema-1 (object)
schema-2 (array with objects)
Any help?
Thanks.
The solution is to have a common definition in one place, and then reference that common definition from two different options inside oneOf:
Here, we put the simple object definition inside definitions:
{
"definitions": {
"singleObject": {
... same definition as in your question ...
}
}
}
We then reference this schema, inside oneOf:
{
"oneOf": [
{"$ref": "#/definitions/singleObject"}, // plain object
{
"type": "array", // array of plain objects
"items": {"$ref": "#/definitions/singleObject"}
}
],
"definitions": {
"singleObject": {...}
}
}
You can organise this a few different ways - I personally often end up with the simple-object definition as the root schema, and have the single/array switcher in definitions, so the schema for my documents is actually http://example.com/schema#/definitions/arrayOrSingle.