Python Cerberus JSON schema validation

367 views Asked by At

I have no clue why my code doesn't work, hence looking for some help.

That's my sample JSON array:

[
    {
        "bookingid": 1774
    },
    {
        "bookingid": 1020
    }
]

and my code is as follows:

def test_get_booking_ids_correct_schema():
    schema = {
        "type": "array",
        "items":
            {
                "properties":
                    {
                        "bookingid":
                            {
                                "type": "integer"
                            }
                    }
            }
    }

    response = requests.get("https://restful-booker.herokuapp.com/booking")
    response_body = response.json()

    v = Validator(schema)
    is_valid = v.validate(response_body)

    assert is_valid == True

and the error I'm getting is as follows:

        if not self.schema_validator(test_schema, normalize=False):
>           raise SchemaError(self.schema_validator.errors)
E           cerberus.schema.SchemaError: {'items': [{'properties': ['unknown rule']}], 'type': ['must be of dict type']}

Do you see any obvious mistake in my schema?

On the contrary, the code below works perfectly fine:

def test_temp():
    schema = {"origin": {"type": "string"}}
    json = {
        "origin": "185.21.87.131"
    }

    v = Validator(schema)
    is_valid = v.validate(json)

    assert is_valid == True

1

There are 1 answers

0
axel584 On

It's not possible to validate a document which is an array as root element. As you can see on : https://github.com/pyeve/cerberus/issues/220

by the way, the type array didn't exist in the Cerberus schema, you should use list instead.