How to check in json schema validation that response doesnt contains any extra fields that wasn't declorated by me in json schema validation?

Hello guys!
I have trouble in json schema validation.
I tried to use all of validators and i found that them doesn’t show error message, while response from api have some extra fields that was not declorated by me.

for example:

my code for validation

var schema = {
  "type": "array",
  "items": [
    {
      "type": "object",
      "properties": {
        "id": {
          "type": "string"
        },
        "serialNumber": {
          "type": "string"
        }
      },
      "required": [
        "id",
        "serialNumber"
      ]
    }
  ]
}

pm.test("Json Schema Validation", function () {
    pm.response.to.have.jsonSchema(schema);
});

pm.test("Verify Status Code is 200.", function () {
    pm.response.to.have.status(200);
});

Then i send request and api returns me this

[
    {
        "id": 1,
        "serialNumber": "TEST_TEST",
        "address": "string"
    }
]

And this validation send to me status of validation “PASSED”, while field address was not declorated as required field, and validator doesnt take a look at field address.

How i can check that response from API doesn’t contain any extra fields that goes through validation?

p.s. I tried to use
"additionalProperties": false in json schema , but it still shows same result as Passed.

Help me please!!

It’s probably where you put the additionalProperties. It goes straight after the “required” array.

var response = [
    {
        "id": "1",
        "serialNumber": "TEST_TEST",
        "address": "string"
    }
]

var schema = {
    "type": "array",
    "items": [
        {
            "type": "object",
            "properties": {
                "id": {
                    "type": "string"
                    },
                "serialNumber": {
                    "type": "string"
                    }
            },
            "required": [
                "id",
                "serialNumber"
            ],
            "additionalProperties": false
        }
    ],
}

pm.test("Json Schema Validation", function () {
    pm.expect(response).to.have.jsonSchema(schema);
});

Also the ID in your response is a number, not a string, so I had to change it to a string for it to pass.

3 Likes

Thanks mate! Solved!

Thank You for raising this & providing solution,
It helped & solved my problem.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.