Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
About JSON Schema
2.1.
JavaScript Object Notation
2.2.
JSON Objects
3.
Create a JSON Schema in REST assured 
3.1.
JSON Object
3.2.
JSON Schema
4.
JSON for Validation of the Schema With REST Assured
4.1.
Validation of the Schema Stored in the Resource of the Project
4.1.1.
OUTPUT
4.2.
Validation of the Schema not Stored in the Resource Folder
5.
JSON for Validation of the Schema Without REST Assured
5.1.
Code Implementation
5.1.1.
OUTPUT
6.
Frequently Asked Questions
6.1.
How to convert JSON to string?
6.2.
What are {} and [] used in JSONpath expressions for?
6.3.
Is JSON secure or free from viruses?
6.4.
Which is better, postman or Rest assured?
6.5.
Why is JSON used over XML?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

What is JSON Schema and Validation of the Schema with and without Rest Assured

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Hello ninjas,
We all know the importance of layouts in building designing. Similar is the case with JSON, where the JSON schema works like a layout for JSON objects.

What is JSON Schema and validation of the schema with and without rest assured

This article will teach you about JSON schema in REST assured in detail and validation of the schema with or without REST assured.

About JSON Schema

In the English language, schema means a structured framework.
In technical terms, a schema is a method to specify documents' structure, content, and, to some extent, semantics. 

schema

JavaScript Object Notation

It can also be called JSON is a format for storing data. To retrieve data from a JSON document, we use JSONpath. It is a query language for JSON.
Data in JSON is stored in key-value pairs. JSON schema in REST assured is the structure of these key-value pairs. It includes allowed format, fields, values, etc. 
It is a type of JSON document.

JSON Objects

JSON objects contain key-value pairs. 
For example:

{
	Id : 2
	Name : Anchita sharma
	Email : anchita.sharma@codingninjas.com 
}

 

The collection of key-value pairs is stored in JSON objects. 
It is surrounded by curly brackets {}.
To learn more, read simple and nested JSON objects.

JSON schema in REST assured can validate JSON objects in two ways:
 

  • Syntactically -  checks if a JSON object is a valid JSON object.
     
  • Semantically - checks if JSON objects include all necessary fields and values.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Create a JSON Schema in REST assured 

There are two essential arrays that are used in JSON schema in REST assured:

  • Required - This enlists all the keys the JSON object must consist of.
     
  • Properties - This enlists the metadata about the keys of JSON objects.
     

NoteadditionalProperties array is used to represent extra data. This is a structure that does not exist in the “Properties” array.

For example:

JSON Object

The code below is for the JSON object:

{
    "name": "Anchita",
    "female": true,
    "address": {
        "street": 21,
        "house number": 485
    }
}

JSON Schema

The code below is for the JSON schema:

{
  "$schema": "https://json-schema.org/draft/2022-23/schema",
  "$id": "http://example.com/example.json",
  "type": "object",
  "default": {},
  "title": "Root Schema",
  "required": [
    "name",
    "female",
    "Address"
  ],
  "properties": {
    "name": {
      "type": "string",
      "default": "",
      "title": "The name Schema",
      "examples": [
        "Anchita"
      ]
    },
    "female": {
      "type": "boolean",
      "default": false,
      "title": "The female Schema",
      "examples": [
        true
      ]
    },
    "address": {
      "type": "object",
      "default": {},
      "title": "The address Schema",
      "required": [
        "street",
        "house number"
      ],
      "properties": {
        "street": {
          "type": "integer",
          "default": 0,
          "title": "The street Schema",
          "examples": [
            21
          ]
        },
        "house number": {
          "type": "integer",
          "default": 0,
          "title": "The house number Schema",
          "examples": [
            485
          ]
        }
      },
      "examples": [{
        "street": 21,
        "house number": 485
      }]
    }
  },
  "examples": [{
    "name": "Anchita",
    "female": true,
    "address": {
      "street": 21,
      "house number": 485
    }
  }]
}

 

You can write a JSON schema in REST assured in two ways:
 

  • Manually - you write the whole set of code by yourself.
     
  • Using the JSON schema tool - you provide the JSON object as input. This tool returns a JSON schema in REST assured that you can modify and use it. 
JSON Schema validation

JSON for Validation of the Schema With REST Assured

What does validation of the schema mean?
Validation of the schemes means spotting the errors in the JSON object using the JSON scheme in REST assured. Such as finding missing properties, the wrong data type of properties, etc. 

Validation of the schemes helps to:

  • Write correct JSON objects.
     
  • Amend existing JSON objects in your projects.
     
  • Saves developers load from manually finding errors.
     
  • Saves time. 
     

