Validate JSON with Postman

postman

In this new post, I explain how to validate a JSON result with Postman from your APIs. In Testing APIs with RestClient in Visual Studio Code post, I talk how to use the RestClient to test APIs. Also, I started to use another extension for Visual Studio Code that it is very simple to use. Thunder Client is the best extension to test APIs in a very similar design of Postman.

After few consideration, I decided to go back to Postman instead of using other tools. In particular because it has the integration with JavaScript that allows me to write some custom tests.

What is Postman?

So, Postman is a useful tool to test API requests. Doesn’t matter if we are developing our own APIs or we are using a third party provider APIs. We can check all the data received on each request. Then, I will explain how to validate JSON with Postman writing tests along with each request. Also, I show how to check if the calls are successful and if json data received meets the expected JSON schema.

Postman first time - Validate JSON with Postman
Postman first time

Check request result

The first and simpler test that we can include is to validate the request has succeded, and we got the Response 200 OK, or any other response code we may be expecting. To do so, the easiest way is to include the test at the Collection level, so that all the requests underneath will inherit this validation. 

So you can edit the Collection, select the “Tests” tab, and include the following script:

pm.test("Status code is OK", function () {
    pm.expect(pm.response.code).to.be.oneOf([200, 201, 204, 207])
});

You can include any other response codes you might be expecting from your requests as well.

Once set up, on any request execution, you should see the test result in the response “Tests” tab:

Test the response code in Postman - Validate JSON with Postman
Test the response code in Postman

Response JSON schema validation

Now, Postman scripting is quite a powerful asset, so you can go beyond a simple response code validation and include more complex validations, like checking that the response JSON meets a determined schema.

What is a JSON schema?

JSON Schema is a grammar language for defining the structure, content, and (to some extent) semantics of JSON objects. It lets you specify metadata (data about data) about what an object’s properties mean and what values are valid for those properties.

The result of applying the grammar language to a JSON document is the schema (a blueprint) describing the set of JSON objects that are valid according to the schema.

  1. JSON Schema is itself a JSON object.
  2. JSON Schema grammar is maintained at https://json-schema.org.
  3. It describes the existing data format.
  4. If offers clear, human-readable, and machine-readable documentation.
  5. It provides complete structural validation, which is useful for automated testing and validating client-submitted data.

Create a JSON schema for a JSON

So, the first step is to create the JSON schema from a JSON. For example, when we design an API, we decide what the inputs/parameters are what the result JSON looks like. For example, I have one API that returns a connection token and it looks like

{
    "access_token": "eyJhbGciOiJS...",
    "expires_in": 3600,
    "token_type": "Bearer",
    "scope": "email openid profile roles smp"
}

Now, from this JSON I want to create the JSON schema. There are a lot of tools online and offline. I found quite straightforward and easy to use jsonformatter.org. There is a page that creates a JSON schema from a JSON and this tool is on this page.

Now, I copy the JSON and paste on the left side and immediately, I have the correspondent JSON schema.

{
    "$schema": "https://json-schema.org/draft-06/schema#",
    "$ref": "#/definitions/Welcome2",
    "definitions": {
        "Welcome2": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
                "access_token": {
                    "type": "string"
                },
                "expires_in": {
                    "type": "integer"
                },
                "token_type": {
                    "type": "string"
                },
                "scope": {
                    "type": "string"
                }
            },
            "required": [
                "access_token",
                "expires_in",
                "scope",
                "token_type"
            ],
            "title": "Welcome2"
        }
    }
}

Here the screenshot.

jsonformatter.org in action
jsonformatter.org in action

Now, we have our JSON schema we can add the code in Postman.

Add the schema in Postman

Once you got the schema, back to Postman, select the request you want to be validated, and edit the “Pre-request Script” tab, where you should add the following script (using the schema from the step before):

Add script in Pre-request Script in Postman
Add script in Pre-request Script in Postman

How you can see in the screenshot, I define a variable schema and then assign the JSON schema. At the end, a semicolon ; is required. This is JavaScript. You have the full code here

var schema = {
    "$schema": "https://json-schema.org/draft-06/schema#",
    "$ref": "#/definitions/Welcome2",
    "definitions": {
        "Welcome2": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
                "access_token": {
                    "type": "string"
                },
                "expires_in": {
                    "type": "integer"
                },
                "token_type": {
                    "type": "string"
                },
                "scope": {
                    "type": "string"
                }
            },
            "required": [
                "access_token",
                "expires_in",
                "scope",
                "token_type"
            ],
            "title": "Welcome2"
        }
    }
};

Now, we have to tell Postman that we want to use this variable in the request. After the definition of the schema variable, add this code

pm.variables.set("schema", schema);

So, Postman (pm) sets a new variable schema that we can use in the test.

Add the response JSON validation

Postman scripting is quite a powerful asset, so you can go beyond a simple response code validation and include more complex validations, like checking that the response JSON meets a determined schema.

In order to execute such validation, back to the “Tests” tab in the Collection to include the following script, right after the previous script we added in the previous step:

try {
    var schema = pm.variables.get("schema");
 
    if(schema) {
        const jsonData = pm.response.json();
        if(jsonData) {
            var Ajv = require('ajv');
            ajv = new Ajv({ logger: console, allErrors: true });
 
            pm.test('Schema is valid', function() {
                var result = tv4.validateMultiple(jsonData, schema);
                console.log(result);
                pm.expect(result.valid).to.be.true;
            });
       }
    }
}
catch(e) {
    console.log(e);
}

Code explained

First, I read the schema from the variables. Then, if it is not null, I parse and save the API response in the jsonData. Then, I use AJV and log all the errors. Now, I ask Postman pm to run a test.

Then, I use tv4 to validate the JSON data with the schema. If the result is valid, the test is passed.

Test results in Postman
Test results in Postman

Ajv JSON schema validator

Ajv JSON schema validator is used by a large number of JavaScript applications and libraries in all JavaScript environments – Node.js, browser, Electron apps, WeChat mini-apps etc.

It allows implementing complex data validation logic via declarative schemas for your JSON data, without writing code.

TV4

TV4 is another tools that Postman is using. Tiny Validator (for v4 JSON Schema) is another JavaScript library to validate simple values and complex objects using a rich validation vocabulary.

Wrap up

How you see, in few line of code, there are a lot of functionalities and concepts to know. I hope this post helps you to write better tests for your API. Please leave your comments and thoughts in the forum.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.