I have an API field that is an enum, but it can also be null: fruit enum┃null Allowed: apple┃orange┃pear┃null
I need to create a JSON schema validation for this field to account for all of the possible cases. Based on several posts I found, I resolved it like this:
This format seems to please the Postman, so the validation passes and everything is great. However, the current solution is unable to raise an issue when an unknown value is found in the fruit field: if I was to replace apple → potato (the full set looking like this: [“potato”, “orange”, “pear”, null]) and the “apple” would be found in the response, the schema validation would still pass with no problems.
I’ve tried using “nullable” keyword, also specifying types as an array of “anyOf”, but still no luck. It’s either an “invalid schema” issue or faulty validation (not checking the actual values apart from null).
As for validating schema, I use the default validation method (if you can call it like that):
pm.response.to.have.jsonSchema(schema);
I have also marked this field as “required” in the schema description.
Hi, Mike! Appreciate your reply! You are correct - fruit really is a property in this scenario.
It was nice to learn that I don’t really need to specify the type - I removed the type declaration from my code.
However, the validation still doesn’t work in the correct way and I’m all out of ideas. Inside the same JSON, I have another enum property - status - that is not nullable, meaning it only has string values. Among the possible values there are “valid” and “expired”. When I remove “expired”, nothing happens and the validation passes, even though there are objects with “status”: “expired” present in the response. However, when I remove “valid”, I get the validation error that the field contains illegal value (“status”: “valid” can also be found in the response).
As for the “fruit”, it’s still not validating anything apart from the null itself.
It’s absolutely maddening and I’m unable to find a pattern here.
I think I found the root of this issue and it’s a really dumb one. I realized this when I started going through my schema definition line by line. My schema begins with the following code:
When experimenting with another field, Postbot assistant suggested a fix that solved some formatting bugs in the whole file, including the code snippet provided above. So the correct way to define a schema is as follows:
I violated the JSON format by adding array brackets while there was no need for that - the “type” property already specifies that.
While it yielded no errors, it seemed to mess with the validation of some fields, including enums.
I think the issue is resolved now, sorry for wasting your time with such a silly problem and thanks for all the help!