81

I created an API spec from some JSON files and I am trying to test if the files validate against the API spec.

There are some good tools to validate against JSON Schema, but I did not have chance to find a tool to validate against specs created in the Swagger (tool for creating API schema). The only solution I found is generating a client/server in the Swagger-Editor, it is quite cumbersome.

Is there already an existing tool to validate JSON against Swagger Schema?

6
  • 1
    Do you want to validate that your spec is a valid OpenAPI (fka. Swagger) spec or validate that an implementation of this spec would produce JSON which is valid regarding your JSON schemas? Commented Sep 2, 2016 at 16:57
  • 14
    The question is solely about checking if a JSON is valid against the OpenAPI spec. Commented Sep 15, 2016 at 7:15
  • 1
    Have you looked at medium.com/@betz.mark/… ? Commented Nov 25, 2016 at 11:12
  • 3
    @PeterGerhat did you get this solved? I don't see any satisfactory answer. Commented Aug 29, 2017 at 5:42
  • 1
    @PeterGerhat did you got the solution for this problem. I am also in need of answer for this question. Please let me know if you have a solution handy. Commented Nov 5, 2018 at 5:02

5 Answers 5

41

Arnaud in the comments is correct that there are two separate questions here.

Do you want to validate that your spec is a valid OpenAPI (fka. Swagger) spec

You can

  • Copy your spec to the online Swagger editor and it will throw errors. A quick dive through the source doesn't tell me what it's using to create those errors, but it doesn't seem to be contacting a server to do it...
  • Use the official swagger-parser for Java.
  • Use the unofficial swagger-parser for JavaScript (browser or Node).

or validate that an implementation of this spec would produce JSON which is valid regarding your JSON schemas?

In other words, here's some JSON from a request or response body, is it correct?

Swagger relies on another standard called JSON Schema for its schema objects, which are what actually describes the JSON (rather than endpoints or metadata). Swagger uses a subset of JSON Schema (missing: oneOf, patternProperties, among others). To that end, you can use a JSON Schema validator. There are 37 listed here; I'll give a shoutout to this online validator that also supports YAML schemas.

But, when I said Swagger relies on a subset of JSON API, I lied. There are a handful of fixed fields that have special meaning in Swagger that's not part of JSON Schema. One of them is discriminator which is used for polymorphism. I am not aware of a Swagger validator that can process discriminator. There are a fair number of tools for swagger and some claim to do validations, but many are abandonware, meant for old versions, not feature-complete, tied to other technologies, and so on. If there's a mature and well-maintained library that I'm missing, I'd love to know.

Sign up to request clarification or add additional context in comments.

6 Comments

I am having the same situation and this was helpful. With a bit of work, I was able to write my own scripts that can validate my server's response payload with the JSON Schema defined by Swagger. I wrote some Express middlware to do that. Instead of trying to use Swagger to do what I want, I can use the schema object it relies on. Thanks!
For the second one, how would I implement it without using an external schema validator? I just want to validate an instance of a schema against a (swagger) schema. How would I do that? Thanks.
internally it looks like swagger is using the z-schema json validator, so theoretically you would look at that to see what features are available? github.com/zaggino/z-schema
This solution is not worked for me. Intentionally removed path param declaration and tested. It did not complaining that the path param missed. It's just validating the well formed json or not.
Yes, Open API Schema (Swagger) doesn't equal JSON Schema. Swagger Schema has some extended keywords which are not supported by json schema standard. You can check swagger docs: swagger.io/docs/specification/data-models/keywords
|
4

Atlassian's swagger-request-validator is a Java library that can do such validation:

A Java library for validating request/responses against a OpenAPI / Swagger specification. Includes support for Swagger v2 and OpenAPI v3 specifications and adapters for common mock and testing libraries.

The core library is not tied to any specific HTTP library, but they also provide additional modules that integrate with Spring MVC, MockMVC, REST Assured etc.

