json-schema-validator icon indicating copy to clipboard operation
json-schema-validator copied to clipboard

validate OpenAPI with referenced schemas

Open Jitterer opened this issue 3 years ago • 0 comments

Hi, I'm trying to figure out how I can validate a json against a JSON Schema, which is included in an OpenAPI definition.

Let me explain with an example. I have to following OpenAPI definition (it got much reduced and therefore, in this example, it's not a valid OpenAPI definition):

{
    "openapi": "3.0.0",
    "info": {
        "description": "...",
        "version": "1.0",
        "title": "my API"
    },
    "components": {
        "schemas": {
            "myJson": {
                "title": "myjson",
                "type": "object",
                "required": [
                    "key1"
                ],
                "properties": {
                    "key1": {
                        "required": [
                            "string1"
                        ],
                        "properties": {
                            "string1": {
                                "$ref": "#/components/schemas/string1"
                            },
                            "string2": {
                                "$ref": "#/components/schemas/string2"
                            }
                        }
                    }
                }
            },
            "string1": {
                "type": "string",
                "example": "blub"
            },
            "string2": {
                "type": "string",
                "example": "blub2"
            }
        }
    }
}

and I want to validate against the following JSON:

{
    "key1" : {
        "string2" : "ok"
    }
}

I initialize the json validator as followed:

factory = JsonSchemaFactory.builder(JsonSchemaFactory.getInstance(sv))
	.objectMapper(mapper)
	.build();
JsonSchema schema = factory.getSchema(schemaNode);
JsonNode node = schema.getRefSchemaNode("#/components/schemas/myJson");
Set<ValidationMessage> errors = schema.validate(inputNode);

So as you can see, I want/have to directly assign to "#/components/schemas/myJson" which is my JSON Schema. This does work as long as I'm not working with $ref, which are declared as parent of #/components/schemas/myJson. Because I'm going to a child node components/schemas/myJson with getRefSchemaNode I assume, that this is the reason the validator isn't able to resolve "$ref": "#/components/schemas/string1" and so on and quits with exactly this error message: #/properties/key1/properties/string2/$ref: Reference #/components/schemas/string2 cannot be resolved

Is there any way how I can solve it? Thank you in advance BR

Jitterer avatar Jun 02 '22 09:06 Jitterer