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

烈酒焚心 提交于 2019-12-06 02:07:18

json-schema-validator seems to work with pure JSON Schema only. OpenAPI Specification uses an extended subset of JSON Schema, so the schema format is different. You need a library that can validate specifically against OpenAPI/Swagger definitions, such as Atlassian's swagger-request-validator.

I suggest using this library, which worked for me:

https://github.com/bjansen/swagger-schema-validator

Example:

invalid-pet.json

{
  "id": 0,
  "category": {
    "id": 0,
    "name": "string"
  },
  "named": "doggie",
  "photoUrls": [
    "string"
  ],
  "tags": [
    {
      "id": 0,
      "name": "string"
    }
  ],
  "status": "available"
}

My SchemaParser:

@Component
public class SchemaParser {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public boolean isValid(String message, Resource schemaLocation) {

        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;
        }
    }
}

A test:

    @Test
    void shouldFailValidateWithPetstoreSchema() throws IOException {

        final Resource validPetJson = drl.getResource("http://petstore.swagger.io/v2/swagger.json");

        try (Reader reader = new InputStreamReader(validPetJson.getInputStream(), UTF_8)) {
            final String petJson = FileCopyUtils.copyToString(reader);
            final boolean valid = schemaParser.isValid(petJson, petstoreSchemaResource);
            assertFalse(valid);
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!