How to validate the JSON response with expected JSON schema

So, here’s my approach.

First, I add some .jar’s into my project:

To grab them … you can manually search them into Maven central … or do a small trick:
- Create a temporary custom keyword and put only this code into it (I name it Grab):

package utilimport groovy.grape.Grape@Grab(group='org.everit.json', module='org.everit.json.schema', version='1.5.1')public class Grab {}

- Once you hit ‘save’ katalon may looks like is freezing … but fear not. After a while, depending on your internet connection it will be back to normal. Now, navigate into C:\Users\your.user\.groovy folder and you will find there a grapes folder. Collect any .jar downloaded and bring them into your project. Now you can delete this temporary package.

Second, I made a custom keyword like this:

package com.apiimport org.everit.json.schema.Schemaimport org.everit.json.schema.ValidationExceptionimport org.everit.json.schema.loader.SchemaLoaderimport org.json.JSONObjectimport org.json.JSONTokenerimport com.kms.katalon.core.annotation.Keywordimport com.kms.katalon.core.util.KeywordUtilclass EveritValidator {	/**	 * Send request and verify status code	 * @param stringJson Json to validate	 * @param stringSchema validation schema	 */	@Keyword	def verifyJsonSchema(String stringJson, String stringSchema) {		JSONObject rawSchema = new JSONObject(new JSONTokener(stringSchema))		Schema schema = SchemaLoader.load(rawSchema)		try {			schema.validate(new JSONObject(stringJson))			KeywordUtil.markPassed("Valid schema")		} catch (ValidationException e) {			StringBuffer outmessage = new StringBuffer()			outmessage << e.getMessage() << "\n"			e.getAllMessages().each { msg -> outmessage << "$msg \n"}			KeywordUtil.markFailed(outmessage as String)		}	}}

Now, the test case looks as follows (I provide the validation schema from an external file located in ./resources/mySchema.json and I use also an parametrized REST test objectnamed** GETRequest.ContentJSON(url,token)** to send the API request, adapt to your needs):

import static com.kms.katalon.core.testobject.ObjectRepository.findTestObjectimport com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WSimport internal.GlobalVariable as GlobalVariable'Given'WS.comment("Setup")reqUrl = "http://your/request/url"schema = new File('./resources/mySchema.json').textrequest = findTestObject('GETRequest.ContentJSON(url,token)', [('url') : reqUrl, ('token') : GlobalVariable.myToken])'When'WS.comment("Sending GET request: ${request.getRestUrl()}")response = WS.sendRequest(request)'Then'WS.comment("Check response status")WS.verifyResponseStatusCode(response, 200)WS.comment("Check response contentType")assert response.isJsonContentType()WS.comment("Validate response schema")responseJson = response.getResponseBodyContent()CustomKeywords.'com.api.EveritValidator.verifyJsonSchema'(responseJson, schema)

If any validation fails, the keyword will collect from the response message all failures and show them into the execution log (also marking the test failed), if passed will just log “valid schema”

Hope it helped!

libs.png

1 Like