Schema

The Schema class validates a dictionary of data against a set of validators — one validator per field.

Basic usage

from valify import Schema, StringValidator, IntValidator

schema = Schema({
    "name": StringValidator(min_length=2),
    "age":  IntValidator(min_value=0),
})

result = schema.validate({"name": "Alice", "age": 30})

Strict mode

By default extra fields in the data are silently ignored. In strict mode they raise ValidationError:

schema = Schema(
    {"name": StringValidator()},
    strict=True,
)

# Raises ValidationError — 'extra' is not in the schema
schema.validate({"name": "Alice", "extra": "field"})

Nested schemas

Schema inherits from Validator, so it can be used as a field value inside another schema:

address_schema = Schema({
    "city": StringValidator(),
    "pin":  StringValidator(min_length=6),
})

user_schema = Schema({
    "name":    StringValidator(),
    "address": address_schema,
})

Schema Utilities

Schema provides convenience methods for validation without raising exceptions.

is_valid()

Returns True if the provided data is valid and False otherwise.

Useful when you only need a success/failure check.

if schema.is_valid(data):
    process(data)

Valid data:

schema.is_valid({
    "name": "Darshan",
    "age": 21,
})

# True

Invalid data:

schema.is_valid({
    "name": "",
    "age": 15,
})

# False

errors()

Returns validation errors as a dictionary instead of raising ValidationError.

Useful for APIs, forms, CLIs, and other user-facing validation flows.

errors = schema.errors(data)

if errors:
    return {"errors": errors}

Example:

schema.errors({
    "name": "",
    "age": 15,
})

Output:

{
    "name": "Name cannot be empty",
    "age": "Value must be at least 18",
}

When validation succeeds:

schema.errors(valid_data)

# {}

Invalid root data

Schemas expect a dictionary as input.

schema.errors(["invalid"])

Output:

{
    "__root__": "Expected a dictionary, got 'list'"
}

API reference

class valify.schema.Schema(fields: dict[str, Validator], *, strict: bool = False)[source]

Bases: Validator

Validates a dictionary against a set of validators.

Parameters:
  • fields (dict) – A mapping of field names to Validator instances.

  • strict (bool) – If True, raise ValidationError for keys in the data that are not defined in the schema. Defaults to False.

Example

schema = Schema({

“name”: StringValidator(min_length=2), “age”: IntValidator(min_value=0, max_value=120),

})

result = schema.validate({“name”: “Alice”, “age”: 30}) print(result) # {“name”: “Alice”, “age”: 30}

errors(data: dict[str, Any]) dict[str, str][source]

Returns validation errors as a dictionary without raising.

Parameters:

data (dict) – The raw data to validate.

Returns:

A dictionary mapping field names to error messages. Empty dict means the data is valid.

Return type:

dict

Example

errors = schema.errors(data) if errors:

return {“errors”: errors},

classmethod from_example(example: dict[str, Any], _depth: int = 0) Schema[source]

Generate a Schema automatically from a sample data dictionary.

Inspects the type of each value and maps it to the appropriate validator. Supports nested dictionaries recursively.

Parameters:

example (dict) – A sample dictionary representing the expected data shape.

Returns:

A Schema instance with inferred validators.

Return type:

Schema

Example

schema = Schema.from_example({

“name”: “Alice”, “age”: 30, “email”: “alice@example.com”, “score”: 9.5, “active”: True,

}) schema.validate({

“name”: “Bob”, “age”: 25, “email”: “bob@example.com”, “score”: 8.0, “active”: False,

})

is_valid(data: dict[str, Any]) bool[source]

Checks if data is valid without raising.

Parameters:

data (dict) – The raw data to validate.

Returns:

True if valid, False otherwise.

Return type:

bool

Example

if schema.is_valid(data):

process(data)

to_json_schema() dict[str, Any][source]

Returns a JSON Schema representation of this validator.

Returns:

JSON schema fragment describing the validator.

Return type:

dict

validate(data: dict[str, Any]) dict[str, Any][source]

Validate a dictionary of data against the schema.

Parameters:

data (dict) – The raw data to validate.

Returns:

A new dictionary containing only the validated (and possibly coerced) values.

Return type:

dict

Raises:

Auto-generating Schemas

Use Schema.from_example() to automatically generate a Schema from a sample data dictionary:

schema = Schema.from_example({
    "name":    "Alice",
    "age":     30,
    "email":   "alice@example.com",
    "score":   9.5,
    "active":  True,
    "address": {
        "city": "Pune",
        "pin":  "411001",
    },
    "tags": ["python", "developer"],
})

# Automatically inferred:
# name    → StringValidator
# age     → IntValidator
# email   → EmailValidator
# score   → FloatValidator
# active  → BoolValidator
# address → nested Schema
# tags    → ListValidator(StringValidator)

result = schema.validate({
    "name":    "Bob",
    "age":     25,
    "email":   "bob@example.com",
    "score":   8.0,
    "active":  False,
    "address": {"city": "Mumbai", "pin": "400001"},
    "tags":    ["django", "fastapi"],
})