Validation Schema Management in Postman REST Client

Introduction

Postman REST Client provides an elegant way to validate your API responses using TinyValidator ( tv4 ) for JSON schema validation. Generally GET APIs or Error Responses have same schema. Normally you will add the schema object in the Test scripts tab, which leads to duplication in each request configuration. Hence to make schemas reusable we need to have single source of truth. In this blog I will share this approach.


Setup

We will be using below tools or features for explanation

  • Mock JSON Server : We will be using two APIs from this website for demo. ( Get Todos and Get All Users )

  • Postman Pre-Request Script : The script is executed before each request of the collection when it is added at the collection level. We will be loading the schemas in this script like suite level execution.

  • Postman Test Script : The script executed after the request is processed. We will be validating the JSON schema here.

  • http-server : For serving the schema files over http request from a folder ( Note : Please install it at global level using hyphen g flag of npm install command )

Explanation

The approach we have taken is to store the JSON schemas in the folder and serve them over the http like static JSON files. Load all the schemas in the pre-request script and store them in the environment variables and use them on demand in the test scripts.


Storage of Schemas


We are storing the schemas as JSON files in the filesystem like shown below

Serving over http


We then install http-server globally using npm install command mentioned below


npm i -g http-server

Start the http-server from the folder ( in the terminal window change the working directory to this folder ) and serve it on port 8084 using below command


http-server . -p 8084

Sample output of running http-server would be something like below

http-server settings: 
CORS: disabled
Cache: 3600 seconds
Connection Timeout: 120 seconds
Directory Listings: visible
AutoIndex: visible
Serve GZIP Files: false
Serve Brotli Files: false
Default File Extension: none

Available on:
  http://127.0.0.1:8084
  http://192.168.1.29:8084
Hit CTRL-C to stop the server


Load Schemas in the Collection's Pre-Request Script


You need to make an HTTP request to fetch the schemas and store them in the environment variables. Below is the code snippet for the same

Note : We are adding a suffix "Schema" hence in the environment variables the Schemas would be stored as GetTodosSchema and GetAllUsersSchema respectively
const schemaNames = [
    'GetTodos',
    'GetAllUsers'
]

function loadAllSchemas(){
    for(let index=0;index<schemaNames.length;index++){
        const currentSchema = schemaNames[index];
        pm.sendRequest(`http://localhost:8084/${currentSchema}.json`,(err,response)=>{
            if(err){
                console.error(`Unable to fetch Schema : ${currentSchema}`);
            }
            if(response == undefined || response.length == 0){
                console.error(`No data in response for Schema : ${currentSchema}`);
            }
            if(response){
                pm.environment.set(`${currentSchema}Schema`,response.json());
            }
        });
    }
}

// This check is required so that we don't load all the schemas for every request.
const firstSchema = pm.environment.get("GetTodos");
if(firstSchema === undefined){
    console.log("Loading Schemas...");
    loadAllSchemas();
}

Copy past above snippet in the Collection Level Pre-Request Script tab as shown in the image below

Postman Collection Level Pre-Request Script tab
Postman Collection Level Pre-Request Script tab

Postman Request Configuration


Create a Postman GET Request for the request you want to test. In our case we created a request to GET Todos and Get Users from the Mock JSON API website.


Test Script Tab Validating Schema

Add a Test Script to validate response against loaded schema

Last step is to add a test script which will validate the response value against the schema stored in memory. Below is the code snippet for the same :



var schema = pm.environment.get('GetTodosSchema')

pm.test('Schema is valid', function () {
    var jsonData = pm.response.json();
    var validationResult = tv4.validate(jsonData, schema);
     if(validationResult === false){
        var result = tv4.validateResult(jsonData, schema, true);
        console.log(result.error);
    }
    pm.expect(validationResult).to.be.true;
});
    

Below is the postman rest client screenshot

Postman Test Script for Response Schema Validation
Postman Test Script for Response Schema Validation

Summary

We resolved an issue of redundancy when you are validating the schemas of the responses using TinyValidator for JSON. We stored them in file system and served them over http. You can now reuse the schema for different requests like error responses, etc. Only drawback with this approach is that we have to pre-fetch and store them in memory as environment variables.