bgh
bgh

Reputation: 2170

Validate Swagger API Declaration using official Swagger API schema

The swagger-spec repository provides a JSON-schema describing a valid Swagger 2.0 API definition. I would like to use this schema in order to validate if a given API definition file is valid before I try to interpret it. I'm using the following code to load the schema using Json.NET:

JsonSchema swaggerApiSchema;
using (var textReader = new JsonTextReader(new StreamReader(@"C:\path\to\schema.json")))
{
    swaggerApiSchema = JsonSchema.Read(textReader);
}

This throws an ArgumentException reporting "Can not convert Array to Boolean.".

Is there something wrong with the schema file, is this a bug with Json.NET, or am I just doing something wrong?

Upvotes: 1

Views: 4115

Answers (1)

Ilija Dimov
Ilija Dimov

Reputation: 5299

As per documentation, JSON.NET implements JSON Schema Draft 3. More here. But the Swagger schema you posted is created according to the JSON Schema Draft 4. One of the differences between the Draft 3 and Draft 4 of the JSON Schema is the required attribute, which in JSON Schema Draft 3 was an attribute of subschemas in properties. In JSON Schema Draft 4 is a first level keyword playing the same role, and has a string array as an argument.

Sample of JSON Schema Draft 3:

{
    "properties": {
        "Id": {
            "required": true,
            "type": "integer"
        },
        "FirstName": {
            "required": true,
            "type": "string",
        },
        "LastName": {
            "required": true,
            "type": "string
        }
    }
}

Sample of JSON Schema Draft 4:

{
    "properties": {
        "Id": {
            "type": "integer"
        },
        "FirstName": {
            "type": "string"
        },
        "LastName": {
            "type": "string"
        }
    },
    "required": [ "Id", "FirstName", "LastName" ]
}

Notice the difference in the two schemas, of how required properties are defined. That's why you are getting an error: "Can not convert Array to Boolean.".

And here is the first appearance of required property in the Swagger JSON Schema, that is causing the error:

"required": [ "swagger", "info", "paths" ]

I would suggest to validate with parser that implements JSON Schema Draft 4.

Upvotes: 3

Related Questions