Logo

dev-resources.site

for different kinds of informations.

Json validation with OpenAPI Schema

Published at
2/9/2021
Categories
openapi4j
openapi
schema
Author
Eduardo Issao Ito
Categories
3 categories in total
openapi4j
open
openapi
open
schema
open
Json validation with OpenAPI Schema

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.

Featured ones: