Validating JSON messages against Swagger definition in Java

江枫思渺然 提交于 2019-12-20 03:26:15

问题


I created a REST API using a Swagger definition, now I need to validate incoming messages using that swagger schema. I found several solutions however all of them rely on some specific use case. The closest to what I need is this and true to it's description it works well with provided json schema, however when I deliver much more complex swagger definition, it just marks everything as valid. My question is. Is there any better, more complete or competent solution, library perhaps, that would natively validate given JSON messages against Swagger definition? I need this because I'm implementing WSO2 API REST solution and this would greatly help.


回答1:


There is the swagger-request-validator having several adapters for various frameworks, e.g.: Spring Web MVC

It is capable of validating requests and / or responses against Swagger / OpenAPI 2 or OpenAPI 3 schemes.

It doesn't simply validate the defined JSON body. It validates the rest of the request, too, like path (variables), headers, etc.

The validator is capable of i18n.

Up until now the most complete validation against Swagger and OpenAPI in Java.




回答2:


Have a look at my answer here with a solution for this:

Validating json payload against swagger file - json-schema-validator

It's based on using the library: https://github.com/bjansen/swagger-schema-validator. It allows to check your json against the definitions contained in the swagger schema.

try (InputStream inputStream = schemaLocation.getInputStream()) {
            SwaggerValidator validator = SwaggerValidator.forJsonSchema(new InputStreamReader(inputStream));
            ProcessingReport report = validator.validate(message, "/definitions/Pet");
            return report.isSuccess();
        } catch (IOException e) {
            logger.error("IOException", e);
            return false;
        } catch (ProcessingException e) {
            e.printStackTrace();
            return false;
        }


来源:https://stackoverflow.com/questions/43760008/validating-json-messages-against-swagger-definition-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!