How To Do JSON Schema Validation

In this article, we will understand what is JSON Schema validation and how we can achieve it.

What is JSON Schema?

JSON refers to JavaScript Object Notation. It is a widely used data interchange format where data is stored in the form of key-value pair.

JSON Schema is a format or document that is written in JSON itself to define the structure of JSON data. It specifies the metadata like what are the properties of the object, and what values are acceptable for those properties.

Visit official documentation for JSON schema specifications.

Understand The JSON Syntax

Let’s understand the commonly used JSON data types.

  1. JSON Object
{
 "id": 1,
 "name": "John"
}

JSON file starts with curly braces {}. This is the root-level object. Data that is present inside curly braces is considered an object. We can have multiple objects as well separated by a comma. For example, refer to the JSON schema mentioned below that contains 2 objects inside the root object.

{
    "one":
    {
        "number": 1
    },
    "two":
    {
        "number": 2
    }
}

2. JSON Array

"books_isbn": [
        "93086002-df2f-43a2e492149a",
        "67856002-df2f-43a2e492154e"
    ]

JSON array store data inside square brackets []. We can have objects inside arrays as well as arrays inside objects.

3. String – used for Character Value.

4. number – used for Decimal and Integer Values.

5. boolean – This is used for either True or False.

Let’s take the example of a JSON payload that consists of all these data types.

{
  "name": "Oscer",
  "age": 2,
  "adopted" : true,
  "owners": [
    {
      "name": "John",
      "email": "[email protected]"
    }
  ]
}

In this schema “name” is of String type, “age” is a number field, and “adopted” is a boolean field. “owners” is an array of objects that contains name and email field.

How to generate JSON Schema

To generate JSON schema several online free tools are available. I will be using this tool for the demo. Open the tool, paste the JSON payload and click on generate schema. If the provided payload is valid then the schema is generated.

Refer generate schema.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "integer"
    },
    "adopted": {
      "type": "boolean"
    },
    "owners": {
      "type": "array",
      "items": [
        {
          "type": "object",
          "properties": {
            "name": {
              "type": "string"
            },
            "email": {
              "type": "string"
            }
          },
          "required": [
            "name",
            "email"
          ]
        }
      ]
    }
  },
  "required": [
    "name",
    "age",
    "adopted",
    "owners"
  ]
}

Understand The JSON Schema

This is the simplest form of schema which is defining the basic structure of our JSON payload. In this section, we will try to understand the schema and how it can help us in our validations.

  1. “type”: “object”: Root-level type is instructing that this is an object. If any other type is returned in response like “array” then schema validation will fail.
  2. Properties block describing the keys along with their expected data types. name is a key that expects string data type, so in return, if we get int or float then this is a validation failure.
"properties": {
    "name": {
      "type": "string"
    },
    "age": {
      "type": "integer"
    },
    "adopted": {
      "type": "boolean"
    },

3. “type”: “array” defining that “owners” property expects a collection of Array type.

4. “required” block defines that the keys present inside these blocks are mandatory. Suppose “age” is not coming in response then our test will fail and we will find out that the “age” key is missing from the response.

 "required": [
    "name",
    "age",
    "adopted",
    "owners"
  ]

You can add multiple validations in the schema as per your project requirement.

What Is JSON Schema Validator

JSON Schema Validator is a rest-assured library that helps in validating the JSON Schema. Create a maven project and add the below-mentioned dependencies in your pom.xml file.

<dependency>
	<groupId>io.rest-assured</groupId>
	<artifactId>rest-assured</artifactId>
	<version>5.3.0 </version>
	</dependency>
<dependency>
	<groupId>io.rest-assured</groupId>
	<artifactId>json-schema-validator</artifactId>
	<version>4.5.0</version>
</dependency>

Go to JSON schema generator and generate the schema of your API response payload. Create a new file with JSON extension for your project and store the generated schema in this file. keep all JSON files in the src/test/resources folder.

JSON Schema Validation

Write JSON Schema Validation Tests

First, we need to read the JSON schema from our location and then write an assertion in our rest-assured test whether the response body is matching with the schema or not.

We will utilize the matchesJsonSchemaInClasspath(file) method of the JSON schema validator for assertion.

	@Test
	public void getDashboardData() throws Exception {
            Log.info("*** Get Dashboard data ***");
            given().baseUri("baseURL")
             .log().all().get("endpoint").then ()
               .statusCode (200).and()
               .assertThat ()
	       .body(matchesJsonSchemaInClasspath("DashboardSchema.json"))
		}

Now let’s execute the test and validate the results. The test was executed successfully since the JSON schema received in the response matches the expected JSON Schema.

You will observe error messages in case of failure like

error: instance type (integer) does not match any allowed primitive type (allowed: ["string"])
    level: "error"
    schema: {"loadingURI":"#","pointer":"/properties/id"}
    instance: {"pointer":"/id"}
    domain: "validation"
    keyword: "type"
    found: "integer"
    expected: ["string"]

This message clearly states that the “id” field is expected of String type but in response, it is coming as “integer”. This is just the simplest example of how schema validation works. By leveraging the JSON Schema validator in the API test suit we can build a solid and robust framework.

Discover more from AutomationQaHub

Subscribe now to keep reading and get access to the full archive.

Continue reading