Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postman array schema validation

I have the problem with array json schema validation in postman.

var schema = {
    "type": "array",
    "items": [{
         "id": {
            "type":"long"
             },
         "name": {
             "type":"string"
             },
         "email": {
             "type":"string"
            }
    }]
};


pm.test('Response schema type nodes verification', function() {
  pm.expect(tv4.validate(pm.response.json(), schema)).to.be.true;
});

And the response body is:

[
    {
        "id": 1,
        "name": "test1",
        "email": "[email protected]"
    },
    {
        "id": 2,
        "name": "test2",
        "email": "[email protected]"
    },
 .
 .
 .
]

I have always passed result. Also I tried with removed [].

Where is the problem?

like image 290
profiler Avatar asked Dec 14 '22 11:12

profiler


2 Answers

The schema used in question is incorrect, you need to define the type of item in array as object. The correct JSON schema would look like:

var schema = {
    "type": "array",
    "items": [{
        type: "object",
        properties:{
         "id": {
            "type":"integer"
             },
         "name": {
             "type":"string"
             },
         "email": {
             "type":"string"
            }
        }
    }]
};


pm.test('Response schema type nodes verification', function() {
  pm.expect(tv4.validate(pm.response.json(), schema)).to.be.true;
});

Please note there are only 2 numeric types in JSON Schema: integer and number. There is no type as long.

like image 192
shaochuancs Avatar answered Dec 18 '22 11:12

shaochuancs


You could also use Ajv, this is now included with the Postman native apps and the project is actively maintained:

var Ajv = require("ajv"),
    ajv = new Ajv({logger: console}),
    schema = {
        "type": "array",
        "items": {
            "type": "object",
            "properties": {
                "id": { "type": "integer" },
                "name": { "type": "string" },
                "email": { "type": "string" }
            }  
        }
    };


pm.test("Schema is valid", function() {
        pm.expect(ajv.validate(schema, pm.response.json())).to.be.true;
});
like image 43
Danny Dainton Avatar answered Dec 18 '22 11:12

Danny Dainton