top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Validate JSON Schema in Postman

What is JSON and JSON schema?

JSON (Java Script Object Notation) is an open standard file format and data interchange format that human and machines can read and write. It is language independent data format which is derived from JavaScript. JSON filenames use the extension .json.

JSON Schema is a declarative language for defining structure and constraints for JSON data. It describes the content, structure, data types, and expected constraints within JSON document, which helps ensure the consistency and integrity of JSON data in different applications. JSON schema defines various keys and their values and certain constraints on their values. JSON schema is useful for validating API payloads and ensuring data consistency.


Why JSON Schema validation is required?

JSON schema validation is required for ensuring the correctness and quality of JSON data. It allows developers to define, validate and document the structure and content of JSON data according to a set of predefined rules known as schema.

  1. Ensure that the JSON data follows the expected format when exchanging data between systems.

  2. Maintain the integrity of the data by preventing invalid or malicious data from being processed.

  3. Provide a mechanism for error handling by specifying which parts of the data are incorrect.

  4. Serves as documentation for the data format which makes it easier for developers to understand and work with the data.


Steps to verify JSCON schema :

  1. Generate and understand JSON schema

    open the link "https://www.jsongenerator.io/schema" and copy JSON data on left side and press convert to generate JSON schema

    In this schema :

The object has properties "id", "name" , "type", "available" .

The “required” array specifies that “id”, “name”, "type” and "available must always be present.

2. Save JSON schema

Ensure postman is installed on your system and sign in or create a new account.

Copy and Save JSON schema in postman environment.

Next, create a sample API request whose response data need to validate against our predefined JSON schema. In the following example : Simple Book API_Practise is a collection and List of books is a request name and GET is HTTP request created using the URL .


3. Create API request in postman

In the workspace click on the "NEW" button and select "HTTP" .

Name your request appropriately (for example: List of books).

choose existing collection or create new request by selecting appropriate method (GET, POST ,PUT etc.)

based on your endpoint.

Paste the endpoint URL where you expect to receive a JSON response.

click the "Send" button in postman and check the response.

Following is the response after clicking "send" button.

Test is passed as we get 200 OK .

4. Verify JSON schema :

To validate the JSON response against your schema within postman , you will need to write a test script.

In the Postman interface, Navigate to the "scripts" tab below the request and write script

//Define the JSON schema that you want to validate
var schema = {
  "type": "array",
  "$schema": "http://json-schema.org/draft-04/schema#",
  "description": "",
  "minItems": 1,
  "uniqueItems": true,
  "items": {
    "type": "object",
    "required": [
      "id",
      "name",
      "type",
      "available"
    ],
    "properties": {
      "id": {
        "type": "number"
      },
      "name": {
        "type": "string",
        "minLength": 1
      },
      "type": {
        "type": "string",
        "minLength": 1
      },
      "available": {
        "type": "boolean"
      }
    }
  }
}
//Validate the response body
pm.test('Schema validation', () => {
  pm.response.to.have.jsonSchema (schema);
});


//Get the response result
var data = pm.response.json();

//Validate the response body
pm.test('Schema is valid', function() {
pm.expect(tv4.validate(data, schema)).to.be.true;
 });

Schema Definition: The schema holds our schema, which we will validate against the API response.

Response Handling: The pm.response.json() method extracts the JSON response from the API call.

Define Test : pm.test function define tests. It provides a name and a function that returns a boolean value to indicate if the test passed or failed.

pm.expect(): it is used in assertions to test the response detail. Here it is checking if var data (which is having json response) is same as schema. so checking the validation of JSON schema with the response using tv4 library which is available in postman.

You can also check console for better understanding:


Another approach to validate JSON schema:

  1. Import the Ajv library which is a JSON schema validator for Javascript.

  2. Initializing Ajv, An instance is initialized allowing us to use its functionalities.

  3. The defined schema is compiled using Ajv's compile() method , resulting in validation function.

  4. The compiled schema validation function is used to validate the sample data. If the data conforms to the schema, a success message is logged; otherwise, validation errors are logged.

    1. Steps are as follows :

      initialize npm in project directory

      npm init -y

    2. Install Ajv library using npm

      npm install ajv

    3. javascript to validate JSON schema

      const Ajv = require("ajv");


      // Define schema and data

      const schema = {

      type: "object",

      properties: {

      name: { type: "string" },

      age: { type: "number" }

      },

      required: ["name", "age"]

      };


      const data = {

      name: "John Doe",

      age: 30

      };


      // Initialize Ajv

      const ajv = new Ajv();


      // Compile schema

      const validate = ajv.compile(schema);


      // Validate data

      const isValid = validate(data);


      if (isValid) {

      console.log("Validation successful");

      } else {

      console.log("Validation failed:", validate.errors);

      }

    4. Run the javascript using Node.js

      node validate.js


      So we can validate JSON schema using two different methods.





11 views0 comments

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page