JSON Schema Validation in API Test Automation

   The API testing process analyzes multiple endpoints such as web services, databases, or web UIs. Testers should watch for failures or unexpected inputs. API testing can be achieved manually or via automation. API automation testing ensures that APIs function properly and meet customer’s expectations. In API testing, we usually validate the data in the responses, headers, status code, etc., In this article, I would like to share more about the response JSON schema validation during the API test automation in different programming languages. Schema validation will help to define, document, and validate the data models, as well as generate client-side and server-side code. It also helps to produce the stable and quality APIs.

Below is the sample JSON response for the validation,

{
"data": {
"id": 2,
"email": "janet.weaver@reqres.in",
"first_name": "Janet",
"last_name": "Weaver",
"avatar": "https://reqres.in/img/faces/2-image.jpg"
},
"support": {
"url": "https://reqres.in/#support-heading",
"text": "To keep ReqRes free, contributions towards server costs are appreciated!"
}
}

   Below is the JSON response schema data for the above JSON response data, we have to pass the JSON response schema data to the logic where we are doing the validation.

{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"email": {
"type": "string"
},
"first_name": {
"type": "string"
},
"last_name": {
"type": "string"
},
"avatar": {
"type": "string"
}
},
"required": [
"id",
"email",
"first_name",
"last_name",
"avatar"
]
},
"support": {
"type": "object",
"properties": {
"url": {
"type": "string"
},
"text": {
"type": "string"
}
},
"required": [
"url",
"text"
]
}
},
"required": [
"data",
"support"
]
}

   NOTE: we can generate the JSON schema data corresponding to the JSON response using the online JSON-to-schema converter (https://www.liquid-technologies.com/online-json-to-schema-converter)

JSON Schema Validation in Java (REST Assured)

To achieve JSON schema validation in Java (REST Assured), we need the following prerequisites:

  • Create a maven project.
  • Add the latest version of the following dependencies in pom.xml file:
    • rest-assured
    • json-schema-validator
  • Make sure that you added the below import:
    • import io.restassured.module.jsv.JsonSchemaValidator;

Once you set the prerequisites, we can start the validation using the below logic,

String baseURI = "https://reqres.in";
String endPointPath = "/api/users/2";

RestAssured.given().baseUri(baseURI).basePath(endPointPath).when().get().then().assertThat().body(JsonSchemaValidator.matchesJsonSchema(JSONSchemaData));

//JSONSchemaData will be the JSON response schema data mentioned above, we can pass it as String value.
JSON Schema Validation in Java (Playwright)

To achieve JSON schema validation in Java (Playwright), we need the following prerequisites:

  • Create a maven project.
  • Add the latest version of the following dependencies in the pom.xml file:
    • playwright
    • json-sKema

Once you set the prerequisites, we can start the validation using the below logic,

String baseURI = "https://reqres.in";
String endPointPath = "/api/users/2";

APIRequestContext apiRequestContext = playwright.request().newContext(new APIRequest.NewContextOptions().setBaseURL(baseURI));

APIResponse response = apiRequestContext.get(endPointPath);
JsonValue schemaJson = new JsonParser(jsonSchemaData).parse();
Schema schema = new SchemaLoader(schemaJson).load();
Validator validator = Validator.forSchema(schema);

String jsonResponseData = response.text();
JsonValue instance = new JsonParser(jsonResponseData).parse();
ValidationFailure failure = validator.validate(instance);
if (failure != null) {
System.out.println(failure);
}

//jsonSchemaData will be the JSON response schema data mentioned above, we can pass it as String value.
JSON Schema Validation in C#

To achieve JSON schema validation in C#, we need the following prerequisites:

  • Create a project in Visual Studio or Visual Studio Code.
  • Add the latest version of the following packages to the project:
    • RestSharp
    • Newtonsoft.Json.Schema

Once you set the prerequisites, we can start the validation using the below logic,

string baseURI = "https://reqres.in";
string endPointPath = "/api/users/2";

RestClient client = new RestClient(baseURI);
RestRequest request = new RestRequest(endPointPath, Method.Get);
request.AddHeader("Content-Type", "application/json");
RestResponse response = client.Execute(request);
string responseData = response.Content.Trim();

JSchema schema = JSchema.Parse(schemaData);
JObject data = JObject.Parse(responseData.Trim());
IList<string> errorMessages;
bool isValid = data.IsValid(schema, out errorMessages);
if (!isValid)
{
Console.WriteLine("Validation Errors:");
foreach (var error in errorMessages)
{
Console.WriteLine(error);
}
}
if (isValid)
{
Console.WriteLine("JSON schema validation passed!");
}
else
{
Console.WriteLine("JSON schema validation failed!");
}
//schemaData will be the JSON response schema data mentioned above, we can pass it as string value.
JSON Schema Validation in Python

To achieve JSON schema validation in Python, we need the following prerequisites:

  • Create a project in PyCharm or using relevant IDE.
  • Add the latest version of the following package to the project:
    • jsonschema
  • Make sure to include the following import statement in the Python file,
    • from jsonschema import validate, ValidationError

Once you set the prerequisites, we can start the validation using the below logic,

base_uri = 'https://reqres.in'
end_point_path = '/api/users/2'
url = base_uri + end_point_path
response = requests.get(url, headers=None)
try:
  json_response_data= response.json()
  validate(instance=json_response_data, schema=json_schema)
  print("Schema validation successful")
except ValidationError as e:
print(f"Schema validation failed: {e}")

//json_schema will be the JSON response schema data mentioned above, we can pass it in the logic.
JSON Schema Validation in JavaScript (Playwright)

To achieve JSON schema validation in JavaScript (Playwright), we need the following prerequisites:

  • Create a Playwright project based on JavaScript programming language in Visual Studio Code IDE.
  • Add the latest version of the following packages in the package.json file:
    • @playwright/test
    • jsonschema
  • Make sure to include the following import statement in the JavaScript class file,
    • const { Validator, ValidationError } = require(‘jsonschema’);

Once you set the prerequisites, we can start the validation using the below logic,

const baseURI = 'https://reqres.in';
const endPointPath = '/api/users/2';
const response = await fetch(`${baseURI}${endPointPath}`);
var v = new Validator();
const responseJSON = await response.json();
const validationResult = v.validate(responseJSON, jsonSchema);
if (validationResult.errors.length > 0) {
validationResult.errors.forEach((error) => {
if (error instanceof ValidationError) {
console.error(`Validation error: ${error.property} ${error.message}`);
} else {
console.error('Non-validation error:', error);
}
});
} else {
console.log('Validation successful');
}

//jsonSchema will be the JSON response schema data mentioned above, we can pass it in the logic.

   I hope you enjoyed reading this article and got some ideas on JSON schema validation and its implementation in different programming languages. Try to utilize the implementations in your project if you have such a requirement.

make it perfect!

Leave a comment

Create a website or blog at WordPress.com

Up ↑