There is also swagger-schema-validator that can validate a JSON document against a Swagger V2 definition (disclaimer: I'm the author). This Java library is less complete than Atlassian's though.

2 Comments

Is there a C# port of this library or equivalent?
this Atlassian library is not checking polymorphism and inheritance.
2

Validate against Swagger v3 with SpringBoot and atlassian-swagger-request-validator

SpringBoot code that assumes your schema is available at http://localhost:8080/v3/api-docs and the payload you want to validate corresponds to the path /endpoint/myentity.

This will allow pasting your JSON payload in the input form in the swagger-ui, and then click Try it out to do the validation. springdoc-openapi-starter-webmvc-ui is used for the Swagger UI and underlying dependencies.

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.atlassian.oai.validator.OpenApiInteractionValidator;
import com.atlassian.oai.validator.model.Request;
import com.atlassian.oai.validator.model.Response;
import com.atlassian.oai.validator.model.SimpleResponse;
import com.atlassian.oai.validator.report.ValidationReport;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;

@RestController
public class SwaggerValidator {
    @Operation(
            summary = "Validate JSON payload against Schema",
            description = "Validate provided JSON response string. "
                    + "Paste your JSON in the request body to check if it adheres to the schema rules."
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "Validation successful"),
            @ApiResponse(responseCode = "400", description = "Validation failed due to invalid JSON schema")
    })
    @PostMapping("/validate")
    public ResponseEntity<?> validateSchema(@RequestBody String jsonBody) {
        OpenApiInteractionValidator validator = OpenApiInteractionValidator.createForSpecificationUrl("http://localhost:8080/v3/api-docs").build();
        Response response = SimpleResponse.Builder
                .status(200)
                .withBody(jsonBody)
                .withContentType("application/json")
                .build();

        ValidationReport validationResult;
        try {
            validationResult = validator.validateResponse("/endpoint/myentity", Request.Method.GET, response);
            if (!validationResult.hasErrors()) {
                return new ResponseEntity<>(validationResult, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(validationResult.getMessages(), HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.toString());
        }
    }
}
a minimalistic maven pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.0</version>
        <relativePath/>
    </parent>
    <groupId>com.example.openapi</groupId>
    <artifactId>example-openapi-spec</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-complete</name>
    <description>API Definition</description>

    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>2.6.0</version>
        </dependency>
        <dependency>
            <groupId>com.atlassian.oai</groupId>
            <artifactId>swagger-request-validator-core</artifactId>
            <version>2.43.0</version>
        </dependency>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Once you add the dependencies and the classes to your SpringBoot project, run mvn spring-boot:run, open the swagger UI at http://localhost:8080/swagger-ui.html, and validate your JSON payload by pasting the raw string into the POST form body in swagger.


deprecated answer for Swagger v2

Validate against Swagger v2 with swagger-schema-validator

Minimal java code to do offline validation of a .json payload file against a .yaml swagger spec using https://github.com/bjansen/swagger-schema-validator:

  1. Reference the dependencies in your own project as described in the swagger-schema-validator readme or clone locally with git clone https://github.com/bjansen/swagger-schema-validator.git.

  2. Copy your .yaml and .json files into the src/test/resources folder under your test root folder.

  3. Create a test class containing something along the lines (make sure to change "/definitions/MyPayloadObjectMustBeSetHere" to point to your own definition):

import com.github.bjansen.ssv.SwaggerValidator;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import static org.junit.jupiter.api.Assertions.assertEquals;

@Test
void SwaggerSpecTest() {
    InputStream spec = getClass().getResourceAsStream("/api/swagger.yaml");
    SwaggerValidator validator = SwaggerValidator.forYamlSchema(new InputStreamReader(spec));

    InputStreamReader sample = new InputStreamReader(getClass().getResourceAsStream("/api/payload.json"));
    ProcessingReport report = validator.validate(CharStreams.toString(sample), "/definitions/MyPayloadObjectMustBeSetHere");
    assertEquals("success", report.toString()); // force printing the errors/warnings
}

Comments

1

If your Swagger JSON is hosted, you could use the following url: http://online.swagger.io/validator/debug?url=your_url

1 Comment

This works only for url's which can be accessible through internet. This won't work for Intranet url's.
-3

The OpenAPI 2.0 / Swagger schema is available in a few places, it's just a bit hard to find because of the heavy use of the word 'schema' in swagger itself.

So you can point a generic validator at this schema and your document. For example, this works nicely for me using vscode and Red Hat's YAML extension.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.