DEV Community


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:


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

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

Discussion (0)

Editor guide