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
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.
Articles
12 articles in total
Resumo Kubernetes
read article
Check for newer versions of dependencies in pom.xml
read article
Changing the JVM in spring-boot:build-image
read article
Changing the base Linux image in spring-boot:build-image
read article
Custom Root CA in spring-boot:build-image
read article
Getting http status in curl
read article
DB2 backup/restore schema
read article
Using MTLS
read article
Convert OpenAPI spec to JSON Schema
read article
Json validation with OpenAPI Schema
currently reading
SFTP server in Ubuntu
read article
Using multiple JMS servers with Spring Boot
read article
Featured ones: