Do you want to validate JSON response of your application REST APIs? For a large JSON, it is easy to use JSON schema for validation. In this post, we will see how to validate JSON response with JSON Schema in Postman using ajv validator. BrijPad - Online tool allows you to generate and validate JSON Schema. We will use it to generate Schema.
Read Also: Inspect JSON Easily with BrijPad
Video
Watch the following video tutorial for this post to learn more:
Steps
Here are the step by step guide to validate JSON response:
Step 1: Get JSON Data:
Let's take JSONPlaceholder Online REST API for testing. In POST /posts HTTP endpoint, if we pass following data:
{
"title": "foo",
"body": "bar",
"userId": 1
}
The output will be following:
{
"title": "foo",
"body": "bar",
"userId": 1,
"id": 101
}
Whatever JSON we will post comes with id field in response. It is good and simple for testing purpose.
Step 2: Generate JSON Schema with BrijPad:
BrijPad allows you to generate draft-07 version of JSON schema. You can also validate different data against the schema there. It is very easy to test.
To generate schema, put the JSON data in left side box and click "JSON To Schema" button in "JSON" tab. It will generate Schema in right side box.
Now, you can validate different JSON data in left side to validate against the generated schema in right side. Click "Validate Schema" button in JSON tab. In case of invalid data, it will display error and generate the details in the browser console.
Note: Make sure your JSON data must be in left side box and JSON Schema must be in right side box. Currently, it supports draft-07 schema.
Let's remove userId in JSON data (left side box) and click "Validate Schema" button.
It will show error and in browser console, you will get the error details and you can easily identify where the problem is.
Step 3: Setup Test Script with ajv:
Open Test tab in Postman and write following test script:
var Ajv = require('ajv'),
ajv = new Ajv({logger: console}),
schema = {
// Paste JSON Schema generated from BrijPad here...
};
pm.test('Schema is valid', function() {
var data = pm.response.json();
pm.expect(ajv.validate(schema, data)).to.be.true;
});
Replace schema value with the generated JSON Schema in Brijpad. Here ajv is used as JSON Schema Validator.
Step 4: Run and check Postman Request
Run the request, you will get test "Schema is valid" is "Pass"
Let's remove userId in POST body and test the same. You will get "Fail" status.
If you want to see error in Test Results tab, update test method in following way:
pm.test('Schema is valid', function() {
pm.expect(ajv.validate(schema, pm.response.json()), JSON.stringify(ajv.errors)).to.be.true;
});
Conclusion
In this post, we saw:
- How to generate and validate JSON Schema using BrijPad
- Using JSONPlaceholder as mock APIs for testing using Postman
- How to use ajv as JSON Schema validator in Postman test script
Hope, it helps. Enjoy BrijPad !!