python-jsonschema / jsonschema

An implementation of the JSON Schema specification for Python
https://python-jsonschema.readthedocs.io
MIT License
4.58k stars 578 forks source link

Bug: checking required fields doesn't produce error when not present. #1173

Closed prakharcode closed 11 months ago

prakharcode commented 11 months ago

The validator currently doesn't check if a required field is present or not. According to the specification (here) it should be checked and validated accordingly.

code example:

from jsonschema import Draft4Validator
schema = {
            "$schema": "http://json-schema.org/schema#",
            "type": [
                 "object",
                 "null"
            ],
            "properties": {
                "type": {
                    "type": [
                        "string",
                        "null"
                    ],
                    "required": []
                }
            }
        }
record = {}
Draft4Validator(schema=schema).validate(record)

output:

expected: To produce an error for the required field type

Julian commented 11 months ago

Your schema does not require any properties, so none are required. Require type if you mean to do so, and then you'll get an error when it's missing:

>>> Draft4Validator(schema={'type': ['object', 'null'], 'properties': {'type': {'type': ['string', 'null']}}, "required": ["type"]}).validate(record)
Traceback (most recent call last):
  File "<stdin>", line 19, in <module>
  File "/Users/julian/.dotfiles/.local/share/virtualenvs/jsonschema/lib/python3.11/site-packages/jsonschema/validators.py", line 435, in validate
    raise error
jsonschema.exceptions.ValidationError: 'type' is a required property

Failed validating 'required' in schema:
    {'properties': {'type': {'type': ['string', 'null']}},
     'required': ['type'],
     'type': ['object', 'null']}

On instance:
    {}

All this is correct according ato the JSON Schema spec. (You linked RFC 2119 -- not sure why, it's not relevant to this.)

prakharcode commented 11 months ago

Hi Julian, thank you, for the input I was just looking into it and indeed the schema was wrongly defined. The example makes perfect sense.