NOTE: You need to add the JSON-schema-Validator java library in the project classpath to perform validation of the schema. It allows you to use JSON for validation of the schema. The versions of the validator and REST assured should be the same.
 

Validation of the schema can be done in 2 ways : 

  • matchesJsonSchemaInClasspath() - used when JSON schema in REST assured files are stored in the resource folder of your project.
     
  • matchesJsonSchema() - used when JSON schema in REST assured files are stored at a different location.

Validation of the Schema Stored in the Resource of the Project

For validation of the schema stored in the resource of the project in REST assured, we use the matchesJsonSchemaInClasspath() method.

package JsonSchema;

import org.hamcrest.Matchers;
import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.module.jsv.JsonSchemaValidator;

public class JSONschemaverification {

  @Test
  public void singlemember() {

    String jsonStringPayload = "{\"username\":\"admin\",\"password\":\"}";

    RestAssured
      .given()
      .baseUri("https://localhost:3001")
      .contentType(ContentType.JSON)
      .body(jsonStringPayload)
      .when()
      .post()
      .then()
      .assertThat()
      .statusCode(200)
      .body("token", Matchers.notNullValue())
      .body(JsonSchemaValidator.matchesJsonSchemaInClasspath("FILE FOLDER.json"));
  }

}

OUTPUT

Output image


NOTE: Since the JSON path follows all the schemes (rules) thus JSON will pass while giving no error.

You write the above code and provide a file folder path within the brackets () of matchesJsonSchemaInClasspath()

Validation of the Schema not Stored in the Resource Folder

For validation of the schema stored in the resource of the project in REST assured, we use the matchesJsonSchema() method.
In this method, we use the same syntax as we used for the Validation of the schema stored in the resource of the project discussed in the above sections.

The only change to be made is : 

.body(JsonSchemaValidator.matchesJsonSchema(new File("FILE PATH")));

 

Provide file path within the brackets () of matchesJsonSchema().

JSON for Validation of the Schema Without REST Assured

Why do we need validation of the schema without REST assured?
We validate JSON responses using REST assured. It is necessary to validate JSON request payloads as well before we pass it to the API.
JSON request payloads are the essential information in the data that is passed while making API requests. It is the information sent to or received from the server.

NOTE: You can use JSON-schema-Validator standalone as well to perform validation of the schema without REST assured. You will need to add the Hamcrest library to your project for the same.

Code Implementation

package JsonSchema;

import java.io.File;
import org.hamcrest.MatcherAssert;

import org.testng.annotations.Test;
import io.restassured.module.jsv.JsonSchemaValidator;

public class VerifyJsonSchemaWithoutRestAssured {

  @Test
  public void JSONschemaverification() {
    String json = "{\r\n" +
      " \"firstname\" : \"Anchita\",\r\n" +
      " \"lastname\" : \"Sharma\",\r\n"
  }
  ";

  MatcherAssert.assertThat(json, JsonSchemaValidator.matchesJsonSchema(new File("FILE PATH")));
}
}

OUTPUT

Output image


Since the JSON path follows all the schemes (rules) thus JSON will pass while giving no error.

Provide a file path within the brackets () of matchesJsonSchema().

Now let’s discuss some FAQs.

Frequently Asked Questions

How to convert JSON to string?

JSON.stringify() is used for this purpose. The result will be a string. It will follow the JSON notation.

What are {} and [] used in JSONpath expressions for?

JSONpath expressions is a query language for JSON. It uses [] for JSON objects. And it uses {} for arrays in JSONpath expressions.

Is JSON secure or free from viruses?

JSON can be hijacked and is not completely free from viruses either. The attacker targets a system with access to JSON data. And then can retrieve data from a JSON file.

Which is better, postman or Rest assured?

Rest assured is better than the postman. Rest assured, you can reuse code as it is a Java client. Moreover, in postman, we can provide only one data file for each collection, unlike in Rest assured.

Why is JSON used over XML?

JSON is designed for data interchange. Thus it is faster than XML. Moreover, JSON can be parsed by a javascript function. Whereas XML requires an XML parser.

Check this out :  what is schema in dbms

Conclusion

In this article, we discussed the JSON schema in REST assured and how to write it. We also learned about the validation of schema with and without REST assured in depth.
To learn more about REST assured, refer to,

  1. Introduction to rest assured.
     
  2. JSON objects in rest assured.
     
  3. Creating JSON objects and arrays.
     

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!

Previous article
Specify How The Expected Response Must Look Like In REST Assured
Next article
REST Assured - Editing Existing JSON Object On The Fly Using JsonNode - Jackson
Live masterclass