How to validate a json file against a Schema that is defined in an OpenAPI definition?
Using the open source library openapi4j
!
Add the dependencies in your pom.xml file:
<dependency>
<groupId>org.openapi4j</groupId>
<artifactId>openapi-parser</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>org.openapi4j</groupId>
<artifactId>openapi-schema-validator</artifactId>
<version>1.0.5</version>
</dependency>
Load the OpenAPI definition (petstore.yaml
) and the json file (pets.json
) to validate against the Pets
schema:
URL specURL = new URL("file:src/main/resources/petstore.yaml");
URL contentURL = new URL("file:src/main/resources/pets.json");
String schemaName = "Pets";
OpenApi3 api = new OpenApi3Parser().parse(specURL, true);
JsonNode contentNode = TreeUtil.load(contentURL);
Schema schema = api.getComponents().getSchema(schemaName);
JsonNode schemaNode = schema.toNode();
SchemaValidator schemaValidator = new SchemaValidator(new ValidationContext<>(api.getContext()), null, schemaNode);
ValidationData<Void> validation = new ValidationData<>();
schemaValidator.validate(contentNode, validation);
if (validation.isValid()) {
System.out.println("ok");
} else {
System.out.println(validation.results());
}
If there is any inconsistency, the ValidationData
object will have a list of all errors found.
Top comments (3)
Thank you for this post - this is helpful. I am attempting something slightly different - I want to be able to validate my YAML specs against the OAS3.0 Spec file. (I am aware there are various tools but I am noticing inconsistencies and would like to be able to figure it out myself). However, if the URL is pointing to the OAS3 spec file, the OpenApi3Parser().parse() call is giving me this exception:
Exception in thread "main" org.openapi4j.core.exception.ResolutionException: Failed to load document from 'file:src/main/resources/object'
Do you know if what I am attempting is possible with openapi4j ?
Regards
In my example, the json and yaml file are in standard Maven folders.
Try to use use the full path:
"file://c:/Users/MyUser/path_to_files/pets.yaml"
The same program can parse both json and yaml files.