DEV Community

loading...

Json validation with OpenAPI Schema

adzubla profile image Eduardo Issao Ito ・1 min read

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>
Enter fullscreen mode Exit fullscreen mode

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());
        }
Enter fullscreen mode Exit fullscreen mode

If there is any inconsistency, the ValidationData object will have a list of all errors found.

Discussion (0)

pic
Editor guide